text
stringlengths
28
935k
meta
stringlengths
137
139
red_pajama_subset
stringclasses
1 value
\section{Introduction} The inscrutability of deep models has grown in tandem with their power \citep{doshi2017towards}, which has motivated efforts to interpret how these black-box models work \citep{sundararajan2017axiomatic, belinkov2019analysis}. Post-hoc interpretation aims to explain a trained model and reveal how the model arrives at a decision. This interpretability is achieved by interpreting a trained model in post-hoc ways \citep{molnar2020interpretable}. In recent years, various post-hoc interpretation methods have been proposed. Erasure-based method asserts contributions of features by measuring the change of output after these features removed \citep{li2016understanding, feng2018pathologies, chen2020generating}. Gradient-based method uses gradients to study the impact of different features on model output \citep{sundararajan2017axiomatic, wallace2019allennlp, hao2020self}. Attention-based method uses the magnitude of the attention weights as feature importance scores \citep{serrano2019attention, vashishth2019attention, hao2020self}. At the same time, these interpretation methods have received much scrutiny, arguing that the interpretations are fragile or unreliable \citep{alvarez2018robustness, pruthi2019learning, wang2020gradient, slack2020fooling}. Though the research on post-hoc interpretations has developed rapidly, one growing pain in this field is the difficulty in evaluating. This difficulty comes from the inherent properties of post-hoc interpretation: \emph{The reason humans need post-hoc interpretations is that human-readable reasoning process of deep models is inaccessible. However, this reasoning process is the ground truth in evaluating interpretations.} This contradiction led that post-hoc interpretations can only be evaluated indirectly. Papers provide diverse and sometimes non-overlapping evaluation methods to demonstrate their argument. However, there are some logic traps behind these evaluation methods, which are often ignored in most existing works. The lack of a clear statement on these traps has damaged the community in the following aspects: First, different evaluation methods may give rise to contradictory conclusions, which has caused many debates, such as the argument in using the magnitudes of attention weights as interpretations for transformer-based models \citep{wiegreffe2019attention, jain2019attention, pruthi2019learning, bastings2020elephant} and the rebuttal of gradient-based methods \citep{alvarez2018robustness, ghorbani2019interpretation, wang2020gradient, slack2020fooling}. Debates can play a positive role in the development of the community. However, many evaluation methods in these debates fall into crucial logic traps and draw conclusions recklessly. Without a unified understanding of logic traps in existing evaluation methods, these debates seem endless and will never get conclusions. Second, since some evaluation metrics are widely used, newly proposed work may be required to compare with other works using these metrics. However, the logic traps in these evaluation metrics may make the comparison unfair and not suitable for assessing the value of new work. Using evaluation metrics to make comparisons without considering the influence of the logic traps has caused unfair comparisons and unnecessary obstacles to new work. Last, the over-belief in evaluation gives rise to efforts to propose more "accurate" interpretation methods. However, due to the logic traps in existing evaluation methods, the performance improvement is under an unreliable evaluation system. We believe we should pay more attention to other aspects in this research field, such as reducing the impact of indirect evaluation, proposing new interpretation forms, and using interpretations to improve model performance. In this opinion piece, we summarize four kinds existing evaluation methods and point out the logic traps behind them. We believe a clear statement on these logic traps is important and helpful for the community. \section{Evalution Methods and Corresponding Logic Traps} \subsection{Using Human Explanation As the Ground Truth} In this evaluation, interpretations are compared with explanations given by humans. \subsubsection{Related works} Works often demonstrates the effectiveness of interpretations by giving examples consistent with human problem-solving process. For example, \citet{murdoch2018beyond} shows heat maps generated by different interpretation methods and argues their proposed method is better than others because only it can capture 'favorite' is positive, which is consistent with human understandings. Furthermore, works also use human-annotated labels to evaluate interpretations quantitatively. For example, besides sentence-level annotations for sentence classification, Stanford Sentiment Tree bank binary classification corpus (SST-2) \citet{socher2013recursive} provides word-level sentiment annotations. \citet{lei2016rationalizing, li2016understanding, tsang2020does, kim2020interpretation} evaluate interpretations by evaluating the consistency between interpretations and word-level sentiment annotations in SST-2. \subsubsection{Logic trap} \textbf{The decision-making process of neural networks is not equal to the decision-making process of humans.} \citet{jacovi2020towards} has discussed this issue and clarified the difference between faithfulness and plausibility, summarized as: \emph{The evaluation criterion should be how accurately the interpretation reflects the actual reasoning process (faithfulness), not how convincing the interpretation is to humans (plausibility).} \citet{jacovi2020towards} suggests the evaluation should not involve any human-judgment and human-provided labels. Different from \citet{jacovi2020towards}, we suggest that if an interpretation method does not use any human annotations, it can hardly generate plausible results to humans from chaotic. In this circumstance, the plausibility of interpretations can be seen as coming from the reasoning process of deep models, and it can reflect the faithfulness of interpretations. However, plausibility can not be used as a quantitative evaluation criterion. Because neural networks often rely on unreasonable correlations, even when producing correct decisions. Interpretations preposterous to humans may be consistent with the actual reasoning process of deep models. \subsection{Evaluating by Perturbing Features and Calculating Output Change} Since human annotations are not suitable for quantitative evaluation, researchers design diverse evaluation metrics for quantitatively evaluating interpretations. One of the most widely used is perturbing features and calculating output change. For example, evaluation metrics based on the area over the perturbation curve (AOPC) \citep{samek2016evaluating} first define an ordered $set_{O} = \left \{feature1, feature2, … \right \}$ according to interpretations, in which features at the front attribute more to the model outputs. Then perturb the top $k\%$ features and calculate the average change in the model outputs as AOPC(k). Higher AOPC(k) is better, which means that the features selected by interpretations are essential. The perturbing strategy and functions used to calculate output change diverse among different works. \subsubsection{Related works} Many works \citep{samek2016evaluating, shrikumar2017learning, chen2018shapley, nguyen2018comparing, nguyen2018comparing, deyoung2019eraser, chen2020generating, kim2020interpretation, chen2020learning} use this kind of method to perform evaluation and comparison. For example, \citet{chen2020generating} chooses masking tokens as perturbation and use subtraction and log-odds as calculation functions; \citet{shrikumar2017learning} chooses erasing pixels as perturbation and uses log-odds as calculation function. \subsubsection{Logic trap} \textbf{This evaluation is using interpretations to evaluating interpretations.} Assigning importance for features by calculating output change after perturbing is an interpretation method too. For example, when using erasing one token per time as the perturbing strategy, AOPC(k) degenerates into interpretation method: \textbf{leave-one-out} \citep{li2016understanding}. This evaluation measures how similar two interpretations are, and the one used as the ground truth is determined by the perturbing strategy. For example, \citet{chen2020generating} uses AOPC(k) as evaluation metric, choosing k = 20 and erasing tokens as perturbation. Not surprisingly, erasure-based methods perform well in their evaluation, and even the most simple leave-one-out method generates competitive results. \citet{kim2020interpretation} proposes the out-of-distribution (ODD) problem of erasure-based interpretation methods. Since their proposed interpretation method can be seen as a remedy to the ODD problem caused by erasing tokens, the commonly used perturbing strategy: erases tokens directly, is not suitable for evaluating their proposed method. \citet{kim2020interpretation} also mention it in their paper. Unfortunately, they did not discuss this in-depth but chose to use a perturbing strategy more similar to their proposed method, causing unfair comparison in their favor. The widespread use of such evaluation metrics has negatively impacted the research field, and the logic trap behind them has not been proposed. We should not use any such metrics to perform the comparison. If we have a method that can get feature importance as the ground truth, why do we need other interpretation methods to get feature importance? \subsection{Evaluating the Consistency after Perturbing Inputs} In this evaluation, works evaluate interpretations by inspecting the consistency of interpretations after perturbing the inputs. The argument is that if the interpretation method is reliable, similar inputs giving rise to the same predictions should have similar interpretations. \subsubsection{Related works} This evaluation is often used to disprove the effectiveness of interpretation methods. \citet{alvarez2018robustness} argues that a crucial property that interpretations should satisfy is robustness to local perturbations of the input. They assert that current popular interpretation methods are not robust. \citet{kindermans2019reliability} finds that by adding a constant shift to the input data, a transformation with no effect on the model prediction can significantly affect interpretation methods. They assert these interpretations are unreliable. \citet{ghorbani2019interpretation} argues that interpretations of neural networks are fragile by showing that systematic perturbations can lead to dramatically different interpretations without changing the label. \citet{ding2021evaluating} evaluates interpretations' faithfulness through model consistency test. They perform substitutions in the input and measure the consistency of feature importance. \subsubsection{Logic trap} \textbf{The success of attacking interpretations may be a result of attacking deep models.} First, similar inputs in human eyes are not equal to similar inputs for deep models. It is well known that deep models are susceptible to adversarial attacks \citep{goodfellow2014explaining, papernot2016limitations, moosavi2016deepfool}. The adversarial attacks deliberately add some subtle interference that people cannot detect to the input sample, causing the model to give a wrong output with high confidence. The success in adversarial attacks on deep models demonstrates a indistinguishable change in human eyes can cause a very different reasoning process in deep models. Second, since deep models' prediction has compressed the complicated calculation process into limited categories, giving the same prediction is a very weak constraint to constrict the reasoning process of deep models. For example, there is always half probability of giving the same prediction for a binary classification task even with a random reasoning process. Thus, it is no surprise that adversarial attacks can find similar input, which causes the same prediction but a different reasoning process. The risk underlying this evaluation is the success of attacking interpretations may be a result of attacking the deep models, as shown in Figure \ref{F5}, in which we use the path from input to output to represent the reasoning process of deep models visually. Unfortunately, existing works ignore this risk and use adversarial methods to attack interpretations. Not surprisingly, all of them get similar conclusions that existing interpretation methods are fragile or unreliable. \begin{figure}[htb] \centering \includegraphics[width=0.99\linewidth]{emnlp.png} \caption{Adversarial attacks on deep models can cause similar inputs with different reasoning processes. Circumstance in (b) may be regarded as a successful attack on interpretations, which falls into the logic trap.} \label{F5} \end{figure} \subsection{Manipulating Interpretations} In this evaluation, works prove the unreliability of interpretations by manipulating them and letting the manipulated interpretations focusing on some special features or ignoring some crucial features. \subsubsection{Related works} \citet{jain2019attention} randomly permutes the attention distributions and searches for maximally different attention distributions that still produce a similar prediction. They claim that attention distributions can not be interpretable because they are not exclusive. \citet{wang2020gradient} trains an extra model with uniform predictions but large gradients for some particular words. They add this extra model to the original model. Since the extra model generates uniform predictions, predictions of the merged model are dominated by the original model. However, the gradients are influenced by the extra mode. \citet{slack2020fooling} trains a classifier to distinguish if the inputs are perturbed instances and uses a different sub-model to process perturbed instances. This way, they can control the interpretations of perturbation-based methods such as LIME and SHAP and assert they are not reliable. \subsubsection{Logic trap} \textbf{The goal of interpretation methods is confused.} We suggest the goal of interpretation methods is confused in their works. Traditional models such as the linear regression model and the decision trees are regarded as interpretable models because their calculation process is easy to analyze. The interpretations of them is based on manual analysis of their calculation process. The deep model is regarded as a black-box model because its calculation process is too complicated to understand and analyze directly, not because its calculation process is inaccessible. Thus, requiring interpretation methods for deep models to give interpretations without access to the calculation process and manual analysis is unfair. The goal of interpretation methods is to help humans understand and analyze a trained deep model, not automatically generate interpretations for any system containing deep models. The manual added pipeline structures in \citet{wang2020gradient} and \citet{slack2020fooling} can be easily understand by humans and there is no need to use interpretation methods to interpret these structures. The manipulation of interpretations in their works will easily fail when manual analysis involved. \citet{jain2019attention} confuses the interpretation goal because the deep model is damaged in their work. The neural network works as a whole and its parameters are interdependent. Assigning the attention weights generated by parts of the model makes the rest of the model meaningless. The interpretation target in their work can not even be regarded as a trained model, which makes their manipulation meaningless. \subsection{Conclusions} The intrinsic properties of post-hoc interpretations make it cannot be directly evaluated, and there are some crucial logic traps in existing evaluation methods. These logic traps have been ignored for a long time and have brought negative effects to the community. We suggest a clear statement about these traps is important and helpful. Since the logic traps in existing evaluation methods can cause inaccurate evaluation and unfair comparison, we should not focus on improving the performance under an unreliable evaluation system. Other aspects of this field should give rise to more attention, such as the applications of post-hoc interpretations, alleviating the influences of indirect evaluation, and proposing new interpretation forms.
{'timestamp': '2021-09-14T02:20:32', 'yymm': '2109', 'arxiv_id': '2109.05463', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05463'}
arxiv
\section{Introduction} The human gut microbiome is the genetic content of all bacteria, archaea, viruses, and eukaryotic microbes residing in the human gut and is commonly used to profile the composition of the gut microbiota. Advances in next-generation sequencing techniques have substantially reduced the cost of this approach and made it widely accessible. One cost-effective microbiome profiling strategy is based on targeting a single marker gene, the 16S ribosomal RNA (rRNA) gene, through amplicon-based sequencing \citep{2015_Li}. A more expensive, but more precise, approach is whole-genome shotgun metagenomic sequencing \citep{1997WeberMyers}. Traditionally, sequencing reads have been clustered into Operational Taxonomic Units (OTUs), which serve as the basic unit of microbial taxa. Recently, amplicon sequencing variants (ASVs) have come into wider use as they can achieve more precise characterization of microbial species and resolve the sample-specificity issue of the OTU \citep{2017_Callahan}. Our work is applicable to either method of characterizing microbial taxa; in the following we shall generically refer to the basic unit as ASVs. Gut microbiome studies often involve highly heterogeneous samples due to the multitude of factors that can influence an individual's gut microbiota. A useful data analytical strategy for microbiome compositions is to sort microbiome samples into clusters characterized by particular compositional signatures. In the context of gut microbiome, these clusters are called ``enterotypes'' \citep{2011SiezenKleerebezem} and are associated with health outcomes \citep{2014_Chierico}. One of the most popular microbiome clustering methods is the Dirichlet-multinomial mixture (DMM) model \citep{2000_Nigam,2012_Holmes}, which uses a hierarchical structure to allow within-cluster cross-sample variability in subcommunity compositions. However, the DMM is too restrictive to realistically characterize the within-cluster cross-sample variance in microbiome data \citep{2017_Wang,2018_Tang} as it uses a single scalar parameter to characterize the entire covariance structure across all microbial taxa. More general methods have recently been introduced to alleviate, though not eliminate, this limitation through the use of Dirichlet-tree models \citep{1991Dennis,2017_Wang}. Such clustering analysis, however, makes the implicit assumption that each microbiome sample must belong to a {\em single} signature ``community'' characterized by the cluster centroid. This assumption is often unrealistic and overly restrictive for complex environments such as the gut microbiome \citep{2012_Holmes, 2020_Mao}. Recent developments embrace the more relaxed biological hypothesis that the ASVs characterizing a microbiota sample hail from a combination of multiple microbial ``clusters'', or more precisely ``subcommunities''. Mixed-membership (MM) models are generalizations of clustering models that provide a generative modeling framework for data involving subcommunity structure as they allow each sample to be composed of multiple subcommunities. \cite{2019_Sankaran} applied the most well-known MM model, latent Dirichlet allocation (LDA), to microbiome profiling. Earlier, \cite{2015_Shafei} and \cite{2020_Deek} proposed variations of LDA accounting for environmental factors and inflated zero-counts, respectively, in the microbiome context. The key motivation for our paper is the observation that existing MM models such as LDA and its variations---originally developed for other contexts such as topic modeling \citep{2003_Blei} and population genetics \citep{2000_Pritchard}---do not incorporate key features of microbiome compositions. Most notably, they assume that a microbial subcommunity's composition must remain {\em exactly the same} across all samples. This is unrealistic in the vast majority of microbiome studies collected from diverse environments such as the gut where samples often possess large heterogeneities \citep{2018_Tang,2021JeganathanHolmes}. It is interesting to note that such heterogeneity has been well-recognized in clustering models for microbiome data \citep{2012_Holmes,2020_Mao}, but has been largely ignored in existing MM models. Additionally, choosing the number of subcommunities for LDA is not trivial in the presence of cross-sample heterogeneity, and LDA-based approaches often lead to overestimates in the number of subcommunities in microbiome applications \citep{2021Fukuyamaetal}. We introduce a generalization of LDA that aims to appropriately incorporate cross-sample heterogeneity, or ``random effects", in microbiomal subcommunity compositions due to unmeasured sources, thereby leading to more accurate identification of subcommunities in MM models. Our approach takes advantage of the availability of a natural tree structure relating the microbial taxa---the phylogenetic tree---which allows us to decompose the compositional vector into a collection of binomial observations on the tree nodes. This transform serves two purposes. First, it allows us to model the heterogeneity by modeling the vector of log-odds transforms of the binomial probabilities at each node as Gaussian. By modeling the subcommunity compositions as realizations from this logistic-tree normal (LTN) \citep{2021_Wang} distribution, we are able to impose constraints on the underlying covariance structure to ensure the identifiability of the subcommunities. A second purpose of the tree-based transform is computational. By utilizing the P\'olya-Gamma (PG) data augmentation technique \citep{2013_Polson}, Bayesian inference under the resulting MM model can be readily accomplished through fully conjugate collapsed blocked Gibbs sampling. We term our new model logistic-tree normal latent Dirichlet allocation (LTN-LDA). Several other relevant prior works are worth mentioning. Graph-Sparse LDA \citep{2015DoshiVelezetal} also incorporates random effects from subcommunity-to-subcommunity using a tree structure. However, in the context of microbiome compositions, it would assume that every node of the tree is an ASV which can occur in a sample and is thus incompatible with the phylogenetic tree. Other tree-based MM methods include \cite{2007TamSchultz}, which uses trees to model the abundance of subcommunities in samples, and \cite{2009Andrzejewskietal}, which uses mixtures of trees to model subcommunity composition by explicitly modelling which ASVs must co-occur and which cannot. In the following, we will briefly review the LDA and LTN models before introducing the LTN-LDA model. We will augment the LTN-LDA model using a class of auxiliary P\'olya-Gamma variables \citep{2013_Polson} and present a collapsed blocked Gibbs sampler for carrying out fully Bayesian inference. We will demonstrate in simulations that, in the presence of cross-sample heterogeneity, inference by LTN-LDA is robust with respect to overspecifying the number of subcommunities while inference by LDA can be highly sensitive to the choice of the number of subcommunities. We apply LTN-LDA to the dataset of \cite{2011_Dethlefsen}, which has been used for demonstrating MM models in the microbiome settings \citep{2019_Sankaran}, and compare our results to LDA. \section{Methods} \subsection{Latent Dirichlet allocation} Let there be $D$ samples consisting of counts of $V$ unique ASVs indexed by $1,2,\ldots,V$. For sample $d$, let $\mathbf{x}_d = (x_{d,1} ,\dots, x_{d,V})$ be the vector of ASV counts such that $x_{d,v}$ is the total count for ASV $v$ in sample $d$. Let $N_{d} = \sum_{v=1}^V x_{d,v}$ be the sum of counts in sample $d$, which is determined by the sequencing depth. Subcommunities are defined to be collections of ASVs that co-occur in samples at given relative proportions. An ASV can occur in multiple subcommunities at various abundances and the key assumption underlying an MM model, in contrast to a clustering model, is that different instances (i.e., different sequencing reads) of the same ASV in a sample can arise from the participation of that ASV in multiple microbial subcommunities. Key parameters of interest in MM models are subcommunity abundance, i.e., the proportions of the various subcommunities in each sample, and subcommunity composition, i.e., the proportions of the ASVs in each subcommunity. To describe LDA, it is convenient to introduce categorical indicators for each read and its associated subcommunity identity. For $d=1,2,\ldots,D$, let $\mathbf{w}_d$ be a vector $\mathbf{w}_d = (w_{d,1},\dots,w_{d,N_d})$ where $w_{d,n}\in \{1,2,\ldots,V\}$ is the categorical indicator of the ASV associated with the $n$th read in the sample. We refer to the elements $w_{d,n}$ in this vector as ``tokens" to draw analogy with topic modelling. There, each token is a word in a document; here, each token corresponds to a read in a sample. We also note that $x_{d,v}=\sum_{n=1}^{N_d} \mathbf{1}_{\{w_{d,n}=v\}}$. Let $\bm{\phi}_d=(\phi_{d}^1,\phi_{d}^2,\ldots,\phi_{d}^K)' \in \Delta^{K-1}$, where $\Delta^{S}$ is the $S$-dimensional simplex, be the subcommunity abundance vector. That is, $\phi_{d}^k$ represents the relative abundance of subcommunity $k$ in sample $d$, and so $\bm{\phi}_d$ specifies the categorical distribution of each token over the $K$ underlying subcommunities in sample $d$. Let $z_{d,n}$ represent the subcommunity from which the $n^{th}$ token in sample $d$ arises from and let $\mathbf{z}_d$ be the vector all such assignments for sample $d$. Also, let $\bm{\beta}_k=(\beta_{k}^1,\beta_{k}^2,\ldots,\beta_{k}^V)' \in \Delta^{V-1}$ be the subcommunity composition for subcommunity~$k$. That is, $\bm{\beta}_k$ gives the relative proportions of the $V$ unique ASVs in subcommunity $k$. For $d=1,\dots,D$ and $n=1,\dots,N_d$ and while $\bm{\alpha}$ and $\bm{\gamma}$ are hyperparameters, the LDA model (Figure~$\ref{fig:graph_lda}$) \citep{2003_Blei} is then \\ \[ \begin{aligned} w_{d,n}\,|\,z_{d,n},\bm{\beta}_{z_{d,n}} &\stackrel{\mathrm{ind}}{\sim} {\rm Cat}(\bm{\beta}_{z_{d,n}}) & z_{d,n}\,|\,\bm{\phi}_d &\stackrel{\mathrm{ind}}{\sim} {\rm Cat}(\bm{\phi}_d) \\ \bm{\phi}_d\,|\,\bm{\alpha} &\stackrel{\mathrm{iid}}{\sim} {\rm Dir}(\bm{\alpha})& \bm{\beta}_k\,|\,\bm{\gamma} &\stackrel{\mathrm{iid}}{\sim} {\rm Dir}(\bm{\gamma}). \end{aligned} \] Though LDA can be applied in the microbiome context \citep{2019_Sankaran}, it does not account for cross-sample heterogeneity in subcommunity composition. In particular, it assumes that the $\bm{\beta}_k$ are the {\em exact same} across all samples. This is inconsistent with the empirical behavior of the microbiome where large cross-sample heterogeneities exist \citep{2012_Holmes}. LDA thus tends to interpret cross-sample heterogeneity as the presence of additional subcommunities. \subsection{Incorporating cross-sample heterogeneity} We shall enrich the LDA framework to allow the subcommunity compositions to vary across samples. There are several hierarchical models for microbiome compositions such as the Dirichlet-Multinomial (DM) model \citep{2000_Nigam,2012_Holmes} and Aitchinson's log-ratio based normal (LN) models \citep{1982_Aitchison}, which could be embedded into LDA for this purpose. However, the DM is highly restrictive in its ability to characterize the underlying cross-sample variability as the Dirichlet distribution has only one scalar variance parameter, while the LN models are computationally challenging due to lack of conjugacy to the multinomial sampling model. To resolve these difficulties, we adopt the recently introduced logistic-tree normal (LTN) model \citep{2021_Wang}. In particular, we will show that the LTN model can be embedded into the LDA model to accommodate cross-sample heterogeneity and that posterior inference can be accomplished through simple collapsed blocked Gibbs sampling using a data-augmentation technique called P\'olya-Gamma augmentation. Moreover, since the adoption of the LTN model requires specifying a dyadic partition tree on the ASVs, the phylogenetic tree relating the taxa is a natural choice. \subsubsection{The phylogenetic tree} Let $\mathcal{T}$ denote a phylogenetic tree capturing genetic similarities between the observed ASVs. The leaf nodes in the tree correspond to the observed ASVs in the data set. Each interior node is the inferred common ancestral taxon for the ASVs lying in the corresponding descendant subtree at the node. Each node (or taxon) $A$ in the phylogenetic tree $\mathcal{T}$ can be represented by the collection of its descendant ASVs. In particular, each leaf node $A$ contains a single ASV, whereas each internal node $A$ contains multiple ASVs. In the following, we let $\mathcal{I}$ be the set of internal nodes. Throughout this work, we shall assume that the phylogenetic tree is rooted and binary in the sense that each $A\in\mathcal{I}$ has exactly two child nodes (i.e., direct descendants): let $A_l$ and $A_r$ be the left and right children of $A$, respectively. \subsubsection{The logistic-tree normal model} We shall adopt the logistic-tree normal (LTN) model \citep{2021_Wang} as the sampling model for the ASV count distribution within each subcommunity. LTN is a distribution on a tree-based log-odds transform of the categorical probabilities $\bm{\beta} = (\beta^1,\beta^2,\ldots,\beta^V)' \in \Delta^{V-1}$. Specifically, given the phylogenetic tree $\mathcal{T}$, for each interior node we define $\theta(A) = \frac{\sum_{v\in A_l}\beta^v}{\sum_{v\in A}\beta^v}$: the probability that a token belongs to an ASV in $A_l$ given that it belongs to an ASV in $A$. The collection of $\theta(A)$ on all $A\in\mathcal{I}$ gives an equivalent reparametrization of $\bm{\beta}$. In Figure~$\ref{fig:toy_trees}$ we plot an example phylogenetic tree over $6$ ASVs with labelled nodes (Figure~$\ref{fig:toy_tree}$) and with labelled $\beta^v$ and $\theta(A)$ (Figigure~$\ref{fig:labelled_toy_tree}$) to demonstrate the link between the $\beta^v$ and the $\theta(A)$. After taking the logit transform of these binomial probabilities on the tree nodes, $\psi(A) = \log \frac{\theta(A)}{1-\theta(A)}$, let $\bm{\psi}$ be the vector of $\psi(A)$ with respect to an ordering on the $p$ internal nodes of $\mathcal{T}$. LTN is simply a Gaussian model on these tree-based log-odds: $\bm{\psi} \, | \, \bm{\mu},\Sigma \stackrel{\mathrm{iid}}{\sim} {\rm MVN}(\bm{\mu},\Sigma)$ for some mean $\bm{\mu}$ and covariance $\Sigma$ parameters that specify the overall average profile of the count distribution and the cross-sample variability. Posterior computation under LTN, which we will describe later, relies on an equivalent representation of the categorical sampling on the leaves of the tree as a collection of sequential binomial experiments on the internal nodes of the tree. Specifically, generating a categorical draw from the probability vector $\bm{\beta}$ can be achieved by sequentially ``dropping'' the token from top-to-bottom along the phylogenetic tree: at each node determine whether the token belongs to the left or right child node with probabilities $\theta(A)$ and $1-\theta(A)$, respectively. More formally, for each node $A\in\mathcal{T}$, we use $y(A)$ to denote the total counts associated with the ASVs descended from node $A$. That is, $y(A) = \sum_{n=1}^{N} 1_{w_{n}\in A}$ where $w_n$ represents the $n$th count. Generating a multinomial count vector with probabability $\bm{\beta}$ can be achieved by sequentially drawing $y(A_l)$ given $y(A)$ from $\text{Bin}(y(A_l)\,|\,y(A),\theta(A))$. Putting the pieces together, and letting ${\rm expit}(\psi)=1/(1+e^{-\psi})$, LTN is the following generative model: for all internal nodes $A\in \mathcal{T}$, \[ \begin{aligned} y(A_l)\,|\,y(A),\psi(A) &\stackrel{\mathrm{ind}}{\sim} {\rm Bin}(y(A),\theta(A)={\rm expit}(\psi(A))) & \text{ and } \quad \bm{\psi}\,|\,\bm{\mu},\Sigma &\stackrel{\mathrm{ind}}{\sim} {\rm MVN}(\bm{\mu},\Sigma). \end{aligned} \] \subsection{LTN-LDA} We incorporate the LTN model into LDA to allow cross-sample heterogeneity in subcommunity compositions. The resulting model is termed logistic-tree normal latent Dirichlet allocation (LTN-LDA). Specifically, for $d = 1,\dots,D$, $k=1,\dots,K$, $n=1,\dots,N_d$, and $A\in \mathcal{I}$, where the subscripts $d$, $k$, and $n$ indicate the corresponding quantities associated with the $d$th sample, $k$th subcommunity, and $n$th read, the model is as follows \\ \[ \begin{aligned} y_{d,k}(A_l)\,|\,y_{d,k}(A),\psi_{d,k}(A) &\stackrel{\mathrm{ind}}{\sim} {\rm Bin}(y_{d,k}(A),\text{expit}(\psi_{d,k}(A))) \\ y_{d,k}(A) & =\sum_{n=1}^{N_d} 1_{z_{d,n}=k}1_{w_{d,n}\in A} & z_{d,n}\,|\,\bm{\phi}_d &\stackrel{\mathrm{ind}}{\sim} {\rm Cat}(\bm{\phi}_d)\\ \bm{\phi}_d \,|\, \bm{\alpha} &\overset{\text{iid}}{\sim} {\rm Dir}(\bm{\alpha})& \bm{\psi}_{d,k}\,|\,\bm{\mu}_k,\Sigma_k &\stackrel{\mathrm{ind}}{\sim} {\rm MVN}(\bm{\mu}_k,\Sigma_k), \\ \bm{\mu}_k \,|\, \bm{\mu}_0, \Lambda_0 &\overset{\text{iid}}{\sim} {\rm MVN}(\bm{\mu}_0,\Lambda_0) & \Sigma_k \,|\, {\rm G} &\overset{\text{iid}}{\sim} {\rm G} \end{aligned} \] Note that we also endowed the subcommunity mean $\bm{\mu}_k$ and covariance $\Sigma_k$, with corresponding priors ${\rm MVN}(\bm{\mu}_0,\Lambda_0)$ and $G$, which will be specified later. Figure~$\ref{fig:graph_ltn_lda}$ provides the graphical model representation for this full hierarchical model. The key distinction between LTN-LDA and LDA is that LTN-LDA uses a hierarchical kernel, namely LTN, to model cross-sample heterogeneity. In particular, the composition in sample $d$ of subcommunity $k$ is determined by $\bm{\psi}_{d,k}$ and is explicitly allowed to vary across samples. Without additional constraints on the high-dimensional covariance matrices for each subcommunity, $\Sigma_k$, the model is too flexible \citep{2009HaffariTeh}, and can become unidentifiable. Additional structural constraints serving the purpose of regularization on the covariance structure are thus necessary and so we assume that $\Sigma_k$ is a diagonal covariance matrix. An LTN distribution with diagonal covariance is similar in distributional properties to a Dirichlet-tree multinomial (DTM) distribution \citep{1991Dennis,2017_Wang} but is computationally more efficient because there are no known conjugate priors for the mean and variance parameters under the DTM model. While this limitation is manageable when the DTM is used as a standalone model or the top layer in a hierarchical model, when embedded as a kernel within an MM model such as LDA the incurred numerical computational cost becomes prohibitive. (For more details, see Supporting Information S1.) While the covariance constraint may appear strong, we note that the dependence among the tree-based log-odds ratios is generally much weaker than the complex dependence structure among the ASV counts themselves. In a sense, the tree-based log-odd transform of the abundance vectors ``decorrelates'' the data. For the interested reader, this decorrelation phenomenon is analogous to the so-called ``whitening'' effects in wavelet analysis \citep{2008Nason}, as the dyadic tree transform we incorporate here is the counterpart of Haar-wavelet transform on functions. (In Supporting Information Section~S2 we investigate the effects of relaxing the diagonal covariance to a blocked diagonal covariance, and the results show that the additional sophistication does not lead to noticeable improvement in the inference.) Aside from the diagonal covariance, we also assume that the amount of variability for each node depends on that node's distance to the bottom (i.e., leaf) level of the tree. In particular, we assume that taxa close to the bottom of the phylogenetic tree have larger cross-sample variability in the corresponding log-odds ratio than those which are distant. This is motivated by the biological intuition that taxa close to each other on deep levels of the phylogenetic tree tend to have comparable functionality; the relative proportions of such taxa thus often display elevated levels of variance \citep{2021JeganathanHolmes}. Specifically, let $|A|$ measure the distance of $A$ from the leaf level by denoting the number of leaves descended from node $A$. For $i = 1,\dots,p$, $k = 1,\dots, K$, $C\in\mathbb{N}$ (a tuning parameter), and $\bm{\tau}_k = (\tau_{k}^1,\dots,\tau_{k}^p)$, the prior we adopt has the form $\Sigma_k \,|\, \bm{\tau}_k = \text{diag}(\bm{\tau_{k}})$ where \[ \tau_{k}^i\,|\,a_1,a_2,b \stackrel{\mathrm{iid}}{\sim} \begin{cases} \text{IG}(a_1,b) & |A_i| \geq C \\ \text{IG}(a_2,b) &|A_i| < C \\ \end{cases} \] We default to $(a_1,a_2,b) = (10^4,10,10)$ and note that while we still refer to the $\psi_{d,k}$ as being drawn from a multivariate normal distribution, we have $\psi_{d,k}^i \, | \, \mu_k^i,\tau_k^i \stackrel{\mathrm{iid}}{\sim} \text{N}(\mu_k^i,\tau_k^i)$. This choice of priors ensures conjugate updating and avoids identifiability issues. Further, it partitions the internal nodes of the tree in two: we shall refer to these sets as the upper tree $\mathcal{U} = \{A\in\mathcal{I}:|A|\geq C\}$ and the lower tree $\mathcal{L} =\{A\in\mathcal{I}:|A| < C\}$. In $\mathcal{U}$, the hyperparameters $a_1$ and $b$ are such that the $\tau_{k}^i$ will be small and the $\psi_{d,k}^i$ will vary little around $\mu_k^i$; in $\mathcal{L}$, the hyperparameters $a_2$ and $b$ are such that the $\tau_k^i$ are allowed to be large and the $\psi_{d,k}^i$ can vary significantly across samples. This implies that if $A_c$ is the child of $A$, and $A_c\in\mathcal{L}$ but $A\in\mathcal{U}$, then all ASVs descended from $A_c$ can substitute for each other across samples in a given subcommunity. We call sets of ASVs which are allowed to substitute for each other substitution sets. All ASVs are either part of a substitution set or singletons. The tree structure is critical to how LTN-LDA models cross-sample heterogeneity, and we include an analysis on the robustness to misspecified trees in Supporting Information S3. \subsection{Bayesian inference by collapsed blocked Gibbs sampling} While the LTN-LDA model is not conditionally conjugate by itself, one can restore conjugacy by introducing a class of P\'olya-Gamma latent variables \citep{2013_Polson} $v_{d,k}(A)$ --- one for each interior node $A$ --- which are independent of $y_{d,k}(A_l)$ conditioned on $y_{d,k}(A)$ and $\psi_{d,k}(A)$: $v_{d,k}(A)\,|\,y_{d,k}(A),\psi_{d,k}(A) \sim {\rm PG}(y_{d,k}(A),\psi_{d,k}(A))$. The full conditional for $\psi_{d,k}(A)$ is then proportional to $\exp\left({(y_{d,k}(A_l) - \frac{y_{d,k}(A)}{2})\psi_{d,k}(A) - \frac{v_{d,k}(A)\psi_{d,k}(A)^2}{2}}\right)$, which takes a quadratic form in the exponent and thus is conjugate to the Gaussian model on $\psi_{d,k}(A)$. The graphical model for LTN-LDA with the P\'olya-Gamma variables is presented in Figure $\ref{fig:graph_ltn_lda_pg}$. To speed up the sampling of P\'olya-Gamma variables we adopt an approximate sampler proposed by \cite{2019_Glynn} for $y_{d,k}(A) \geq 30$. Further, we integrate $\bm{\phi}_d$ out of the sampling model to improve convergence as in \citep{2004_Griffiths}. The algorithm scales linearly with $D$, $K$, $V$, and $N_d$. (For details, see Supporting Information S4.) \section{Numerical experiments} \subsection{Robustness in choosing the number of subcommunities} The true number of subcommunities $K$ in a given dataset is typically unknown and it is common to treat $K$ as a tuning parameter. However, for data with large cross-sample heterogeneity such as microbiome data, intuition suggests that a model assuming zero heterogeneity will confuse sample-specific variation around a subcommunity mean with the presence of additional subcommunities. This results in difficulty estimating $K$ and inference sensitive to $K$; indeed, LDA encounters both of these difficulties \citep{2021Fukuyamaetal}. To verify this intuition, we generated data from a known LTN-LDA model which induces cross-sample heterogeneity. In particular, we simulated $D = 50$ samples, and $N_d = 10,000$ reads per sample; we set $\alpha = 1$, $\mu = 0$, $\Lambda = I$, $a_1 = 10^4$, $a_2=b=10$, and $(K,C) = (4,5)$. The underlying phylogenetic tree is presented in Supporting Information S5: there are $V = 49$ ASVs. We then contrasted LDA and LTN-LDA by running Gibbs samplers on the data generated above with $K\in\{4,5,7,10\}$ and $C = 5$. In the left part of Figure~$\ref{fig:Sim_Case_K_10_Mult_Plots}$, we plot the posterior means of the subcommunity abundances $\bm{\phi}_d$ for both LDA and LTN-LDA. We corrected for label switching and estimated the $\bm{\phi}_{d}$ as in \cite{2004_Griffiths}. With $K$ set to truth, LDA performs comparably to LTN-LDA in estimating the true values of $\bm{\phi}_d$; however, as we increase $K$, the inference provided by LDA worsens. While it still recovers the abundances for subcommunities $1$ and $2$, it does a worse job at recovering subcomunities $3$ and $4$. Moreover, LDA detects the presence of additional subcommunities which do not exist in the true generative model. LTN-LDA, in contrast, is remarkably stable when $K$ is overspecified. No matter the modelled value of $K$, it detects the four true subcommunities with approximately the same abundances while estimating that additional subcommunities have little abundance. For $K = 10$, we plotted the subcommunity compositions on the right part of Figure~\ref{fig:Sim_Case_K_10_Mult_Plots}. For LTN-LDA, distributions for the $\bm{\beta}_{d,k}$ are in blue and the $\bm{\beta}_k$ are in red; the LDA $\bm{\beta}_k$ distributions are in black. LTN-LDA finds moderate levels of cross-sample heterogeneity in subcommunity $2$, and a high levels in samples $3$ and $4$. These figures imply that LDA is able to recover the subcommunity abundances only for those subcommunities with low cross-sample heterogeneity. LDA fails to recover the subcommunity abundances for those subcommunities with high cross-sample heterogeneity, mistaking heterogeneity for additional subcommunities. In effect, LDA splits true heterogeneous subcommunities into many smaller subcommunities with no heterogeneity and ASVs which ought to belong in the same subcommunity are separated. LTN-LDA, on the other hand, provides stable and accurate inference as the modelled $K$ increases. This thus confirms our intuition about the behavior of LDA in the presence of cross-sample heterogeneity. \subsection{Predictive scoring as a device for choosing tuning parameters} While incorporating cross-sample heterogeneity enhances the robustness of LTN-LDA to overspecifying the number of subcommunities, it is still useful to have a generally applicable strategy for setting the tuning parameters for LTN-LDA: $K$ and $C$. One option is to use out-of-sample predictive performance to identify suitable choices of the tuning parameters. A popular performance measure for MM models is perplexity \citep{2009_Wallach}: a transform of out-of-sample predictive likelihood such that lower perplexity is preferred. We thus implement the simple strategy of computing the average out-of-sample perplexity score for different choices of $(K,C)$ and examine whether that can lead to a practical way of choosing these parameters. We will also examine whether this strategy could be adopted for models without cross-sample heterogeneity, namely LDA, to alleviate their limitations. We follow the procedure in Section~$5.1$ of \cite{2009_Wallach} for computing the perplexity for LDA, and generalize that strategy to LTN-LDA. (For deatils, see Supporting Information S6.) We generated 200 simulated datasets. In each, there are $D = 50$ samples and $N_d = 10,000$ counts per sample; we set $\alpha = 1$, $\mu = 0$, $\Lambda = I$, $a_1 = 10^4$, $a_2=b=10$, and $(K,C) = (4,5)$. For each dataset, we also generate a test set of the same size where the sample specific parameters are generated using $\alpha = 1$ and the training set's $\bm{\mu}_k$ and $\Sigma_k$. Fixing $C$ to truth, we varied $K$ and computed average perplexity for LDA and LTN-LDA in Figure~\ref{fig:Perp_Results}(a). There are three main observations: (i) LTN-LDA significantly outperforms LDA for $K$ near truth, (ii) the perplexity curve for LTN-LDA decreases until it stabilizes at the true value of $K$, (iii) the perplexity curve for LDA continues to decrease as the modelled $K$ is increased past its true value. The main reason for the difference is that LDA interprets the presence of cross-sample heterogeneity as extra subcommunities and so finds as many subcommunities as are modelled. While this improves out-of-sample predictive performance, it does not improve inference on the underlying truth. Thus, using perplexity to select the modelled number of subcommunities for LDA is a poor method if there is significant cross-sample heterogeneity. LTN-LDA is more robust and parsimonious in its representation of the data because it incorporates cross-sample heterogeneity in subcommunity compositions. Fixing $K$ to truth, we computed average perplexity for LTN-LDA as we varied $C$ in Figure~\ref{fig:Perp_Results}(b). The perplexity curve decreases until it stabilizes at the true value of $C$. In addition to perplexity, we also computed the $L_2$ distances between the posterior mean estimates and the true values for the $\bm{\phi}_d$, $\bm{\beta}_{d,k}$, and $\bm{\beta}_k$ distributions (Figure~\ref{fig:Perp_Results}(c)). Unlike the perplexity curves, the $L_2$ distances are lowest around $C = 5$ and increase as $C$ increases. Thus, if the modelled value of $C$ is increased too far above truth, inference becomes unreliable. The above results suggest a simple two-stage strategy for choosing $(K,C)$ using perplexity. First, let $(K,C)$ vary jointly on a grid and use cross-validation to compute the average perplexity, giving $K$ perplexity curves over $C$. Set $C$ to be the inflection point in these curves. Second, vary $K$ and set the value of $K$ to be the inflection point of the resulting perplexity curve. Note that this strategy may fail for LDA: as our numerical examples show below, due to the lack of cross-sample heterogeneity in LDA, the perplexity score generally continues to improve as one increases the number of subcommunities beyond truth. This in turn leads to misleading inference on subcommunity abundance and composition. \section{Evaluation on a microbiome study} We apply LTN-LDA to identify subcommunity dynamics in the dataset of \cite{2011_Dethlefsen}, which has been previously investigated by \cite{2019_Sankaran} using LDA. The data includes gut microbiome samples of three patients who were administered two five-day courses of ciprofloxacin over a ten-month span. We focus on the $54$ samples from patient F, each consisting of approximately $10,000$ reads. Ciproflaxin was administered during samples 12-23 and 41-51. There are $2,852$ unique ASVs in the dataset; we merged ASVs into taxa at the finest known level and pruned all taxa which did not total at least $100$ sequencing reads. This left $44$ taxa comprising $99.86$ percent of the original counts. The resulting phylogenetic tree is included in Supporting Information~S7. We implemented the strategy outlined above to choose tuning parameters. In particular, we implement a $4$-fold cross-validation letting $K$ vary in $\{2,3,\dots,8\}$ and $C$ in $\{1,2,\dots,21\}$. The resulting $K$ perplexity curves over $C$ are presented in Figure $\ref{fig:Perp_Results}$(d). The inflection point in the curve appears at $C = 8$. Setting $C = 8$ and varying $K$ gives the results in Figure $\ref{fig:Perp_Results}$(e); for comparison, we also applied LDA to the data over varying $K$. LTN-LDA has strictly lower perplexity than LDA, indicating that there are significant levels of cross-sample heterogeneity in the dataset. Moreover, LTN-LDA experiences a noticeable inflection point (near $K = 5$) in contrast to LDA whose perplexity decays slowly. We now present more detailed analysis for LTN-LDA and LDA with $C = 8$. For $K \in \{3,4,7\}$ we plotted the subcommunity abundance on the left side of Figure $\ref{fig:Sank_C_8_K_7_Mult_Plots}$, after manually correcting for label switching. The grey regions indicate periods of ciproflaxin treament. The subcommunities found by LTN-LDA are remarkably stable as $K$ changes. Subcommunities $1$, $2$, and $3$ have almost the exact same abundance, and additional subcommunities have minimal abundance. LDA, however, finds as many subcommunities as are modelled: it will split a heterogenous subcommunitiy into multiple subcommunities with no heterogeneity. For $K = 7$, we plotted the ASV-subcommunity distributions on the right side of Figure $\ref{fig:Sank_C_8_K_7_Mult_Plots}$. Distributions for the $\bm{\beta}_{d,k}$ are in blue, the $\bm{\beta}_k$ in red, and the LDA distributions in black. The $5$ most prevalent ASVs in each subcommunity are presented in Figure $\ref{fig:Sank_C_8_K_7_Top}$ for LDA and LTN-LDA. These demonstrate that LTN-LDA finds significant levels of cross-sample heterogeneity and subcommunities with meaningfully different compositions than LDA. LTN-LDA thus provides two major advantages. First, LTN-LDA is more robust with respect to modelling differing numbers of subcommunities than LDA. This is similar to our simulations and indicates that LTN-LDA better accounts for the cross-sample heterogeneity in the data than does LDA. Moreover, the three subcommunities found by LTN-LDA are biologically interpretable. The first subcommunity is composed mostly of Lachnospiraceae and Ruminococcaceae and displays significant levels of cross-sample heterogeneity, indicating that LTN-LDA has found these two ASVs can substitute for each other. \cite{2018Haaketal} found this phenomena in humans undergoing ciproflaxin treatment. LTN-LDA can thus learn when two ASVs substitute for each other across samples from the data, with no prior knowledge. The second subcommunity, composed mainly of Bacteroides, increases in abundance during the antibiotic treatments. Studies in mice \citep{2020_Zhu} and humans \citep{2015_Stewardson} indicate that the abundance of Bacteroides increases during ciproflaxcin treatment. The third subcommunity has a small spike in abundance only on the first day of the second antibiotic course, and is composed mostly of Dialister and Veillonella. Ciproflaxin has been shown to be effective against Dialister \citep{2007_Morio} which may explain the decrease in this subcommunity after treatment began. \section{Discussion} We have proposed a novel mixed-membership model which seeks to appropriately incorporate cross-sample heterogeneity in subcommunity compositions: a characteristic of the data prevalent in most microbiome studies. By incorporating the logistic-tree normal model for the sample-specific compositions of each subcommunity, we explicitly allow the composition of subcommunities to vary across samples. We have shown that incorporating cross-sample heterogeneity into MM models can lead to substantially improved inference over models which assume zero cross-sample heterogeneity. LTN-LDA is substantially more robust than LDA with respect to overspecifying $K$ and significantly outperforms LDA in terms of predictive performance. Moreover, perplexity can be a useful device to set the tuning parameters for LTN-LDA but not for LDA. Posterior computation on LTN-LDA can proceed through collapsed blocked Gibbs-sampling with the assistance of P\'olya-Gamma augmentation, and as such implementation for LTN-LDA is convenient. Moreover, LTN-LDA is a fully Bayesian model and the Gibbs sampler allows for posterior uncertainty quantification. In comparison to LDA, LTN-LDA incorporates two new features: the tree structure and the random effects allowing cross-sample heterogeneity. The tree structures provides guidance on how to parsimoniously model the random effects without causing non-identifiability. We carried out an additional numerical experiment that shows that using the tree structure as a way to parametrize the model without adding random effects does not lead to improved inference. For a more detailed discussion see Supporting Information~S8. Like other unsupervised learning methods, LTN-LDA is unable to differentiate between different scenarios giving rise to the same sampling distributions. That is, LTN-LDA, or any other models for that matter, cannot distinguish between multiple subcommunities and a single over-dispersed one if the two give rise to the same sampling distributions. Domain knowledge is necessary to identify such possibilities; traditionally, there are two strategies to incorporate such domain knowledge. The first is through modeling assumptions, such as modelling how large the single-subcommunity dispersion is through the hyperpriors on the $\tau_k^i$. The other strategy is using a decision theoretic formulation that introduces certain loss functions to carry out post-hoc merging of the identified topics. LTN-LDA could be extended to explicitly account for outcomes as in \cite{2007Blei}. Moreover, we believe that the idea of incorporating cross-sample heterogeneity in MM models could be valuable beyond the context of microbiome compositions. In topic models, for example, one might expect different authors to write on the same topic using different vocabulary. LTN-LDA has the potential to be applicable to these other contexts as well, though the immediate challenge is finding an appropriate tree structure. \subsection*{Software} The version of the dataset used in \cite{2019_Sankaran} is available at \url{https://github.com/krisrs1128/microbiome_plvm/tree/master/data/antibiotics-study}. Reproducible code and data for this paper is available \url{https://github.com/PatrickLeBlanc/ReproduceLTNLDAPaper}. R code for implementing the LTN-LDA model is available in the LTNLDA package \url{https://github.com/PatrickLeBlanc/LTNLDA}. \section*{Acknowledgments} LM's research is partly supported by NIGMS grant R01-GM135440 as well as NSF grants DMS-1749789 and DMS-2013930. Part of the research was completed when PL was supported by an NSF-sponsored IBIEM fellowship at Duke University.
{'timestamp': '2022-05-18T02:11:19', 'yymm': '2109', 'arxiv_id': '2109.05386', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05386'}
arxiv
\section{Introduction} In the new norm of work and entertainment under COVID-19, people are increasingly using audio and video recordings. In 2020, most of the international conferences, if not cancelled, were going online. In these online conferences, presenters are often required to record their speech beforehand to avoid possible network interruptions during a live broadcast. Podcast usage is also seeing a rapid growth, by 42\% from March, 2020 to April, 2020, according to Voxnest \cite{voxnest.org}. One of the main pain points when people record audios/videos is that it is hard to make changes when a mistake is made, even if it is just a single misspoken word. Recently, several user-friendly audio/video editing tools \cite{jin2017voco,fried2019text,discript.org} are proposed, allowing users to make small changes to audio narration or even video frames by editing transcript. Such systems support the deletion, cutting/copying, cutting/pasting, insertion, and replacement of a word or a short phrase in the transcript with corresponding changes automatically made in the audio or video. While deletion, cutting/copying, and cutting/pasting only requires cross-modality alignment and a stitching technique, insertion and replacement involves the generation of unseen words and therefore is much more difficult to handle. In this paper, we shall address the zero-shot text-based speech insertion problem. Given a piece of speech and its transcript with the inserted word, we aim to automatically synthesize the inserted word in a voice that sounds seamless in context – as if it were uttered by the same person in the same recording. We ambitiously target at the case where no training corpus of the target speaker is available except for the context speech. A classic solution of this problem is to use a TTS synthesizer to say the word in a generic voice, and then use voice conversion (VC) to convert it into a voice that matches the narration \cite{jin2017voco}. VC is achieved by unit selection in the pioneering work CUTE \cite{jin2016cute} and a later system VoCo \cite{jin2017voco}. The source voice is used as a query to search for snippets of the target voice that sound similar to the query as much as possible, while also matching at the stitch boundaries through minimizing the predefined loss function. A main drawback of this unit selection based VC is that it needs 20 to 40 minutes of target voice \cite{jin2017voco} to achieve a good performance. Some other works \cite{su2020acoustic,morrison2021context} explore attributes-based voice conversion. They use a predefined method to extract certain types of attributes of the target speech. These methods can improve the speech quality to a certain extent, but an inherent limitation still exists. If the gap between the TTS-synthesized voice and the target voice is large, or attributes other than extracted ones are different, there is no quality guarantee. Again, these data-driven VC methods require a moderate amount of parallel speech corpus (source and target voice with the same content). \begin{figure}[t] \centering \includegraphics[width=\linewidth]{fig/task_desc.png} \caption{Text-based speech editing. Through editing text, synthesize the speech of the inserted word (red) that sounds seamless in context (blue) – as if it were uttered by the same person in the same recording. } \label{fig:task_desc} \end{figure} Another line of research that can potentially be applied in the scenario of our interest is zero-shot TTS \cite{jia2018transfer}. Although the mainstream TTS research \cite{shen2018natural,li2019neural,ren2019fastspeech,ren2020fastspeech} focuses on synthesizing high-quality speech using certain timbre with sufficient training corpus, zero-shot TTS \cite{jia2018transfer} aims to synthesize any speaker's speech without training on that speaker's corpus. The main idea is to use a pre-trained speaker verification architecture to extract the target speaker embedding from the reference speech, and then synthesize speech for new content. However, only the global feature of the speaker, such as timbre, is considered in generating the target word. The context given is not utilized for smoothness or naturalness. Speech information can be roughly decomposed into three components \cite{qian2020unsupervised}: language content, timbre, and prosody. In order to synthesize speech that can be seamlessly inserted into the reference speech, these three components of the speech should be jointly considered. Unfortunately, none of the existing methods have done so. We point out that transcript text provides content information, reference speech provides timbre information, and the context surrounding the inserted words provides prosody information. It is based on this observation that we design a one-stage context-aware framework for zero-shot text-based speech synthesis. Our framework has three important features. First, it is a one-stage framework that directly synthesizes the target speech by simultaneously considering all the input information. Second, it is context-aware by applying transformer to the aligned multi-modality hidden sequences. Third, as far as we know, ours is the first zero-shot approach to achieve high-quality results in this scenario. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{fig/framework.png} \caption{Proposed one-stage context-aware text-based speech editing framework. We align the phoneme sequence and the mel-spectrogram sequence before feeding the sum of the two to the mel-spectrogram decoder to directly generate the desired speech. $\otimes$ represents zero padding operation.} \label{fig:framework} \end{figure} \section{Proposed Methods} \subsection{Overview} Given a piece of speech, its transcript text, and the edited transcript with an inserted word or short phrase, we aim to generate a natural and coherent edited speech for the edited transcript, without any additional prior information or training data about the speaker. There are at least three requirements to ensure naturalness and coherence of the generated speech: 1) The inserted speech should match the inserted word in the edited transcript and should have sufficient intelligibility; 2) The timbre of inserted speech should be the same as that of the speaker; 3) The prosody of the generated speech, such as tone and rhythm, should be coherent with its surrounding speech. A major challenge in solving this problem is to meet these requirements without any training data of the given speaker. This is a constrained zero-shot speech synthesis problem. We propose a novel one-stage context-aware framework to solve this problem. There are two prominent features in our solution. First, different from conventional two-stage solutions which involve an intermediate speech generated by a generic TTS engine, our solution directly produces the mel-spectrogram of the target speech from the inserted phonemes and the mel-spectrogram of the original speech. No generic TTS is required. Second, our solution is context-aware. When the same word is inserted into different parts of a speech, the synthesized speech could be different in tone and prosody. Similarly, when the same word is inserted into the speech of different speakers, the synthesized speech will be different in timbre as well. This work makes two additional technical contributions. First, inspired by a generic TTS engine named FastSpeech2 \cite{ren2020fastspeech} which benefits greatly from duration estimation, we introduce a duration estimation module. However, conventional TTS engine uses a large amount of training data of a specific speaker to learn the phoneme duration to be spoken by this speaker. In our scenario, the speaker is unknown during training, making it a challenging zero-shot prediction problem. Second, we use transformers in multiple modules in the framework to explore the global correlation and make full use of the provided speech and transcript. We believe that it is because of transformer's superior attention ability that the challenging zero-shot TTS problem can be solved satisfactorily. Our framework is demonstrated in Figure ~\ref{fig:framework}. It can be decomposed into two phases. In the first multi-modal alignment phase, the duration of the inserted text is estimated and then the phoneme embedding and the speech embedding are matched and aligned. In the second decoding phase, the cross decoder module, built upon transformers, fully explores the local and global correlations in the input and directly generates the desired mel-spectrograms. Finally, for simplicity, the Griffin-Lim \cite{griffin1984signal} algorithm is applied as vocoder to synthesize waveforms. \subsection{Multi-modal alignment phase} This phase handles two streams: phoneme stream and mel-spectrogram stream. For the phoneme stream, the input phoneme (converted from the entire transcript including the inserted words) is first processed by a text embedding block. This block first embeds the input one-hot vector into a trainable embedding of 512 dimensions and then uses a one-dimensional 3-layer CNN with ReLU activation to produce an embedding which contains context information in the input phoneme sequence. Batch normalization, ReLU activations and dropout are applied after every CNN layer. An extra linear layer is added to project the hidden phoneme sequence to the embedding of 256 dimensions. Then, a scaled positional encoding \cite{li2019neural} is added to the text embedding before it is fed into the text encoder. The text encoder is a 2-layer transformer encoder with multi-head self-attention and position-wise fully connected (FC) feed-forward network \cite{vaswani2017attention}. The output of the encoder is the hidden phoneme sequence. It is first sent to the duration prediction module and then, with the predicted duration, it passes through a length regulator to obtain the extended hidden phoneme sequence. Here, phoneme duration is defined as the length of the phoneme in the mel-spectrogram, as in \cite{ren2019fastspeech}. In our framework, we perform zero-shot prediction of phoneme length in the duration prediction module. In addition to the encoded phoneme sequence, the reference duration is also provided to the predictor. In particular, duration of existing phonemes is obtained from Montreal forced alignment (MFA) tools \cite{mcauliffe2017montreal} and that of the inserted phonemes are set to zero. The duration prediction module consists of one transformer encoder layer and 2 FC layers. ReLU activations are applied after every FC layer except the last one. The predicted duration is used to regulate both phoneme sequence and the mel-spectrogram sequence. For the mel-spectrogram stream, the input is first extended with the information of the edited position and the predicted duration. Specifically, we apply zero padding to the mel-spectrogram corresponding to the edited region. As such, the extended mel-spectrogram has the same length as the extended hidden phoneme sequence. The extended mel-spectrogram is then consumed by the spectrogram embedding module which is a neural network composed of two FC layers (each has 256 hidden units) with ReLU activation followed by a scaled positional encoding as applied in \cite{li2019neural}. Finally, the extended mel-spectrogram with the positional encoding information is processed by the spectrogram encoder to obtain the extended hidden mel-spectrogram sequence. The spectrogram encoder has the same network structure as the text encoder. It can be noticed that transformers are extensively used in our framework. The idea behind this design is that transformer is good at capturing long-range dependency for a sequence. We apply zero padding to the input spectrogram before positional embedding. With transformers, the model can gradually "inpaint" the hole at the edited regions. Actually, we have also tried to omit this step, but the results are far from satisfactory. \subsection{Decoding phase} We perform position-wise addition for the aligned phoneme and mel-spectrogram sequences. Then, we adopt a non-autoregressive decoder to predict the synthesized mel-spectrogram from the combined hidden sequence. The reasons why we use addition operation are two-fold. First, we want the input and the output of the decoder to have the identical length, so that a non-autoregressive decoder can be applied. It is known that we have to use an autoregressive decoder if there is length discrepancy between the input and the output. Second, the model can have explicit matching information between the phoneme sequence and the mel-spectrogram sequence. The decoder module is implemented by a 5-layer transformer encoder followed by a linear layer. We use L2 loss to measure the distance between the synthesized and the ground-truth mel-spectrogram. L1 loss is applied to calculate the distance between the predicted and the ground-truth phoneme duration. The weights for the two losses are 1 and 0.01, respectively. It is worth noting that loss is applied on the entire sentence, not just the edited region. \section{Experiments} \subsection{Experiment setup} \subsubsection{Dataset} We conduct experiments on LibriTTS dataset \cite{zen2019libritts}, which contains both English audio clips and the corresponding text transcripts of 2456 speakers. The total audio length is about 585 hours. All of our models are trained on the \emph{train-clean-360} subset which contains 430 female and 474 male speakers, with the total audio length of about 191 hours. All speech recordings are downsampled to 24 kHz sampling rate. In order to solve mispronunciation problems \cite{shen2018natural}, we use the Montreal forced alignment (MFA) \cite{mcauliffe2017montreal} tool to convert text to phoneme and acquire alignment information between speech and phoneme. \subsubsection{Implementation details} In text embedding block, the kernel size of CNN layer is 5 and dropout rate is set to 0.2. The hidden size of the self-attention are set to 256 and the number of attention heads is set to 4. We use four Nvidia Tesla V100 to train our model. The ADAM \cite{kingma2014adam} optimizer with default parameters is applied for 100 epochs. Learning rate is 1e-3 and batch size is 32. Missing words are randomly chosen during training and testing. We use mel-spectrograms with 80 bins using librosa mel filter defaults. Mel-spectrograms are computed through a short time Fourier transform (STFT) using a 50ms frame size, 12.5 ms frame hop, and a Hann window function. We use the Griffin-Lim algorithm \cite{griffin1984signal} as vocoder to synthesize waveform from the predicted mel-spectrogram. A CBHG module \cite{wang2017tacotron} is applied to predict spectral magnitude sampled on a linear-frequency scale. It is trained separately on \emph{train-clean-360} subset of LibriTTS. The hyperparameters of Griffin-Lim and CBHG are the same as in \cite{wang2017tacotron}. We emphasize that our choice of Griffin-Lim is for simplicity. Developing a fast and high-quality trainable spectrogram to waveform converter is an ongoing work. \subsubsection{Evaluation methods} We primarily rely on Mean Opinion Score (MOS) evaluations based on subjective listening tests with rating scores from 1 to 5. We evaluate synthesized speech along two dimensions: its naturalness and similarity to real speech from the target speaker. We randomly choose four speakers (two males and two females) from LibriTTS test-clean set. For each speaker, ten sentences are randomly selected. The chosen speakers are not included in the training set. The following experiments are based on these sentences. We use the method in \cite{jia2018transfer} as baseline for comparison. The target sentence is fed as reference speech for \cite{jia2018transfer} to extract speaker features. However, since the baseline method is not developed for word insertion, it does not make use of the insertion position and therefore does not provide smoothness guarantee. \subsection{Speech naturalness} We conducted three experiments to evaluate the speech naturalness of our methods. The first one is an identification test where subjects will tell whether they think a narration contains an inserted synthetic word. The second one is a Mean Opinion Score (MOS) test that asks subjects to rate the quality of the inserted synthetic words. The third one is an objective test to evaluate the accuracy of phoneme duration prediction. For each sentence selected, we maintain three versions including the original recording. To create the other two altered versions, we randomly choose and remove one word, and synthesize it using our method or the voice clone method as described in \cite{jia2018transfer}. We ensure that the selected word has more than one phoneme. Then we insert the synthesized word to its original location to create the altered narrations. \subsubsection{Speech naturalness identification test} In the identification test, a subject is presented one narration at a time and is informed that there may or may not be one synthesized word. The task is to identify if the narration is original or edited. We use original rate (the number of sentences that are considered as original recordings divided by the total number of sentences) to evaluate the performance of the model. A higher original rate indicates that more synthesized sentences are considered to be original. \begin{table}[th] \caption{Speech naturalness identification test} \label{tab:identification test} \centering \begin{tabular}{l r } \toprule \textbf{Method} & \textbf{Original Rate} \\ \midrule Ground truth & 94.75\% \\ \hline Baseline\cite{jia2018transfer} & 17.75\% \\ Ours & \textbf{47.25}\% \\ \bottomrule \end{tabular} \end{table} Table \ref{tab:identification test} shows the results. The original recordings receive an original rate of 94.75\%, which can be treated as an upper bound of this task. The fact that original recordings cannot achieve a 100\% original rate also shows a high standard of the subjects. With this high standard, the baseline method only achieves 17.75\% original rate. Our method, in contrast, achieves a much higher score of 47.75\%, which demonstrate the advantage of our method to fully explore the local and global correlations to synthesize the target speech. \subsubsection{Speech naturalness MOS test} In the speech naturalness MOS test, subjects are additionally asked to rate the quality of the sentence on a scale from 1 to 5 (1: very annoying, 2: annoying, 3: slightly annoying, 4: perceptible but not annoying, 5: almost real), no matter they think it is an original recording or an edited narration. Each sentence is rated by ten people and we use the average score as the final score. \begin{table}[th] \caption{Speech naturalness Mean Opinion Score (MOS) test} \label{tab:MOS test} \centering \begin{tabular}{l r } \toprule \textbf{Method} & \textbf{MOS} \\ \midrule Ground truth & 4.57 \\ \hline Baseline\cite{jia2018transfer} & 2.66 \\ Ours & \textbf{3.86} \\ \bottomrule \end{tabular} \end{table} Table \ref{tab:MOS test} shows the results. We can see that the performance of our method is significantly better than the baseline method. The reason is obvious: we take advantage of the context while the baseline does not. Compared to the original sentence, our method still has room for improvement. It should be noted that Griffin-Lim is a simple vocoder and better results can be expected if a higher quality vocoder is used. \subsubsection{Duration prediction} Zero-shot phoneme duration prediction is an important technical contribution of our work. This section evaluates the quality of our duration prediction and demonstrates its importance in creating a natural speech through the comparison with the baseline method. Two objective metrics, namely phoneme-level error and word-level error, are used to evaluate the performance. The phoneme error is defined as the mean absolute difference between the predicted duration and the ground truth duration of a phoneme. Each word consists of a few phonemes, and the duration of the word is computed by summing up the duration of all the phonemes. For baseline method, they do not have a duration prediction step, so we only calculate its word-level error based on the duration of synthesized words. Table~\ref{tab:duration prediction} shows the results. The average word-level error of our method is 5.04 frames while that of baseline is 46.56 frames. This clearly verifies the effectiveness of our zero-shot duration prediction module. With an more accurate duration, more high-quality target speech can be obtained. It partially explains why our method achieves significantly better subjective scores than the baseline method in the previous two evaluations. Besides, the average phoneme-level difference of our method is 1.76 frames. Considering the average phoneme duration is 6.28 frames and word duration is 24.05 frames, it still has room for improvement. We will continue to explore speaker-dependent zero-shot duration prediction problem in our future work. \begin{table}[th] \caption{Duration prediction evaluation} \label{tab:duration prediction} \centering \begin{tabular}{l c c} \toprule \textbf{Method} & \textbf{Phoneme-level error} & \textbf{Word-level error} \\ \midrule Baseline\cite{jia2018transfer} & - & 46.56\\ Ours & \textbf{1.76} & \textbf{5.04}\\ \bottomrule \end{tabular} \end{table} \subsection{Speaker similarity} It is hard to evaluate speaker similarity based on a sentence with only one word altered. Therefore, we design a procedure to generate an utterance with all synthesized words. In particular, for each word in a sentence, we remove it and synthesize it using the rest of the sentence as input. We repeat the process multiple times and then concatenate the synthesized words according to their original order in the sentence. For the baseline method \cite{jia2018transfer}, generating a synthesized sentence is quite straightforward, as it was designed to be used in this way. During evaluation, we pair each synthesized utterance with the reference (original) utterance of the same content from the same speaker. Each pair are rated by one rater with the following instructions: “You should not judge the content, grammar, or audio quality of the sentences; instead, just focus on the similarity of the speakers to one another”. The similarity of each pair of the sentences is rated on a scale from 1 to 5 (1: very unsimilar, 2: unsimilar, 3: slightly similar, 4: similar, 5: almost the same). \begin{table}[th] \caption{Speaker similarity Mean Opinion Score (MOS)} \label{tab:speaker similarity} \centering \begin{tabular}{l c} \toprule \textbf{Method} & \textbf{MOS} \\ \midrule Baseline\cite{jia2018transfer} & 2.69\\ Ours & \textbf{3.41}\\ \bottomrule \end{tabular} \end{table} The results are shown in Table~\ref{tab:speaker similarity}. Despite the fact that the baseline method focuses on extracting timbre of the target speaker, the MOS of our method is 0.72 higher. The results demonstrate the success of our method in exploring long range correlation to extract timbre information. \section{Conclusion} In this paper, we have designed a one-stage context-aware framework for zero-shot text-based speech synthesis. Our method jointly considers the three components of speech, namely language content, timbre, and prosody, by an end-to-end framework that directly synthesizes the target speech. The input information is made full use of by several transformer-based modules. Experimental results show that our method can synthesize target speech with high naturalness and similarity without the training corpus of the target speaker. As we know, the performance of Griffin-Lim algorithm is not quite satisfactory. In our future work, we plan to jointly train a high-quality vocoder. Besides, we plan to extend our work to zero-shot TTS scenario to synthesize longer phrases or even the whole sentence. \bibliographystyle{IEEEtran}
{'timestamp': '2021-09-14T02:19:01', 'yymm': '2109', 'arxiv_id': '2109.05426', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05426'}
arxiv
\section{Introduction} Search systems play significant roles in today's online shopping experience. In conventional e-commerce search systems, user interacts with the system through typing of keywords, followed by product clicks or keywords modifications, depending on whether returned product list matches with user expectation. The recent success of intelligent assistants such as Alexa, Google Now, and Siri enables user to interact with search systems using natural language. For online shopping in particular, it becomes alluring that users can navigate through products with conversations like traditional in-store shopping, guided by a knowledgeable yet thoughtful virtual shopping assistant. However, building a successful conversational search system for online shopping faces at least two real world challenges. The first challenge is the \emph{imperfect product attribute schema and product knowledge}. While this challenge applies also to traditional search systems, it is more problematic for conversational search because the later depends on product attributes to link lengthy multi-turn utterances (in contrast to short queries in conventional search) with products. Most previous conversational shopping search work \cite{DBLP:conf/nips/LiKSMCP18,DBLP:conf/cikm/BiAZC19,DBLP:conf/aaai/YanDCZZL17} looks for the target product through direct attribute matching, assuming availability of complete product knowledge in structured form. In practice, this assumption rarely holds, and systems designed with this assumption will suffer from product recall losses. The second challenge is the \emph{lack of in-domain dialog dataset} for model training. Constructing a large-scale dialog dataset by crowd-sourcing from scratch is inefficient. Popular approaches include Machines-Talking-To-Machines (M2M) \cite{DBLP:conf/naacl/ShahHLT18}, which generates outlines of dialogs by self-play between two machines, and Wizard-of-Oz (WoZ) \cite{DBLP:journals/tois/Kelley84}, which collects data through virtual conversations between annotators. Note that both approaches require manually written utterances. In addition, a line of other work \cite{DBLP:conf/wsdm/Lei0MWHKC20,DBLP:conf/www/LuoSWLY20,DBLP:conf/cikm/BiAZC19} constructs conversations from the review datasets such as Amazon Product Data \cite{DBLP:conf/kdd/McAuleyPL15} and LastFM\footnote{\url{https://grouplens.org/datasets/hetrec-2011/}}, whereas usage of these datasets is limited to sub-tasks (e.g., dialog policy) due to the absence of user utterances. \citet{DBLP:conf/aaai/SahaKS18} collected a dialog dataset for fashion product shopping. However, the described method requires dozens of domain experts to manually create the dialog, and the dataset can hardly be generalized beyond fashion shopping given the lack of utterance annotations. To address the first challenge of imperfect attribute schema and product knowledge, we propose \textbf{ConvSearch}, an end-to-end conversational search system that deeply combines the dialog and search system to improve the search performance. In particular, the Product Search module leverages both structured product attributes and unstructured product text (e.g. profile), where the product text may contain phrases matching with utterances when schema is incomplete or when a product attribute value is missing. Putting together, our system has the advantage of both reduced error accumulation along individual modules, and enhanced robustness against product schema/knowledge gaps. To address the second challenge of lacking in-domain dialog dataset, we propose a jump-start dialog generation method \textbf{M2M-UT} which 1) generates utterance from existing dialogues of similar domains (e.g., movie ticketing \cite{DBLP:conf/ijcnlp/LiCLGC17}), and 2) builds dialog outlines from e-commerce search behavior data, and fills them with the generated utterances. The proposed approach significantly reduces manual effort in data construction, and as a result we introduce a new conversational shopping search dataset \textbf{CSD-UT} with 942K utterances. Note that although the dialogue dataset construction focuses on shopping, the approach described here can be adapted for other task-oriented conversations as well, which we will leave it to future work. Our contributions are summarized as follows: \begin{itemize} \item We proposed an end-to-end conversational search system which deeply combines dialog with search, and leverages both structured product attributes and unstructured text in product search to compensate for incomplete product schema/knowledge.\footnote{The prototpye development, evaluation, and data set presented in this paper are independent from any existing commercialized chatbot system.} \item We proposed a new dialog dataset construction approach, which can transfer utterances from dialogs of similar domains and build dialogues from user behavior records. Using this new approach which significantly reduced manual work compared with existing approaches, we introduced a new conversational search dataset for online shopping. \item Extensive experiments show that our system outperforms evaluated competitors for success rate (SR@5) score. \end{itemize} \section{Related Work} \paragraph{Conversational Search System} Conversational search task aims to understand user's search intents through multi-round conversational interactions, and return user the desired search item. Due to lack of annotated dialog utterances in particular for conversational search tasks, previous work either adopted rule-based utterance parsing or focused only on dialog policy. \citet{DBLP:conf/aaai/YanDCZZL17} proposed a rule-based approach to cold-start online shopping dialog systems utilizing user search logs and intent phrases collected from community sites. In another line of work, \citet{DBLP:conf/www/LuoSWLY20} and \citet{DBLP:conf/cikm/ZhangCA0C18} utilized Amazon review dataset, \citet{DBLP:conf/wsdm/Lei0MWHKC20} and \citet{DBLP:conf/nips/LiKSMCP18} revised user reviews from Yelp\footnote{\url{https://www.yelp.com/dataset/}} and LastFM\footnote{\url{https://grouplens.org/datasets/hetrec-2011/}}, all of which focused on the conversation policy without utterance understanding. As a comparison, in this paper we focused an end-to-end conversational search system, which fuses both utterance understanding and product search together through multi-task learning. \begin{figure*}[!t] \centering \includegraphics[width=\textwidth]{pics/system_structure_1.pdf} \caption{Illustration of our end-to-end conversational search system. State Tracker module takes utterances to predict dialog state $S_t$ using the seq-to-seq transformer. Product Search module matches products represented by transformers with query representations $\mathbf{q_t}$ using a multi-head attention mechanism. Dialog Policy module takes inputs from $S_t$, intent and ranked product list, and decides the responses. NLG module composes system responses as instructed by Dialog Policy, and displays them to user.} \label{neural_search_img} \end{figure*} \paragraph{Constructing Dialog Dataset for Online Shopping} \citet{DBLP:conf/aaai/RastogiZSGK20} proposed a crowd-sourcing version of Wizard-of-Oz (WOZ) paradigm for collecting domain-specific corpora. In this system, users and wizards were given a predefined task to complete (e.g. find a Chinese restaurant in the North). To avoid the distracting latency, users and wizards were asked to contribute just a single turn for each dialogue. \citet{DBLP:conf/aaai/SahaKS18} built a multi-mode dialog system for fashion with experts and in-house labors. They crawled 1 million fashion items from the web, hand-crafted taxonomy for items, identified the set of fashion attributes, and employed experts to write dialogs. The described methods were highly labor-consuming, and the published dataset did not contain attribute annotation on utterances, making it hard for utterance understanding model training. The approach adopted by \citet{DBLP:conf/aaai/YanDCZZL17} mines phrases of shopping from community sites and uses crow-sourcing to label utterance intents. Although costing less labors, this work did not construct the full dialogs. As a comparison, in this paper we constructed the full shopping search dialogs through real user behavior data, with user utterances filled by transferring from existing dialogs of similar domains. \section{End-to-End Conversational Search with Multi-task Learning}\label{sec-e2e} Our conversational search system, depicted in Figure \ref{neural_search_img}, consists of four major modules: State Tracker (ST), Product Search, Dialog Policy, and Natural Language Generation (NLG). The State Tracker module interprets the dialog content, outputs user intent, along with product attributes that the user is interested in. The Product Search module returns a list of products which are matching with tracked attributes user interested in. Based on output from State Tracker, the Dialog Policy manages agent response according to user intents and the candidate search result, and the NLG module transforms the response into natural language displayed to user. To address the challenge of imperfect product attribute schema/knowledge, our Product Search module leverages both structured product attributes and unstructured text. To mutually benefit from each other's learning, we integrate State Tracker and Product Search together through multi-task learning, and build an end-to-end trainable search system. \subsection{State Tracker}\label{sec-nlu} Unlike previous work that treats state tracking as a multi-label classification task \cite{DBLP:conf/acl/ZhuZFLTLPGZH20,DBLP:conf/icml/WenMBY17}, we redefine the state tracking task as a sequence-to-sequence problem. As shown in Figure \ref{neural_search_img}, we link the slots and values of dialog state with special delimiter tokens, turning it into a sequence. Then we employ a transformer network to translate dialog turns into state, which encodes the dialog lines with a bidirectional transformer encoder and generate state sequence autoregressively. At each turn in the dialog, the State Tracker module outputs 1) the dialog \emph{state} $S$ and 2) the user utterance \emph{intent} $I$, where $S$ are attribute-values grouped by product attributes, representing the system's tracking of user's preferred search criteria, and \emph{intent} $I\in \mathbb{I}$ is an enumerable value from $\mathbb{I}=$\{\textit{request}, \textit{inform}, \textit{ask\_attribute\_in\_n}, \textit{buy\_n}\}. Formally, given a dialog at turn $t$, we have all history records of $\{R_0, U_0, R_1, U_1, \cdots, R_t, U_t, \}$, where $R_t$ and $U_t$ are \emph{system response} and \emph{user utterance} at turn $t$ respectively. We then use a transformer model \cite{DBLP:conf/naacl/DevlinCLT19} to predict the string $S_t$, the \emph{state} at $t$: \begin{equation}\label{eq-transformer} S_{t} = trans(concat(R_0;U_0;\cdots;R_{t-1};U_{t-1})) \end{equation} where $trans(\cdot)$ is the transformer, and $concat(\cdot)$ is a string concatenation function. For \emph{state} prediction, we use the loss function: \begin{equation} \mathcal{L}_s = - \sum_t \sum_{i} \log P(y^{i*}_t) \end{equation} where $y^{i*}_t$ denotes the ground-truth value for $i$-th item of output sequence at $t$-th turn. We also use an MLP layer to predict the \emph{intent} at $t$: \begin{align} &\mathbf{z}_{t} = \mathbf{W}_I \cdot \text{ReLU}(\mathbf{u}_t) + b_I \\ & P_t(I_i) = \text{softmax}(\mathbf{z}_{t}) \end{align} where $\mathbf{u}_t$ is the mean pooling of last layer output from the encoder in Equation (\ref{eq-transformer}), $W_I$ and $b_I$ are trainable parameters, and $P_t(I_i) $ represents the likelihood of \textit{intent} $I_i \in \mathbb{I}$ from user utterance at $t$-th turn. We use the following loss function for intent prediction: \begin{equation} \mathcal{L}_I = - \sum_t \log P_t(I_i^*). \end{equation} where $I_i^*$ is the ground truth of \emph{intent} at turn $t$. \subsection{Product Search} At each turn $t$, given current \emph{state}, Product Search module estimates the matching likelihood $P_t(p_j)$ for each product $p_j$, and then rank the products to be displayed to user (Figure \ref{neural_search_img}). \paragraph{Query Representation} We represent the product query as $\mathbf{q}_t=\mathbf{u}_t \oplus \mathbf{s}_t $, where $\mathbf{s}_t$ is the state representation obtained by mean pooling the last layer of decoder in Equation (\ref{eq-transformer}), and $\oplus$ denotes the vector concatenation operator. \paragraph{Product Embedding} We represent $j$-th product with $\mathbf{p}_j = \mathbf{d}_j \oplus \mathbf{a}_j$, where $\mathbf{d}_j$ is the mean pooling of the last encoding layer of: $trans(\text{description text of } p_{j})$, and $\mathbf{a}_j$ is the product attribute embedding. In particular, we obtain $\mathbf{a}_j$ by mean pooling the last layer of: $trans(\text{attribute sequence of } p_{j})$, where the attribute sequence is constructed as state sequence. The introduction of profile embedding $\mathbf{d}_j$ compensates for the missing matching clue when product schema is incomplete or attribute values are missing, since they may be extracted from product text. \paragraph{Search with Multi-Head Attention} We use multi-head attention mechanism to match query and products. At dialog turn $t$, we first calculate a product context vector $\mathbf{head}^k_t$ based on the glimpse operation \cite{DBLP:journals/corr/VinyalsBK15}: \begin{align} & \mathbf{a}_{t}^{j}= \mathbf{v}_s^{k \top} \text{tanh}( \mathbf{W}^k_{p}\mathbf{p}_j + \mathbf{W}^k_{q}\mathbf{q}_t ) \label{attention_one} \\ & \mathbf{\alpha}_{t}= \text{softmax}(\mathbf{a}_{t}) \\ & \mathbf{head}^k_t = \sum_{t} \mathbf{\alpha}_{j}^{t} \mathbf{W}^k_{p}\mathbf{p}_j \end{align} where $\mathbf{\alpha}_t$ are attention weights, and $\mathbf{W}^k_p, \mathbf{W}^k_q, \mathbf{v}^k_s$ are trainable parameters for head $k$. We then concatenate $K$ attention heads each with individual parameter sets, $\mathbf{head}_t = \oplus_{0 \leq k\leq K} \mathbf{head}^k_t$. We then form likelihood of product $p_j$ at $t$-th turn as: \begin{align} & \mathbf{e}^j_t = \mathbf{v}_p^{\top} \text{tanh}(\mathbf{W}_{p}' \mathbf{p}_j + \mathbf{W}_h \mathbf{head}_t) \label{attention_two} \\ & P_t(p_j) = \text{softmax}(\mathbf{e}_t) \end{align} where $\mathbf{v}_p$, $\mathbf{W}_{p}'$, and $\mathbf{W}_h$ are trainable parameters. We use the following loss function for product search job: \begin{equation} \mathcal{L}_p = - \sum_t \log P_t(p_j^*) \end{equation} where $p_j^*$ is the ground-truth of product. Finally, we rank products with their likelihood, and return top products to Dialog Policy module for displaying. \subsection{Multi-task Learning} Our end-to-end training links all three tasks (\textit{state} prediction, \textit{intent} prediction and Product Search) together through multi-task learning: \begin{equation} \mathcal{L} = \alpha \mathcal{L}_s + \beta \mathcal{L}_I + \gamma \mathcal{L}_p \end{equation} where $\alpha, \beta, \gamma$ are tunable hyper-parameters. With multi-task learning, these three tasks can enhance each other with shared weights and back-propagated errors. The training data requires intent and attribute annotation for each utterance, and purchased products with product attributes and text profiles (optional) associated with each dialog. \subsection{Dialog Policy and Natural Language Generation} During the conversation, the agent needs to propose additional attributes for user to narrow down the search. When triggered, we filter our product knowledge base using current \emph{state} $S$ to retrieve products matching with the criteria, then use EMDM (Entropy Minimization Dialog Management) \cite{DBLP:journals/taslp/WuLL15} to select the proposed attribute with maximum entropy among filtered products, and show user recommended narrowing down question. The Natural Language Generation module translates the action decision from the Dialog Policy module to natural language, e.g. \emph{request(brand)} $\rightarrow$ \emph{Do you have a brand in mind?}. In this paper we simply use manually written agent templates. \section{Dialogue Dataset Construction}\label{sec_transfer} We address the challenge of lack of conversational shopping search training data by proposing \textbf{M2M-UT}, a method that automatically constructs dialog datasets. Unlike previous works \cite{DBLP:conf/aaai/SahaKS18} that rely on crow-source to generate utterances, M2M-UT can automatically generates utterances with transfer. We hypothesize that the conversation between the user and the shopping agent is guided by customer's \textit{intents} that 1) span user's utterance in natural language, and 2) change according to agent's responses. Therefore, our dataset construction has two steps: 1) we use utterance transfer (UT) to generate utterances from existing dialog datasets of similar domains, and 2) we generate the outline of dialog using customer browsing records using Machine Talking To Machine (M2M) \citet{DBLP:conf/aaai/SahaKS18}. \begin{figure}[!t] \centering \vspace{0.2in} \includegraphics[width=\linewidth]{pics/utterance_gen_one.pdf} \caption{Utterance generation algorithm to generate variant utterances for coffee shopping domain. The utterance example employed in this figure is from MDC dataset \cite{li2018mschallenge}. An utterance is first transferred to our domain with the help of constituency parser and then paraphrased to enhance the variance.} \label{template_transfer} \end{figure} \subsection{Utterance Generation by Transfer}\label{ut} For utterance generation, widely used methods such as WoZ and M2M still require workers to create the various utterances, and thus are not easy to scale up in the shopping conversation application. We found that dialogues from existing task-oriented domains such as movie ticketing or restaurants reservation contain rich form of utterances similar to shopping, for example, ``... sounds good'' is seen from both movie ticketing and shopping conversations. We propose utterance transfer (\textbf{UT}), a novel approach that generates shopping utterances from related task-oriented domains. As shown in Figure \ref{template_transfer}, UT consists of five stages. (1) \textbf{remove redundant phrases}: we remove the redundant phrases that not commonly seen in online shopping (e.g. location and time) with syntax rules. We employ a constituency parser \cite{Kitaev-2018-SelfAttentive} to get the syntax tree of the sentence and remove the PPs (preposition phrases) and NPs (noun phrases) referring to location and time. (2) \textbf{replace values with slots}: we identify and replace values with slots according to the original dataset annotations. For example, in Figure \ref{template_transfer}, we identify value ``superhero'' using the annotation, and replace it as slot ``<description>''. This step turns a complete utterance into a template. (3) \textbf{keyword replacement}: we replace verbs and nouns with those from online shopping domain with rules, e.g. \emph{``movie''} to \emph{``coffee''} and \emph{``watch''} to \emph{``drink''}. (4) \textbf{fill slots}: we fill the slots with values according to user's action. (5) \textbf{paraphrase}: to augment the diversity of utterance, we use a fine-tuned T5 model \cite{DBLP:journals/jmlr/RaffelSRLNMZLL20} to paraphrase the utterance. \paragraph{Paraphrase} One pitfall of utterances generated by templates and rules are the lack of diversity, whereas real conversations usually contain various ways of expressing the same intents. As paraphrase can improve the performance of dialog system \cite{DBLP:conf/acl/GaoZOY20}, we employ a pre-trained neural paraphrase model to augment the variance of templates. Specifically, we use a T5 model (Text-to-Text Transfer Transformer)\footnote{https://github.com/ramsrigouthamg/Paraphrase-any-question-with-T5-Text-To-Text-Transfer-Transformer-} \cite{DBLP:journals/jmlr/RaffelSRLNMZLL20} that is fine-tuned on paraphrase dataset, Quora Question Pairs \footnote{https://www.quora.com/q/quoradata/First-Quora-Dataset-Release-Question-Pairs}. \begin{table}[!t] \centering \vspace{0.1in} \resizebox{\linewidth}{!}{ \begin{tabular}{|l|l|} \hline \multicolumn{2}{|l|}{\bf{Search Behavior Data}} \\ \hline \multicolumn{2}{|l|}{Search keywords: vanilla instant coffee packets} \\ \multicolumn{2}{|l|}{ \makecell[l]{Goal: \{flavor:vanilla, item\_type:instant-coffee,\\ brand:Folgers, roast\_type=medium roast,...\} } } \\ \multicolumn{2}{|l|}{Purchase: ID=B074FLFKNV} \\ \hline \hline \bf{Outline} & \bf{Utterances} \\ \hline S: greeting() & Hello, what can I do for you? \\ \hline U: \makecell[l]{inform(flavor=vanilla, \\ item\_type=instant-coffee)} & \makecell[l]{Please find me vanilla instant\\ coffee packets.} \\ \hline S: request(brand) & Do you have a brand in mind? \\ \hline U: inform(brand=Folgers) & Let's try Folgers. \\ \hline S: push(top\_5) & \makecell[l]{I found you following products:\\ <Products List> } \\ \hline U:\makecell[l]{ ask\_attr\_in\_n(roast\_type, \\index=2)} & \makecell[l]{What roast type is it in the \\ second image.} \\ \hline \makecell[l]{S: inform(roast\_type=\\medium roast)} & It is medium roast. \\ \hline U: buy\_n(index=2) & I will buy the second one. \\ \hline S: notify\_success() & Your order has been placed. \\ \hline \end{tabular} } \caption{M2M-UT dialog generation. M2M-UT first generates the dialog outline with search behavior data, then translates it to utterances with the method illustrated in Figure \ref{template_transfer}. S and U denote System and User respectively. We use search keywords to generate the first user utterance.} \label{dialog generation} \end{table} \subsection{Dialog Generation}\label{sec_dialog_gen} Our online shopping dialog in conversational search is supported by the dialog \textit{outlines}, which consists of \textit{intent} and its parameters. For user utterance intents as shown in Table \ref{dialog generation} , their parameters are typically a list of product attributes with their values. For agent intents, parameters are either attribute values, or operation parameters that agent should execute with (e.g., push(top\_5)). Similar to the dialog system presented in Section \ref{sec-e2e}, we use \textit{state} to track agent's understanding of user's search criteria. We use real e-commerce search behavior data to supervise the construction of intent flow in the dialog. Each anonymous search session contains a query and the final purchased product. We first extract product attribute values from the search keywords as the initial attribute customer interested in, i.e., initial \textit{state}. We then follow M2M (Machine Talking to Machine) \cite{DBLP:conf/naacl/ShahHLT18} to generate the transition of dialogue outlines turn by turn. M2M runs in a self-playing manner by simulating the dialog with a user simulator and a system agent. We build an agenda-based user simulator initialized by the search behavior data, and use a finite state machine \cite{DBLP:books/daglib/0016921} as the system agent. By comparing initial \textit{state} and the finally purchased product, we find that users were not always aware of the full search criteria at the beginning, therefore the dialog is constructed to simulate how agent helps user to fill the gap through attribute refinement. Specifically, as shown in Table \ref{dialog generation}, user starts with initial \textit{state} (e.g., flavor=vanilla). Given current \textit{state}, agent in the next turn proposes a new attribute (e.g., brand) using the policy EMDM (Entropy Minimization Dialog Management) \cite{DBLP:journals/taslp/WuLL15} to narrow down the search. User's response in the next turn will be based on attribute value of the purchased product (e.g., brand=Folgers), which also updates the \textit{state}. Then agent displays a list of products in the next turn (e.g., push(top\_5)). If purchased product appear in push list, user asks questions, commits purchase, and ends the dialog (successful). Otherwise agent proposes a new attribute, and continues the conversation. Dialog ends when length exceeds 20 (unsuccessful). We finally translate the generated outline into natural language by using corresponding utterance templates generated after step (3) in Section \ref{ut}, and finalize the utterance following step (4) and (5) in Section \ref{ut}. After these steps, we have a complete shopping search dialog. \section{Experiments} \subsection{Datasets} Our dataset includes three parts: user search behavior data, dialogs, and product knowledge base. The user search behavior data is a collection of user search keywords and their final purchased products sampled from e-commerce platform. We applied the dialog generation method described in Section \ref{sec_transfer} on the coffee shopping domain. We leveraged the utterances from dataset MDC \cite{li2018mschallenge} and MMD \cite{DBLP:conf/aaai/SahaKS18} and transferred 4 intents from their domains (i.e. movie ticketing, restaurant reservation, fashion shopping), which generated 49,999 dialogs, with each of the dialog contains on average 18.85 turns (Table \ref{statistic_dialog}). In addition, we built up a gold-standard test set of 196 dialogs manually written by workers to evaluate the performance. For the product knowledge base, we sampled 154,161 coffee products from the e-commerce platform. As shown in Table \ref{statistic_kb}, each product has a text profile with average 17.34 tokens and also the attribute-value pairs for 13 different attributes. The vacant ratio of values is 32.16\%, which indicates potential missing attribute values for products. \begin{table}[!tp] \centering \resizebox{0.8\linewidth}{!}{ \begin{tabular}{|l|r|} \hline Metric & \textbf{CSD-UT} \\ \hline \#Dialogs & 49,999 \\ \#Total utterances & 942,766 \\ \#User utterances & 471,383 \\ Avg. \#Turns per dialog & 18.85 \\ Avg. \#Tokens per utterance & 6.57 \\ \hline \end{tabular} } \caption{Statistics of generated dialog dataset.} \label{statistic_dialog} \end{table} \begin{table}[!tp] \centering \resizebox{0.8\linewidth}{!}{ \begin{tabular}{|l|r|} \hline \bf{Metric} & \bf{Product KB.} \\ \hline \#Products & 154,161 \\ \#Attributes & 13 \\ Avg. \#Values per attribute & 1111.13 \\ Avg. \#Tokens per profile & 17.34 \\ Vacant ratio of values & 32.16\% \\ \hline \end{tabular} } \caption{Statistics of product knowledge base.} \label{statistic_kb} \end{table} \subsection{Settings} \paragraph{Hyper-parameters} All the transformers used in experiment have 4 sublayers with hidden size of 256, and a word2vec \cite{DBLP:conf/nips/MikolovSCCD13} of 256 dimension is trained to initialize the embedding matrix. Our model used a vocabulary of 50257 entries for text embedding, and 14700 entries for attribute embedding. The models in experiments were trained with AdamW \cite{DBLP:journals/corr/abs-1711-05101} optimizer with the initial learning rate of 1e-4 and batch size of 16. The initial learning rate is selected based on validation loss. We used learning rate scheduler to cut the learning rate by half every time the performance drops and stop training once the performance has three straight drops. Our model was trained on a Nvidia Tesla P100 machine with 16G memory, and the strongest model (ConvSearch w/ Neural Search (attr.\&text.)) took 35 hours for convergence. For multi-task learning, we briefly set $\alpha, \beta, \gamma$ as 1. To save memory, we let the encoder of state tracker and encoder of profile share the parameters, and employed tf$ \cdot$idf to narrow down the search space into 400 products for product search module. \paragraph{Evaluation Metrics} We use the success rate ($SR@t$) to measure the ratio of successful conversations, i.e. recommended the ground-truth item in $t$ turns. We set the max turn $t$ of a session to 5 or 10 and standardized the recommended list length as $5$. Besides, we used recall, precision and F1 to evaluate the performance of state prediction, and reported the performance on slot and value respectively. \begin{table}[!tp] \centering \small \begin{tabular}{|l|cc|} \hline \bf{Model} & \bf{SR@5} & \bf{SR@10} \\ \hline TC-bot \cite{DBLP:conf/ijcnlp/LiCLGC17} & 35.71 & 51.02 \\ ConvLab-2 \cite{DBLP:conf/acl/ZhuZFLTLPGZH20} & 44.89 & 54.08 \\ \hline ConvSearch & & \\ \quad w/ Rule Search & 39.79 & 50.51 \\ \quad w/ Neural Search (attr.) & 46.42 & 57.14 \\ \quad w/ Neural Search (text.) & 48.47 & 59.69 \\ \quad w/ Neural Search (attr. \& text.) & \bf{51.53} & \bf{61.22} \\ \hline \end{tabular} \caption{Evaluation of the end-to-end system. attr. and text. denote attribute and product text respectively. The best score per metric is in bold. Our model outperforms the competitors by 6.64\%. Rule search employs direct attribute matching as traditional work.} \label{dialog_system} \end{table} \begin{table*}[!t] \centering \small \begin{tabular}{|l|ccc|ccc|ccc|} \hline \bf{Model} & \multicolumn{3}{c|}{\bf{State-Attr}} & \multicolumn{3}{c|}{\bf{State-Value}} & \multicolumn{3}{c|}{\bf{Intent}} \\ & R & P & F1 & R & P & F1 & R & P & F1\\ \hline e2e-Trainable \cite{DBLP:conf/eacl/Rojas-BarahonaG17} & 92.67 & 82.74 & 87.46 & 90.98 & 86.57 & 88.66 & 95.75 & 95.91 & 95.82 \\ ZS-DST \cite{DBLP:conf/aaai/RastogiZSGK20} & 96.97 & 89.55 & 93.11 & 91.41 & \bf{87.70} & 89.51 & 96.43 & 97.89 & 97.15 \\ LSTM + classification & 92.34 & 89.72 & 91.01 & 88.97 & 82.31 & 85.51 & 95.65 & 94.26 & 94.94 \\ \hline State Tracker w/o Search & 97.53 & 93.29 & 95.36 & 92.01 & 87.27 & 89.58 & \bf{99.73} & 99.68 & \bf{99.70} \\ State Tracker w/ Search & \bf{98.15} & \bf{93.41} & \bf{95.72} & \bf{93.15} & 87.44 & \bf{90.20} & 99.70 & \bf{99.69} & 99.69 \\ \hline \end{tabular} \caption{Evaluation of state tracking task. R and P denote recall and precision.} \label{SLU_table} \end{table*} \paragraph{Baselines} For state tracking task, we compared against the following baselines: e2e-Trainable \cite{DBLP:conf/eacl/Rojas-BarahonaG17} which encodes utterances with a convolutional neural network (CNN), ZS-DST \cite{DBLP:conf/aaai/RastogiZSGK20}, a Bert-based model which first judges the presence of each slot then the start and end location. We also constructed a baseline by replacing transformers in our system with one-layer LSTMs. For the end-to-end system, we compared against two baselines: TC-bot \cite{DBLP:conf/ijcnlp/LiCLGC17}, a modulized neural dialogue systems for task-completion, and ConvLab-2\footnote{we employ the strongest setting they reported, BERTNLU+RuleDST+RulePolicy +TemplateNLG.}\cite{DBLP:conf/acl/ZhuZFLTLPGZH20}, an open-source toolkit for building, evaluating, and diagnosing a task-oriented dialogue system. \subsection{End-to-End System Evaluation} Table \ref{dialog_system} shows the end-to-end task (success rate) comparisons, where our method outperforms baselines significantly by 6.64\%. This indicates the effectiveness of our end-to-end framework that deeply combines the dialog and search system, while ablation studies (last three rows in Table \ref{dialog_system}) also justify that leveraging both product text and attribute performs better than using only one of them. \subsection{State Tracker Evaluation} Table \ref{SLU_table} shows the performance comparisons of state tracking task. It shows that our method outperforms all baselines in both \emph{state} prediction and \emph{intent} prediction tasks, which is because our state tracking task can better embed the context by concatenating the language of turns together. We also found State Tracker alone without Product Search task showed lower performance, suggesting the effectiveness of multi-task learning. \begin{table}[!tp] \centering \small \begin{tabular}{|l|ccc|} \hline \bf{Model} & \bf{R} & \bf{P} & \bf{F1} \\ \hline tf$\cdot$idf & 5.58 & 1.16 & 1.86 \\ \hline Product Search w/attr. & 15.53 & 3.10 & 5.16 \\ Product Search w/text. & 19.27 & 4.84 & 7.74 \\ Product Search w/text. \& attr. & \bf{26.20} & \bf{5.47} & \bf{9.05} \\ \hline \end{tabular} \caption{Independent evaluation of search task. This experiment shows the benefit of combining product text profile and attribute for search. attr. is abbreviation for product attribute. The best score per metric is in bold.} \label{neural_search_evaluation} \end{table} \subsection{Product Search Evaluation}\label{search_task_result} Table \ref{neural_search_evaluation} shows ablation studies of the Product Search module, along with comparisons with a simple tf.idf baseline. In particular, after the 3rd turn of dialog, we selected top-5 products with highest probability from the list returned by Product Search module, and calculated recall, precision and F1 value against the ground-truth purchased product. We can see that the end-to-end search significantly improved the search recall by 4.69 times over the tf$\cdot$idf baseline. Improvement induced by combining text and attribute embedding suggests the benefits of combining product text and attributes in search task. \subsection{Dialog Generation Method Evaluation} We next conducted ablation studies on the data construction method. We evaluated the effectiveness of each component using the performance of State Tracker task. For each configuration in Table \ref{dataset_evluation}, we trained the State Tracker module with corresponding dataset, and reported the performance on a manually prepared test set. As shown in the table, the module performance degrades without syntax analysis since redundant phrase (e.g. time, location) won't be removed from the utterance. Similarly, module performance degrades without paraphrase since language variance will be weakened. These suggest that both removing redundancy with syntax and increasing variance with paraphrase are effective to improve the training dataset quality. \begin{table}[!tp] \centering \small \resizebox{\linewidth}{!}{ \begin{tabular}{|l|ccc|} \hline \bf{Dataset} & \bf{Attr} & \bf{Value} & \bf{Intent} \\ \hline UT w/o Syntax \& Paraphrase & 72.53 & 65.98 & 88.53 \\ UT w/o Syntax & 85.71 & 79.61 & 98.14 \\ UT w/o Paraphrase & 87.51 & 75.12 & 97.55 \\ \hline UT & \bf{95.72} & \bf{90.20} & \bf{99.69} \\ \hline \end{tabular} } \caption{The effectiveness of utterance generation methods for utterance understanding. The numbers in the table are F1 scores. We can see that both syntax and paraphrase improve the dialog data quality.} \label{dataset_evluation} \end{table} \begin{table}[!tp] \centering \small \begin{tabular}{|l|ccc|} \hline \bf{Method} & \bf{Coherence} & \bf{Fluency} & \bf{Approp.} \\ \hline TC-bot & 2.98 & 3.42 & 3.20 \\ ConvSearch & 3.58 & 3.54 & 3.66 \\ \hline \end{tabular} \caption{Human Evaluation Result. Approp. is short for Appropriateness.} \label{human_evaluation} \end{table} \subsection{Human Evaluation} We also performed human evaluations on system responses. For each method, we collected 100 dialogs and asked three workers to evaluate them with three metrics: coherence, fluency and appropriateness. All metrics have five grades: from 1(worst) to 5(best), where 3 denotes `good'. As shown in Table \ref{human_evaluation}, ConvSearch outperforms the baseline model in all three metrics. \section{Conclusion and Future Work} In this work, we built an end-to-end conversation search system for online shopping, where we deeply combined the dialog and search system with multi-task learning. In particular, our product search module leverages both product attribute and text to retrieve products, which mitigates the imperfect product schema/knowledge challenges. To address issue of lacking in-domain dialog dataset, we proposed a dataset transfer method and constructed shopping dialog dataset from user search behavior data and existing dialogs of similar domain. The proposed dataset construction method lowers the cost, making it possible to scale-up to broader use scenarios. We will leave it to future work to expand the methodology across more shopping categories, and broader use scenarios such as clinical conversations and customer service, etc. \section*{Acknowledgments} Hao He is supported by the National Key Research and Development Program of China under Grant 2018YFC0830400, the Basic Research Project of Shanghai Science and Technology Commission under ECNU-SJTU joint Grant 19JC1410102, the Shanghai Municipal Science and Technology Major Project under Grant 2021SHZDZX0102. This research is partially supported by the Shanghai Science and Technology Innovation Action Plan under Grant 20511102600.
{'timestamp': '2021-09-14T02:20:24', 'yymm': '2109', 'arxiv_id': '2109.05460', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05460'}
arxiv
\section{Introduction} In argumentation theory, an enthymeme is defined as an incomplete argument found in discourse, where some components are explicit, but other propositions are left implicit and need to be \emph{filled in} as premises or conclusions to fully understand what the argument is \cite{waltonReed2005}. In many instances the missing proposition is a premise. The well-cited example of the Silver Blade case from one of Sherlock Holmes' stories \cite{waltonReed2005} presents such as an incomplete argument \begin{displayquote} A dog was kept in the stable, and yet, though someone had been in and fetched out a horse, he had not barked enough to rouse the two lads in the loft. Obviously, the midnight visitor was someone whom the dog knew well. \end{displayquote} The missing premise in this case is the generalization ``Dogs generally bark when a person enters an area unless the dog knows the person well." While there has been work on identification (i.e., classification) and reconstruction of implicit premises in enthymemes \cite{rajendran-etal-2016-contextual,habernal-etal-2018-argument, reisert-etal-2015-computational,boltuzic-snajder-2016-fill,Razuvayevskaya2017FindingEI}, to our knowledge, \emph{automatically generating an implicit premise from a given enthymeme} is a new task. There are two main challenges that need to be addressed: 1) lack of large scale data of incomplete arguments together with annotated missing premises needed to train a sequence-to-sequence model (the largest such set contains 1.7K instances \cite{habernal-etal-2018-argument}); and 2) the inherent need to model commonsense or word knowledge. We propose an approach for generating an implicit premise given a incomplete argument that aims to address these two challenges. Our contributions are three fold. \begin{table}[] \small \centering \begin{tabular}{|l|l|l|} \hline Reason & \multicolumn{2}{l|}{Vaccinations save lives} \\ \hline Claim & \multicolumn{2}{l|}{\begin{tabular}[c]{@{}l@{}}Vaccination should be mandatory\\ for all children\end{tabular}} \\ \hline\hline ZeroShot & \multicolumn{2}{l|}{Vaccines save lives, they save money} \\ \hline \begin{tabular}[c]{@{}l@{}}Fine-tuned on \\\textit{ART} \end{tabular} & \multicolumn{2}{l|}{\begin{tabular}[c]{@{}l@{}}Vaccinations are the best way to \\ protect children.\end{tabular}} \\ \hline \begin{tabular}[c]{@{}l@{}}Fine-tuned on \\ \textit{ART +PARA-C}\end{tabular} & \multicolumn{2}{l|}{\begin{tabular}[c]{@{}l@{}}Vaccinations are the best way to\\ prevent childhood diseases.\end{tabular}} \\ \hline \end{tabular} \caption{\label{table:1}Implicit Premise Generation by BART \cite{lewis2019bart} in three different setting for an input enthymeme from dataset by \citet{habernal-etal-2018-argument} } \vspace{-3ex} \end{table} \emph{A new task of generating an implicit premise given an incomplete argument (enthymeme).} Given an enthymeme consisting of a stated conclusion and a stated premise, generate the implicit/missing premise. As the backbone sequence-to-sequence architecture we use BART \cite{lewis2019bart}. \emph{Leverage abductive reasoning as an auxiliary task}. To address the first challenge, we rely on an observation from argumentation theory that incomplete arguments in naturally occurring discourse, more often than not, require abductive reasoning (plausible explanations) rather than the more strict form of reasoning based on deductive logic \cite{waltonReed2005,10.2307/40320292}. The Silver Blaze case is such an example. We leverage the Abductive Reasoning in Narrative Text (\textit{ART}) dataset introduced by \citet{Bhagavatula2020Abductive} to fine-tune a BART model. \textit{ART} consists of pairs of observations together with the plausible explanation to be generated (Section \ref{section:data}). \emph{Encoding discourse-aware common sense knowledge.} To address the second challenge, we rely on PARA-COMET \cite{Gabriel2021ParagraphLevelCT}, a discourse-aware knowledge model that incorporates paragraph-level information to generate coherent commonsense inferences from narratives. We encode the outputs of PARA-COMET during fine-tuning BART on our auxillary dataset (ART) (Section \ref{section:method}). We show on three different datasets (Section \ref{section:data}) that this knowledge-enhanced model performs best both in automatic and human-based evaluations (Section \ref{section:eval}). Table \ref{table:1} shows an example of an enthymeme consisting of a stated premise and conclusion and the generated implicit premise by a BART model (zero-shot), by a BART model fine-tuned on \textit{ART} dataset, and a BART model fine-tuned on \textit{ART} augmented with discourse-aware commonsense knowledge derived from PARA-COMET. We make the code available at \url{https://github.com/tuhinjubcse/EnthymemesEMNLP2021}. \section{Related Work} Prior work on enthymeme reconstruction has focused primarily on the identification (i.e., classification) of implicit premises in enthymemes \cite{rajendran-etal-2016-contextual,habernal-etal-2018-argument, reisert-etal-2015-computational,boltuzic-snajder-2016-fill,Razuvayevskaya2017FindingEI}. \citet{boltuzic-snajder-2016-fill} study how to identify enthymemes in online discussions, while \citet{habernal-etal-2018-argument} present the task of identifying the correct warrant given two candidates warrants in order to reconstruct an enthymeme. \citet{rajendran-etal-2016-contextual} introduce an approach to classify the stance of a statement as implicit or explicit, as a first step towards the long term goal of enthymeme reconstruction. Unlike these works which propose discriminative approaches to identify an enthymeme or the (correct) implicit premises, we focus on generative models that aim to \emph{generate an implicit premise given an enthymeme}, using abductive reasoning and discourse-aware commonsense knowledge. \citet{alshomary-etal-2020-target} introduce a closely related task of generating an argument's conclusion from its premises. Specifically, they focus on the subtask of inferring the conclusion’s target from the premises. They develop two complementary target inference approaches: one ranks premise targets and selects the top-ranked target as the conclusion target, the other finds a new conclusion target in a learned embedding space using a triplet neural network. Unlike this paper, our work focuses on a new task of generating an implicit premise given an enthymeme that consists of a stated conclusion and a stated premise. \label{section:data} \section{Datasets} \label{section:data} \paragraph{Training dataset.} Based on the theoretical connection between enthymemes and abductive reasoning, we use the \textit{Abductive Reasoning in narrative Text (ART)} data developed for the abductive NLG task \cite{Bhagavatula2020Abductive} to train our models. The task is framed as: given two observations (O1 and O2) from a narrative, generate the most plausible explanation (hypothesis) (Table \ref{table:anlg}). The observations O1, O2 in \textit{ART} are drawn from the ROCStories \cite{mostafazadeh2016corpus} dataset, a large collection of short, manually curated five sentence stories. The beginning and ending of each story maps to the first (O1) and second (O2) observations in ART, respectively. \citet{Bhagavatula2020Abductive} presented O1 and O2 as narrative context to crowdworkers and prompted them to generate plausible and implausible Hypotheses (H) to explain the observations. To avoid annotation artifacts, \citet{Bhagavatula2020Abductive} applied an adversarial filtering step to retain one challenging pair of plausible and implausible hypotheses that are hard to distinguish between. The \textit{ART} training set consists of 50481 instances, while the validation and test set consist of 7252 and 14313 instances, respectively. As can be seen in Table \ref{table:anlg} the observations O1 and O2 could be "mapped" to the stated Premise and the stated Claim in an enthymeme, while the hypothesis H is mapped to the \emph{implicit premise} we try to generate. \begin{table}[t] \small \centering \begin{tabular}{|l|l|l|} \hline O1 & \multicolumn{2}{l|}{Alex had his heart set on an ivy league college} \\ \hline O2 & \multicolumn{2}{l|}{\begin{tabular}[c]{@{}l@{}}Alex ended up achieving his dream \\ of getting into the school.\end{tabular}} \\ \hline H & \multicolumn{2}{l|}{Alex applied to Harvard} \\ \hline \end{tabular} \caption{\label{table:anlg}Instances from the \textit{ART} dataset.} \vspace{-3ex} \end{table} \paragraph{Test datasets.} We test our models on three different datasets of incomplete arguments (enthymeme) annotated with human-generated implicit/missing premises. First, we use the Argument Reasoning Comprehension Task dataset released by \citet{habernal-etal-2018-argument} (\textbf{D1}), which contains 1654 \textit{\{claim, premise, warrant(implicit premise)\}} triples. Second, we used the dataset introduced by \citet{boltuzic-snajder-2016-fill}, which contains 494 enthymemes from an online debate forum with human annotated implicit premises (\textbf{D2}). Third, we use the dataset introduced by \citet{becker-etal-2020-implicit} (\textbf{D3}), which contains implicit premises annotated for each arguments from the MicroText Corpus \cite{peldszus2015annotated}. For \textbf{D3}, we focus only arguments that are in a \emph{support} relation since this corresponds to our task. Moreover, we choose the cases where there is only one implicit premise, rather than a chain of linked premises. This results in a total of 112 enthymemes for D3. For all datasets, we apply automatic filtering to keep only full-formed sentences as claim and premises (e.g., remove cases where the stated premise/claim consists of a noun-phrase, a partial clauses, or many sentences). \begin{table}[] \centering \small \begin{tabular}{|l|l|} \hline \begin{tabular}[c]{@{}l@{}}Encoder\\ Input\end{tabular} & \begin{tabular}[c]{@{}l@{}}Amy was looking through her \\ mother's old scrapbooks. \ \textbf{[SEP]} Amy \\ realized her mother had dated her\\ history professor.\end{tabular} \\ \hline\hline \begin{tabular}[c]{@{}l@{}}Encoder\\ Input +\\ PARA-COMET\end{tabular} & \begin{tabular}[c]{@{}l@{}}Amy was looking through her \\ mother's old scrapbooks. \ \textbf{[SEP]} \textbf{\color{ForestGreen}to} \\ \textbf{\color{ForestGreen}find something} \ \textbf{[SEP]} Amy realized\\ her mother had dated her history\\ professor.\end{tabular} \\ \hline\hline \begin{tabular}[c]{@{}l@{}}Decoder\\ Ouput\end{tabular} & \begin{tabular}[c]{@{}l@{}}Amy was looking through her\\ mother's old scrapbooks. \textbf{\textit{\color{blue}And since}} \\ \textit{Amy found pictures of her history}\\ \textit{professor and mother together}. Amy\\ realized her mother had dated her\\ history professor.\end{tabular} \\ \hline \end{tabular} \caption{\label{table:finetuning} Encoder input in two settings: fine-tuning on \textit{ART} and fine-tuning on \textit{ART} + PARA-COMET (the green text between [SEP]). For decoder's output every hypothesis is prepended by \textit{And since} in bolded blue.} \vspace{-3ex} \end{table} \section{Method}\label{section:method} For our generation model, we use BART \cite{lewis2019bart}, a pre-trained conditional language model that combines bidirectional and auto-regressive transformers. It is implemented as a sequence-to-sequence model with a bidirectional encoder over corrupted text and a left-to-right auto-regressive decoder. \paragraph{Fine-tuning BART on \textit{ART}.} To fine-tune BART on the \textit{ART} dataset (Section \ref{section:data}), we concatenate O1 and O2 with a special delimiter [SEP] as input to BART encoder as shown in Table \ref{table:finetuning} Row 1. For decoding, we focus on reconstructing the entire argument given an enthymeme. To encourage fluency and coherence in our generated argument, we prepend the plausible hypothesis (implicit premise) with a discourse marker \textit{And since} (Table 3 Row 3) during fine-tuning. \paragraph{Fine-tuning BART on PARA-COMET enhanced \textit{ART}.} Adapted knowledge models such as COMET \cite{bosselut-etal-2019-comet} have been shown to generate implicit commonsense inferences along several dimensions (depending on what knowledge graphs they were pre-trained on). PARA-COMET \cite{Gabriel2021ParagraphLevelCT}, is an extension of COMET pre-trained on ATOMIC \cite{atomic} that is able to generate discourse-aware common sense knowledge. ATOMIC is a knowledge graph that contains 9 relations related to social commonsense knowledge, including dynamic aspects of events such as causes and effects, if-then conditional statements, and mental states. Given a text with T sentences ${S_{1}, S_{2}...S_{T} }$, PARA-COMET generates a set of commonsense inferences for the 9 inferential relations from ATOMIC for each sentence $S_{i}$, which are consistent with the entire narrative. Following PARA-COMET's input format, we create a discourse of two sentences containing [O1,O2] from ART. We then feed this as an input to the trained PARA-COMET model and obtain 9 commonsense relations for both O1 and O2. Given the causal nature of the implicit premises for this work we use only the relation \textit{xIntent}. Given an event (e.g., ``X compliments Y"), \textit{xIntent} states the likely intents of person X (e.g., ``X wants to be nice"). We only consider \textit{xIntent} returned for O1 (Premise on our task). We experimented with other relations as well as \textit{xIntent} for both O1 and O2 but the results were not better. After obtaining discourse-aware commonsense, we concatenate \{O1, commonsense, O2\} in a sequential order as shown in Table \ref{table:finetuning} Row 2 and pass it to BART's encoder for fine-tuning. For decoding, we use the same process as before (Table \ref{table:finetuning} Row 3). \paragraph{Inference-time decoding.} For generation on our task and test sets, we concatenate the \{Premise, Claim\} or \{Premise, commonsense, Claim\} in a given enthymeme in the same way as shown in Table \ref{table:finetuning} and pass as an input to the encoder of fine-tuned BART. The fine-tuned BART model then generates the entire argument along with the implicit premise auto-regressively. We use beam search with a beam width of 5 for generation. Post decoding, we split the argument into 3 individual sentences and treat the middle sentence starting with \textit{And since} as the implicit premise after removing the artificially added discourse marker. For zero-shot setting, we use the pre-trained BART (bart-large) model. We use the format \{\emph{Premise. And since [MASK]. Claim}\} and let the language model generate an implicit premise. \section{Evaluation and Results} \label{section:eval} We evaluate three setups: 1) directly use pre-trained BART (Zero-shot); 2) fine-tune BART on \textit{ART}; 3) fine-tune BART on \textit{ART+PARA-COMET}. \paragraph{Automatic Evaluation Setup.} We use \textit{BLEU}~\cite{BLEU}, one of the most widely used automatic metrics for generation tasks to compute BLEU-1 and BLEU-2 scores between the system output and the human written gold implicit premise. We also report F1-Score of \textit{BERTScore}, a metric for evaluating text generation using contextualized embeddings. \paragraph{Human evaluation setup.} We select 50 enthymemes from each test set (total of 150 enthymemes) and the output of our fine-tune BART models (with or without PARA-COMET). We hired crowdworkers on the Amazon Mechanical Turk platform. Given an enthymemes they were asked if the generated implicit premises were plausible or not (agreement: 0.56 based on Krippendorff's $\alpha$). Each enthymeme was judged for plausibility by 3 distinct Turkers (50 crowdworkers overall). As it was a binary judgement, we took majority voting which means if 2/3 of the annotators thought it was plausible we marked it as plausible. Plausibility judgement considers whether the generated premise was grammatical, relevant to the argument, coherent with our commonsense and completes the argument. \paragraph{Results.} While pre-trained language models often contain structured commonsense \cite{davison-etal-2019-commonsense,Zhou2020EvaluatingCI} Table \ref{table:auto} shows that pre-trained BART cannot generate plausible implicit premises. Fine-tuning on the \textit{ART} dataset improves the results significantly. Finally, the model that encodes discourse-aware commonsense outperform all baselines on all test datasets (D1, D2 and D3). Human evaluation further demonstrates that encoding commonsense knowledge leads to better implicit premise generation (Table \ref{table:human}). \paragraph{Analysis.} We notice that adding commonsense beams from PARA-COMET makes the generated implicit premise more plausible. For instance, for the stated claim and premise from D3 in Table \ref{analysis}, we see that PARA-COMET adds a beam \textit{to feel better}. Similarly it adds a beam \textit{to learn more} for the stated claim and premise from D1 for both examples shown in Table \ref{analysis}. We posit that adding these in combination with the stated claim and premise, leads our model to infer more plausible implicit premises compared to the ones generated by BART fine-tuned on \textit{ART}. Finally, given that D3 has been annotated with argument schemes \cite{musi-etal-2018-multi}, we can explore their role in enthymeme reconstruction. We notice that most of the generated plausible implicit premises belong to enthymemes annotated with \textit{Practical Evaluation} argument scheme, where ``the premise is an evaluation about something being ‘good’ or ‘bad’, while the claim expresses a recommendation/advice about stopping/continuing an action" (Table \ref{analysis} ). \begin{table}[] \centering \small \begin{tabular}{|p{0.4cm}|l|l|l|l|} \hline Data & System & BLEU1 & BLEU2 & BS \\ \hline \multirow{3}{*}{D1} & ZeroShot & 6.02 & 2.17 & 42.88 \\ \cline{2-5} & ART & 9.16 & 3.11 & 48.35 \\ \cline{2-5} & \begin{tabular}[c]{@{}l@{}} +PARA-COMET\end{tabular} & \textbf{10.56} & \textbf{3.90} & \textbf{50.22} \\ \hline\hline \multirow{3}{*}{D2} & ZeroShot & 28.24 & 15.13 & 46.96 \\ \cline{2-5} & ART & 37.77 & 18.76 & 60.63 \\ \cline{2-5} & \begin{tabular}[c]{@{}l@{}} +PARA-COMET\end{tabular} & \textbf{44.12} & \textbf{24.14} & \textbf{67.75} \\ \hline\hline \multirow{3}{*}{D3} & ZeroShot & 12.58 & 6.25 & 44.64 \\ \cline{2-5} & ART & 14.89 & 6.34 & 51.78 \\ \cline{2-5} & \begin{tabular}[c]{@{}l@{}} +PARA-COMET\end{tabular} & \textbf{15.56} & \textbf{7.50} & \textbf{53.38} \\ \hline \end{tabular} \caption{\label{table:auto} Automatic evaluation of implicit premise generation by BART in 3 settings based on BLEU1, BLEU2 and BertScore(BS). Difference is significant, $( \alpha < 0.005)$ via Wilcoxon signed-rank test.} \end{table} \begin{table}[] \centering \small \begin{tabular}{|l|l|c|} \hline Data & System & Plausibility \\ \hline \multirow{2}{*}{D1} & ART & 50\% \\ \cline{2-3} & \begin{tabular}[c]{@{}l@{}} +PARA-COMET\end{tabular} & \textbf{58}\% \\ \hline\hline \multirow{2}{*}{D2} & ART & 48\% \\ \cline{2-3} & \begin{tabular}[c]{@{}l@{}} +PARA-COMET\end{tabular} & \textbf{66}\% \\ \hline\hline \multirow{2}{*}{D3} & ART & 38\% \\ \cline{2-3} & \begin{tabular}[c]{@{}l@{}} +PARA-COMET\end{tabular} & \textbf{56}\% \\ \hline \end{tabular} \caption{\label{table:human}Human evaluation results our finetuned BART models in two settings. } \vspace{-3ex} \end{table} \begin{table}[h!] \centering \small \begin{tabular}{|p{0.18cm}|p{1.54cm}|p{4.8cm}|} \hline & & \\ \hline \multirow{6}{*}{D1} & St Premise & \begin{tabular}[c]{@{}l@{}}Deaf students need more specialized \\ education\end{tabular} \\ \cline{2-3} & St Claim & States need special schools for the deaf \\ \cline{2-3} & Gold & \begin{tabular}[c]{@{}l@{}}Their parents can't always enroll them\\ in a deaf private school\end{tabular} \\ \cline{2-3} & Zero-shot & We can't afford it, we shouldn't \\ \cline{2-3} & ART & \begin{tabular}[c]{@{}l@{}}The deaf students are not getting \\ enough education.\end{tabular} \\ \cline{2-3} & +PARA-COMET & \begin{tabular}[c]{@{}l@{}}Deaf students are not \textbf{\color{ForestGreen}being served}\\ \textbf{\color{ForestGreen}well in the schools}\end{tabular} \\ \hline\hline \multirow{6}{*}{D1} & St Premise & \begin{tabular}[c]{@{}l@{}}Understanding other culture is \\more important now than ever before.\end{tabular} \\ \cline{2-3} & St Claim & Colleges need humanities programs \\ \cline{2-3} & Gold & \begin{tabular}[c]{@{}l@{}}More people now fail to understand \\other cultures\end{tabular} \\ \cline{2-3} & Zero-shot & It's the humanities, we need them \\ \cline{2-3} & ART & \begin{tabular}[c]{@{}l@{}}The humanities are the most important \\subjects in college.\end{tabular} \\ \cline{2-3} & +PARA-COMET & \begin{tabular}[c]{@{}l@{}}There is a \textbf{\color{ForestGreen}lot of misinformation}\\ out there about other cultures \end{tabular} \\ \hline\hline \multirow{6}{*}{D2} & St Premise & \begin{tabular}[c]{@{}l@{}}Bush new spending in 8 years? \$5.07\\ TRILLION Obama total New Spending\\ (projected out for the next 8 years)?\\\$1.44 TRILLION. And of that total,\\ only \$430 billion is non-recession \\related.\end{tabular} \\ \cline{2-3} & St Claim & Fixed the economy \\ \cline{2-3} & Gold & Obama spends less money than Bush. \\ \cline{2-3} & Zero-shot & We are talking about the economy \\ \cline{2-3} & ART & \begin{tabular}[c]{@{}l@{}}The Obama administration has spent\\ \$1 trillion.\end{tabular} \\ \cline{2-3} & +PARA-COMET & \begin{tabular}[c]{@{}l@{}}The Obama's \textbf{\color{ForestGreen}spending is much less}\\ than Bush's.\end{tabular} \\ \hline\hline \multirow{6}{*}{D3} & St Premise & \begin{tabular}[c]{@{}l@{}}The morning-after pill has a \\number of side effects.\end{tabular} \\ \cline{2-3} & St Claim & The morning-after pill should only be prescribed after counselling by a physician or pharmacist., \\ \cline{2-3} & Gold & Physicians and pharmacists inform about side effects. \\ \cline{2-3} & Zero-shot & \begin{tabular}[c]{@{}l@{}}Morning-after pills are not FDA\\ approved, they should be avoided .\end{tabular} \\ \cline{2-3} & ART & \begin{tabular}[c]{@{}l@{}}The morning- after pill can \\cause depression.\end{tabular} \\ \cline{2-3} & +PARA-COMET & \begin{tabular}[c]{@{}l@{}}The side effects \textbf{\color{ForestGreen}can be very serious}.\end{tabular} \\ \hline \end{tabular} \caption{\label{analysis}Enthymeme generation for a given stated Premise and Claim by BART in 3 settings: zero-shot; fine-tuned on \textit{ART}; and fine-tuned on \textit{ART} + PARA-COMET. Text bolded in green displays how generations are more plausible due to incorporation of discourse aware commonsense.} \end{table} \section{Conclusions} We propose an end-to-end approach for a new task of \emph{automatically generating an implicit premise given an enthymeme}. We show how leveraging abductive reasoning as an auxiliary task improves over zero-shot performance of a state-of-the-art generative language model. Finally, we build a knowledge-enhanced model by encoding discourse-aware commonsense that outperforms all existing baselines in terms of automatic metrics as well as plausibility judgements from crowdworkers. Future work includes exploring other sources for commonsense knowledge, experimenting with improved decoding techniques, as well as studying the role of argument schemes in enthymemes reconstruction. \section{Ethical Considerations} Although we use language models trained on data collected from the Web, which have been shown to have issues with bias and abusive language \cite{sheng-etal-2019-woman, wallace-etal-2019-universal}, the inductive bias of our models should limit inadvertent negative impacts. Unlike model variants such as GPT, BART is a conditional language model, which provides more control of the generated output. Finally, we finetune our model on the ART dataset, which is built on five sentence short stories which is devoid of harmful and toxic text especially targeted at marginalized communities. While dual-use concerns are certainly possible here, we think that open-sourcing this technology will help to facilitate understanding of arguments with more balanced and better reasoning. The technology should be used responsibly, particularly making sure the generation is controllable by providing the stated premise, claim and any commonsense knowledge pertaining to the enthymeme in textual form. Finally, we pay the Turkers \$15/hour, complying with minimum wage standards in US.
{'timestamp': '2021-09-14T02:16:39', 'yymm': '2109', 'arxiv_id': '2109.05358', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05358'}
arxiv
\section{Conclusion} In this paper, we have proposed a cylindrical and asymmetrical 3D convolution networks for LiDAR segmentation, where it maintains the 3D geometric relation. Specifically, two key components, the cylinder partition and asymmetrical 3D convolution networks, are designed to handle the inherent difficulties in outdoor LiDAR point cloud, namely sparsity and varying density, effectively and robustly. We conduct the extensive experiments and ablation studies, where the model achieves the state-of-the-art in SemanticKITTI, A2D2 and nuScenes, and keeps good generalization ability to other LiDAR based tasks, including LiDAR panoptic segmentation and LiDAR 3D detection. \subsection{Subsection Heading Here} \input{conclu} \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran} \section{Experiments} In this section, we benchmark the proposed model on three downstream tasks. For semantic segmentation task, we evaluate the proposed method on several large-scale datasets, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, SemanticKITTI, nuScenes and A2D2. SemanticKITTI and nuScenes are also used in panoptic segmentation and 3D detection, respectively. Furthermore, extensive ablation studies on LiDAR semantic segmentation task are conducted to validate each component. \begin{table*}[t] \caption{Results of our proposed method and state-of-the-art LiDAR Segmentation methods on SemanticKITTI single-scan test set. Note that all results are obtained from the literature, where post-processing, flip \& rotation test ensemble, \emph{etc}\onedot} \def\vs{\emph{vs}\onedot are also applied.} \label{semantickitti} \centering \begin{adjustbox}{width=\textwidth} \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c} \hline \textbf{Methods} & \textbf{mIoU} & \rotatebox{90}{car} & \rotatebox{90}{bicycle} & \rotatebox{90}{motorcycle} & \rotatebox{90}{truck} & \rotatebox{90}{other-vehicle} & \rotatebox{90}{person} & \rotatebox{90}{bicyclist} & \rotatebox{90}{motorcyclist} & \rotatebox{90}{road} & \rotatebox{90}{parking} & \rotatebox{90}{sidewalk} & \rotatebox{90}{other-ground} & \rotatebox{90}{building} & \rotatebox{90}{fence} & \rotatebox{90}{vegetation} & \rotatebox{90}{trunk} & \rotatebox{90}{terrain} & \rotatebox{90}{pole} & \rotatebox{90}{traffic} \\ \hline \hline TangentConv~\cite{tatarchenko2018tangent} & 35.9 & 86.8 & 1.3 & 12.7 & 11.6 & 10.2 & 17.1 & 20.2 & 0.5 & 82.9 & 15.2 & 61.7 & 9.0 & 82.8 & 44.2 & 75.5 & 42.5 & 55.5 & 30.2 & 22.2\\ \hline Darknet53~\cite{behley2019semantickitti} & 49.9 & 86.4 & 24.5 & 32.7 & 25.5 & 22.6 & 36.2 & 33.6 & 4.7 & 91.8 & 64.8 & 74.6 & {27.9} & 84.1 & 55.0 & 78.3 & 50.1 & 64.0 & 38.9 & 52.2 \\ \hline RandLA-Net~\cite{hu2020randla} & 50.3 & 94.0 & 19.8 & 21.4 & {42.7} & 38.7 & 47.5 & 48.8 & 4.6 & 90.4 & 56.9 & 67.9 & 15.5 & 81.1 & 49.7 & 78.3 & 60.3 & 59.0 & 44.2 & 38.1 \\ \hline RangeNet++~\cite{milioto2019rangenet++} & 52.2 & 91.4 & 25.7 & 34.4 & 25.7 & 23.0 & 38.3 & 38.8 & 4.8 & {91.8} & {65.0} & 75.2 & 27.8 & 87.4 & 58.6 & 80.5 & 55.1 & 64.6 & 47.9 & 55.9 \\ \hline PolarNet~\cite{zhang2020polarnet} & 54.3 & 93.8 & 40.3 & 30.1 & 22.9 & 28.5 & 43.2 & 40.2 & 5.6 & 90.8 & 61.7 & 74.4 & 21.7 & {90.0} & 61.3 & 84.0 & 65.5 & 67.8 & 51.8 & 57.5 \\ \hline SqueezeSegv3~\cite{xu2020squeezesegv3} & 55.9 & 92.5 & 38.7 & 36.5 & 29.6 & 33.0 & 45.6 & 46.2 & {20.1} & 91.7 & 63.4 & 74.8 & 26.4 & 89.0 & 59.4 & 82.0 & 58.7 & 65.4 & 49.6 & 58.9 \\ \hline Salsanext~\cite{cortinhal2020salsanext} & 59.5 & 91.9 & 48.3 & 38.6 & 38.9 & 31.9 & 60.2 & 59.0 & 19.4 & 91.7 & 63.7 & 75.8 & 29.1 & 90.2 & 64.2 & 81.8 & 63.6 & 66.5 & 54.3 & 62.1 \\ \hline KPConv~\cite{thomas2019kpconv} &58.8& 96.0&32.0 & 42.5 & 33.4&44.3&61.5 & 61.6 & 11.8 & 88.8 & 61.3& 72.7&31.6& \bf{95.0} & 64.2 & 84.8 & 69.2 & 69.1 & 56.4 & 47.4 \\ \hline FusionNet~\cite{zhang12356deep} & 61.3 & 95.3 & 47.5 & 37.7 & 41.8 & 34.5 & 59.5 & 56.8 & 11.9 & 91.8 & 68.8 & 77.1 & 30.8 & 92.5 & \bf{69.4} & 84.5 & 69.8 & 68.5&60.4 & \bf{66.5} \\ \hline KPRNet~\cite{kochanov2020kprnet} & 63.1 & 95.5&54.1& 47.9&23.6 & 42.6&65.9 & 65.0 & 16.5 & \bf{93.2} & \bf{73.9} & \bf{80.6} & 30.2 & 91.7 & {68.4} & \bf{85.7} & 69.8 & 71.2 & 58.7 & 64.1 \\ \hline TORANDONet~\cite{gerdzhev2020tornado} & 63.1 &94.2& 55.7& 48.1& 40.0& 38.2& 63.6& 60.1& 34.9& 89.7& 66.3& 74.5& 28.7& 91.3& 65.6& 85.6& 67.0& \bf{71.5} & 58.0 & {65.9} \\ \hline SPVNAS~\cite{tang2020searching} & 66.4 & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - \\ \hline \hline Ours & \bf{67.8} & \bf{97.1} & \bf{67.6} & \bf{64.0} & \textbf{59.0} & \bf{58.6} & \bf{73.9} & \bf{67.9} & \bf{36.0} & {91.4} & {65.1} & {75.5} & \bf{32.3} & {91.0} & {66.5} & {85.4} & \bf{71.8} & {68.5} & \bf{62.6} & {65.6} \\ \hline \end{tabular} \end{adjustbox} \end{table*} \begin{table*}[t] \caption{Results of our proposed method and other LiDAR Segmentation methods on nuScenes validation set.} \label{nuscenes} \centering \begin{adjustbox}{width=\textwidth} \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c} \hline \textbf{Methods} & \textbf{mIoU} & \rotatebox{90}{barrier} & \rotatebox{90}{bicycle} & \rotatebox{90}{bus} & \rotatebox{90}{car} & \rotatebox{90}{construction} & \rotatebox{90}{motorcycle} & \rotatebox{90}{pedestrian} & \rotatebox{90}{traffic-cone} & \rotatebox{90}{trailer} & \rotatebox{90}{truck} & \rotatebox{90}{driveable} & \rotatebox{90}{other} & \rotatebox{90}{sidewalk} & \rotatebox{90}{terrain} & \rotatebox{90}{manmade} & \rotatebox{90}{vegetation} \\ \hline \hline RangeNet++~\cite{milioto2019rangenet++} & 65.5 & 66.0 & 21.3 & 77.2 & 80.9 & 30.2 & 66.8 & 69.6 & 52.1 & 54.2 & {72.3} & {94.1} & 66.6 & 63.5 & 70.1 & 83.1 & 79.8 \\ \hline PolarNet~\cite{zhang2020polarnet} & 71.0 & 74.7 & 28.2 & 85.3 & 90.9 & 35.1 & 77.5 & 71.3 & 58.8 & 57.4 & 76.1 & 96.5 & 71.1 & 74.7 & {74.0} & 87.3 & 85.7 \\ \hline Salsanext~\cite{cortinhal2020salsanext} & 72.2 & 74.8 & 34.1 & 85.9 & 88.4 & 42.2 & 72.4 & 72.2 & 63.1 & 61.3 & 76.5 & 96.0 & 70.8 & 71.2 & 71.5 & 86.7 & 84.4 \\ \hline \hline Ours & \bf{76.1} & \bf{76.4} & \bf{40.3} & \bf{91.2} & \bf{93.8} & \textbf{51.3} & \bf{78.0} & \bf{78.9} & \bf{64.9} & \bf{62.1} & \bf{84.4} & \bf{96.8} & \bf{71.6} & \bf{76.4} & \bf{75.4} & \bf{90.5} & \bf{87.4} \\ \hline \end{tabular} \end{adjustbox} \end{table*} \subsection{Dataset and Metric} \myparagraph{SemanticKITTI~\cite{behley2019semantickitti}}~~~ is a large-scale driving-scene dataset for point cloud segmentation, including semantic segmentation and panoptic segmentation. It is derived from the KITTI Vision Odometry Benchmark and collected in Germany with the Velodyne-HDLE64 LiDAR. The dataset consists of 22 sequences, splitting sequences 00 to 10 as training set (where sequence 08 is used as the validation set), and sequences 11 to 21 as test set. 19 classes are remained for training and evaluation after merging classes with different moving status and ignore classes with very few points. In this dataset, it consists of two challenges, namely, single-scan and multi-scan point-cloud semantic segmentation, where single-scan denotes the single-frame point cloud semantic segmentation and multi-scan denotes the multiple-frame point cloud segmentation, respectively. The key difference is that multi-scan semantic segmentation requires classifying the moving categories, including moving car, moving truck, moving person, moving bicyclist, moving motorcyclist. \myparagraph{nuScenes~\cite{nuscenes}} It collects 1000 scenes of 20s duration with 32 beams LiDAR sensor. The number of total frames is 40,000, which is sampled at 20Hz. They also officially split the data into training and validation set. After merging similar classes and removing rare classes, total 16 classes for the LiDAR semantic segmentation are remained. \myparagraph{A2D2~\cite{geyer2019a2d2}} We follow the data pre-processing in~\cite{zhang2020polarnet} to generate the label and process the point cloud data. A2D2 uses five asynchronous LiDAR sensors where each sensor covers a potion of the surrounding view. After LiDAR panoramic stitching, the A2D2 dataset is split into 22408, 2774 and 13264 training, validation and test scans, respectively with 38-class segmentation annotation. Since there are 38 categories in A2D2 dataset where some of them only have subtle differences, it is harder than other datasets, SemanticKITTI and nuScenes. \begin{figure*}[t] \centering \begin{tabular}{c} \includegraphics[width=0.8\linewidth]{vis2.pdf} \\ \hline \includegraphics[width=0.8\linewidth]{vis3.pdf} \\ \end{tabular} \caption{Visualization of single-scan semantic segmentation on SemanticKITTI validation set. The left is ground-truth and right is our prediction.} \label{fig:vis_result} \end{figure*} \myparagraph{Implementation Details} For these datasets, the Cartesian spaces are different which are related to the LiDAR sensor range. In our implementation, we fix the Cartesian spaces to be $[x: \pm 50m, y: \pm 50m, z: -3m \sim 1.5m]$, $[x: \pm 50m, y: \pm 50m, z: -4m \sim 2m]$, and $[x: \pm 50m, y: \pm 50m, z: -3m \sim 9m]$ for SemanticKITTI, nuScenes and A2D2, respectively. After transforming to the Cylindrical spaces, they are fixed to be $[\rho: 0m \sim 50m, \theta: \pm \pi, z: -3m \sim 1.5m]$, $[\rho: 0m \sim 50m, \theta: \pm \pi, z: -4m \sim 2m]$, and $[\rho: 0m \sim 50m, \theta: \pm \pi, z: -9m \sim 3m]$. In this way, the proposed cylindrical spaces can cover more than 99\% of points for each point cloud scan on average and points out of the spaces are assigned to the closest cylindrical cell. For all datasets, cylindrical partition splits these point clouds into 3D representation with the size = $480\times360\times32$, where three dimensions indicate the radius, angle and height, respectively. We also perform the ablation studies to investigate and cross-validate the effect of these parameters $480\times360\times32$. We use NVIDIA V100 GPU with 16G memory to train the proposed model with batch size = 2. \myparagraph{Evaluation Metric} To evaluate the proposed method, we follow the official guidance to leverage mean intersection-over-union (mIoU) as the evaluation metric defined in~\cite{behley2019semantickitti,nuscenes}, which can be formulated as: $ IoU_{i} = \frac{TP_{i}}{TP_{i} + FP_{i} + FN_{i}} $ where $TP_{i}, FP_{i}, FN_{i}$ represent true positive, false positive, and false negative predictions for class $i$ and the mIoU is the mean value of $IoU_{i}$ over all classes. \subsection{LiDAR-based Semantic Segmentation} \myparagraph{Results on SemanticKITTI Single-scan Semantic Segmentation} In this experiment, we compare the results of our proposed method with existing state-of-the-art LiDAR segmentation methods on SemanticKITTI single-scan test set. The target is to generate the semantic prediction for single frame point cloud. As shown in Table~\ref{semantickitti}, our method outperforms all existing methods in term of mIoU. Compared to the projection-based methods on 2D space, including Darknet53~\cite{behley2019semantickitti}, SqueezeSegv3~\cite{xu2020squeezesegv3}, RangeNet++~\cite{milioto2019rangenet++} and PolarNet~\cite{zhang2020polarnet}, our method achieves 8\% $\thicksim$ 17\% performance gain in term of mIoU due to the modeling of 3D geometric information. Compared to some voxel partition and 3D convolution based methods, including FusionNet~\cite{zhang12356deep}, TORANDONet~\cite{gerdzhev2020tornado} (multi-view fusion based method) and SPVNAS~\cite{tang2020searching} (utilizing the neural architecture search for LiDAR segmentation), the proposed method also performs better than these 3D convolution based methods, where the cylindrical partition and asymmetrical 3D convolution networks well handle the difficulty of driving-scene LiDAR point cloud that is neglected by these methods. \myparagraph{Visualization} We show some visualization results of single-scan segmentation in Fig.\ref{fig:vis_result}, which are sampled from the SemanticKITTI validation set. It can be observed that the proposed method mainly achieves decent accuracy, and well separates the nearby objects and accurately identifies them because it maintains the 3D topology and utilizes the geometric information (we highlight corresponding regions with red rectangles). These visualization can verify our claim that keeping 3D structure and more balanced point distribution could benefit the segmentation results. \begin{figure}[t] \centering \includegraphics[width=0.99\linewidth]{img_multiscan.pdf} \caption{An example of multi-scan fusion. (b) and (c) represent the moving car and stationary car after the multi-scan fusion, respectively. Note that we use three frames to perform the multi-scan fusion.} \label{fig:multiscan} \end{figure} \begin{table*}[t] \caption{Results of our proposed method and state-of-the-art LiDAR Segmentation methods on SemanticKITTI multi-scan test set - Part \uppercase\expandafter{\romannumeral1}.} \label{semantickitti-multiscan} \centering \begin{adjustbox}{width=\textwidth} \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c} \hline \textbf{Methods} & \textbf{mIoU} & \rotatebox{90}{car} & \rotatebox{90}{bicycle} & \rotatebox{90}{motorcycle} & \rotatebox{90}{truck} & \rotatebox{90}{other-vehicle} & \rotatebox{90}{person} & \rotatebox{90}{bicyclist} & \rotatebox{90}{motorcyclist} & \rotatebox{90}{road} & \rotatebox{90}{parking} & \rotatebox{90}{sidewalk} & \rotatebox{90}{other-ground} & \rotatebox{90}{building} & \rotatebox{90}{fence} \\ \hline \hline TangentConv~\cite{tatarchenko2018tangent} & 34.1 & 84.9 & 2.0 & 18.2 & 21.1 & 18.5 & 1.6 & 0.0 & 0.0 & 83.9 & 38.3 & 64.0 & 15.3 & 85.8 & {49.1} \\ \hline DarkNet53~\cite{semantickitti} & 41.6 & 84.1 & 30.4 & 32.9 & 20.0 & 20.7 & 7.5 & 0.0&0.0 & \textbf{91.6} & 64.9 & \bf{75.3} & 27.5 & 85.2 & {56.5} \\ \hline SpSeqnet~\cite{shi2020spsequencenet} & 43.1 & 88.5 & 24.0 & 26.2 & 29.2 & 22.7 & 6.3 & 0.0 & 0.0 & 90.1 & 57.6 & 73.9 & 27.1 & 91.2 & \bf{66.8} \\ \hline KPConv~\cite{thomas2019kpconv} &51.2& 93.7&44.9 & 47.2 & \textbf{42.5}& 38.6 & \textbf{21.6} & 0.0 & 0.0 & 86.5 & 58.4& 70.5&26.7& {90.8} & 64.5 \\ \hline \hline Ours & \bf{51.5} & \bf{93.8} & \bf{67.6} & \bf{63.3} & {41.2} & \bf{37.6} & {12.9} & \bf{0.1} & \bf{0.1} & {90.4} & \bf{66.3} & {74.9} & \bf{32.1} & \bf{92.4} & {65.8} \\ \hline \end{tabular} \end{adjustbox} \end{table*} \begin{table*}[t] \caption{Results of our proposed method and state-of-the-art LiDAR Segmentation methods on SemanticKITTI multi-scan test set - Part \uppercase\expandafter{\romannumeral2}. Note that ``mov car" indicates moving car, and so on.} \label{semantickitti-multiscan2} \centering \begin{adjustbox}{width=\textwidth} \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c|c} \hline \textbf{Methods} & \textbf{mIoU} & \rotatebox{90}{vegetation} & \rotatebox{90}{trunk} & \rotatebox{90}{terrain} & \rotatebox{90}{pole} & \rotatebox{90}{traffic} & \rotatebox{90}{mov car} & \rotatebox{90}{mov truck} & \rotatebox{90}{moving other} & \rotatebox{90}{mov person} & \rotatebox{90}{mov biclist} & \rotatebox{90}{mov motorlist}\\ \hline \hline TangentConv~\cite{tatarchenko2018tangent} & 34.1 & 79.5 & 43.2 & 56.7 & 36.4 & 31.2 & 40.3 & 1.1 & 6.4 & 1.9 & 30.1 & 42.2 \\ \hline DarkNet53~\cite{semantickitti} & 41.6 & 78.4 & 50.7 & 64.8 & 38.1 & 53.3 & 61.5 & 14.1 & 15.2 & 0.2 & 28.9 & 37.8 \\ \hline SpSeqnet~\cite{shi2020spsequencenet} & 43.1 & 84.0 & 66.0 & 65.7 & 50.8 & 48.7 & 53.2 & \bf{41.2} & \bf{26.2} & 36.2 & 2.3 & 0.1 \\ \hline KPConv~\cite{thomas2019kpconv} &51.2& 84.6& 70.3 & 66.0 & 57.0 & 53.9 & 69.4 & 0.5 & 0.5 & \bf{67.5} & {67.4}& \bf{47.2} \\ \hline \hline Ours & \bf{51.5} & \bf{85.4} & \bf{72.8} & \bf{68.1} & \textbf{62.6} & \bf{61.3} & \bf{68.1} & {0.0} & {0.1} & {63.1} & \bf{60.0} & {0.4} \\ \hline \end{tabular} \end{adjustbox} \end{table*} \myparagraph{Results on SemanticKITTI Multi-scan Semantic Segmentation} Unlike the single-scan semantic segmentation, the multi-scan segmentation in SemanticKITTI takes multiple frame point cloud as input and generates the more categories under moving status, including moving car, moving truck, moving other-vehicle, moving person, moving bicyclist and moving motorcyclist. In this experiment, we first perform the multiple-frame point cloud fusion. Specifically, the sequential point clouds in LiDAR coordinate are firstly transformed to global coordinate. Then, these sequential point clouds are fused in the global coordinate. Finally, all these points are transformed to the coordinate of last frame. In this way, we can achieve the multiple-frame fusion and we use 3 sequential point clouds as input data in our implementation. We show an example in Fig.~\ref{fig:multiscan}. It can be found that moving cars have multiple shifting point clouds while stationary cars keep all points in same location. The results of multi-scan semantic segmentation are shown in Table~\ref{semantickitti-multiscan} and \ref{semantickitti-multiscan2}. Generally, our method outperforms all existing methods in terms of mIoU, where it achieves 0.3\% and 8.4\% gain compared to KPConv~\cite{thomas2019kpconv} (ICCV2019) and SpSeqnet~\cite{shi2020spsequencenet} (CVPR2020), respectively. Our method obtains superior performance for most categories, even for some small objects, like bicycle and motorcycle, \emph{etc}\onedot} \def\vs{\emph{vs}\onedot. For these moving categories, our method achieves the best performance on moving car and moving truck. \myparagraph{Results on nuScenes} For nuScenes LiDARseg dataset, we report the results on its validation set. As shown in Table~\ref{nuscenes}, our method achieves better performance than existing methods in all categories, and this consistent performance improvement demonstrates the capability of the proposed model. Specifically, the proposed method obtains about 4\% $\thicksim$ 7\% performance gain than projection-based methods. Moreover, for these categories with sparse points, such as bicycle and pedestrian, our method significantly outperforms existing approaches, which also demonstrates the effectiveness of the proposed method to tackle the sparsity and varying density. Note that RangeNet++~\cite{milioto2019rangenet++} and Salsanext~\cite{cortinhal2020salsanext} perform the post-processing, including KNN, \emph{etc}\onedot} \def\vs{\emph{vs}\onedot. \begin{table*}[t] \caption{Results of our proposed method and other methods on A2D2 dataset - Part \uppercase\expandafter{\romannumeral1}.} \label{a2d21} \centering \begin{adjustbox}{width=\textwidth} \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c} \hline \textbf{Methods} & \textbf{mIoU} & \rotatebox{90}{car} & \rotatebox{90}{bicycle} & \rotatebox{90}{pedestrian} & \rotatebox{90}{truck} & \rotatebox{90}{small-vehi} & \rotatebox{90}{traffic-signal}& \rotatebox{90}{traffic-sign} & \rotatebox{90}{utility-vehi} & \rotatebox{90}{sidebars} & \rotatebox{90}{bumper} & \rotatebox{90}{curbstone} & \rotatebox{90}{solid line} & \rotatebox{90}{irrelevant signs} & \rotatebox{90}{road blocks} & \rotatebox{90}{tractor} & \rotatebox{90}{non-drivable} & \rotatebox{90}{zebra crossing} \\ \hline \hline Squeezeseg~\cite{wu2018squeezeseg} & 8.9 & 9.7 & 0.0 & 0.0 & 15.8 & 0.0 & 0.7 & 64.4 & 0.0 & 0.4 & {0.0} & {2.2} & 15.6 & 0.5 & 15.9 & 0.0 & 0.0 & 0.0 \\ \hline Squeezesegv2~\cite{wu2019squeezesegv2} & 16.4 & 15.4 & 0.2 & 8.6 & 63.8 & 0.0 & 16.8 & 61.7 & 0.6 & 0.1 & 0.0 & 14.8 & 24.7 & 12.7 & {33.2} & 0.0 & 5.8 & 0.0 \\ \hline DarkNet53~\cite{semantickitti} & 17.2 & 15.2 & 0.8 & 6.1 & 68.5 & 0.0 & 15.5 & 63.8 & 0.4 & 0.3 & 0.0 & 17.3 & 23.8 & 13.3 & 35.6 & 0.0 & 6.3 & 0.0 \\ \hline PolarNet~\cite{zhang2020polarnet} & 23.9 & \bf{23.8} & 10.1 & 18.2 & 69.7 & 9.6 & 49.1 & 58.5 & 0.0 & \bf{11.3} & 0.0 & 28.3 & 37.6 & 24.8 & 42.8 & 0.0 & 14.8 & 0.0 \\ \hline \hline Ours & \bf{27.1} & 20.1 & \bf{21.1} & \bf{29.6} & \bf{77.8} & \textbf{26.7} & \bf{58.6} & \bf{67.6} & \bf{4.6} & 10.3 & 0.0 & \bf{33.4} & \bf{43.9} & \bf{29.9} & \bf{51.0} & 0.0 & \bf{19.9} & 0.0 \\ \hline \end{tabular} \end{adjustbox} \end{table*} \begin{table*}[t] \caption{Results of our proposed method and other methods on A2D2 dataset - Part \uppercase\expandafter{\romannumeral2}.} \label{a2d2} \centering \begin{adjustbox}{width=\textwidth} \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c} \hline \textbf{Methods} & \textbf{mIoU} & \rotatebox{90}{Obstacles} & \rotatebox{90}{Poles} & \rotatebox{90}{RD restricted area} & \rotatebox{90}{Animals} & \rotatebox{90}{Grid structure} & \rotatebox{90}{Signal corpus} & \rotatebox{90}{Drivable cobbleston} & \rotatebox{90}{Electronic traffic} & \rotatebox{90}{Slow drive area} & \rotatebox{90}{Nature object} & \rotatebox{90}{Parking area} & \rotatebox{90}{Sidewalk} & \rotatebox{90}{Ego car} & \rotatebox{90}{Painted driv instr} & \rotatebox{90}{Traffic guide obj} & \rotatebox{90}{Dashed line} & \rotatebox{90}{RD normal street} & \rotatebox{90}{Sky} & \rotatebox{90}{Buildings} & \rotatebox{90}{Blurred area} & \rotatebox{90}{Rain dirt} \\ \hline \hline Squeezeseg~\cite{wu2018squeezeseg} & 8.9 & 0.0& 0.3& 0.0& 0.0& 0.0& 0.0& 0.0& 0.0& 0.0& 64.5& 0.0& 13.7& 0.0& 0.0& 0.1& 0.2& 77.7& 10.4& 27.7& 0.0& 0.0 \\ \hline Squeezesegv2~\cite{wu2019squeezesegv2} & 16.4 & 0.2& 5.2& 29.5& 0.0& 10.3& 5.5& 2.7& 0.0& 1.9& 76.4& 3.8& 29.2& 0.0& 6.4& 12.4& 17.1& 85.8& 12.1& 50.9& 0.0& 0.0 \\ \hline DarkNet53~\cite{semantickitti} & 17.2 & 3.9& 7.6& 38.7& 0.0& 10.8& 4.4& 3.3& 0.0& 0.0& 77.9& 3.1& 31.5& 0.0& 9.4& 7.3& 15.7& 86.4& \bf{12.9} & 55.2& 0.0& 0.0 \\ \hline PolarNet~\cite{zhang2020polarnet} & 23.9 & 8.0& 11.0& 55.6& 0.0& 14.8& 11.9& 7.0& 0.0& \bf{4.4} & 81.6& \bf{12.8} & 42.5& 0.0& 12.7& 11.5& 31.8& 90.3& 9.2& 57.0& 0.0& 0.0 \\ \hline \hline Ours & \bf{27.1} & \bf{15.6} & \bf{14.0} & \bf{60.8} & 0.0 & \bf{23.4} & \bf{21.1} & \bf{13.5} & \bf{0.41} & 0.29 & \bf{84.8} & 10.2 & \bf{46.7} & 0.0 & \bf{20.0} & \bf{23.8} & \bf{34.6} & \bf{91.3} & 10.0 & \bf{64.0} & 0.0 & 0.0 \\ \hline \end{tabular} \end{adjustbox} \end{table*} \myparagraph{Results on A2D2} We report the results on A2D2~\cite{geyer2019a2d2} validation set. As shown in Table~\ref{a2d21} and~\ref{a2d2}, it can be observed that the proposed method performs much better than existing methods about 3\% in terms of mIoU, including Squeezeseg~\cite{wu2018squeezeseg}, SqueezesegV2~\cite{wu2019squeezesegv2}, DarkNet53~\cite{semantickitti} and PolarNet~\cite{zhang2020polarnet}, where all of them are based on the 2D projection and 2D convolution networks. Specifically, our method achieves better performance on almost all categories consistently, which also demonstrates the effectiveness of our method. Note that due to the more fine-grained categories in A2D2 (38 categories in total), it is harder than other datasets, such as SemanticKITTI and nuScenes, and there exist more categories with zero values. In general, our method achieves the consistent state-of-the-art performance in all three datasets with different settings (single-scan and multi-scan) and sensor ranges. It clearly demonstrates the effectiveness of the proposed method and its good generalization capability across different datasets. \subsection{LiDAR-based Panoptic Segmentation} Panoptic segmentation is first proposed in \cite{kirillov2019panoptic} as a new task, in which semantic segmentation is performed for background classes and instance segmentation for foreground classes and these two groups of category are also termed as {\bf{stuff}} and {\bf{things}} classes, respectively. Behley \etal \cite{behley2020benchmark} extend the task to LiDAR point clouds and propose the LiDAR panoptic segmentation. In this experiment, we conduct the panoptic segmentation on SemanticKITTI dataset and report results on the validation set. For the evaluation metrics, we follow the metrics defined in \cite{behley2020benchmark}, where they are the same as that of image panoptic segmentation defined in \cite{kirillov2019panoptic} including Panoptic Quality (PQ), Segmentation Quality (SQ) and Recognition Quality (RQ) which are calculated across all classes. PQ\textsuperscript{$\dagger$}{} is defined by swapping PQ{} of each {\bf{stuff}} class to its IoU and averaging over all classes like PQ{} does. Since the categories in panoptic segmentation contain two groups, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, {\bf{stuff}} and {\bf{things}}, these metrics are also performed separately on these two groups, including PQ\textsuperscript{Th}, PQ\textsuperscript{St}, RQ\textsuperscript{Th}, RQ\textsuperscript{St}, SQ\textsuperscript{Th} and SQ\textsuperscript{St}, where Panoptic Quality (PQ) is usually used as the first criteria. For the experimental setting, we follow the LiDAR semantic segmentation, where Adam optimizer with learning rate = $1e^{-4}$ is used for optimization. In this experiment, we use the proposed cylindrical partition as the partition method and asymmetrical 3D convolution networks as the backbone. Moreover, a semantic branch is used to output the semantic labels for stuff categories, and an instance branch is introduced to generate the instance-level features and further extract their instance IDs for things categories through heuristic clustering algorithms (we use mean-shift in the implementation and the bandwidth of the Mean Shift used in our backbone method is set to $1.2$ while the minimum number of points in a valid instance is set to 50 for SemanticKITTI). We report the results in Table~\ref{tab:semkitti_val}. It can be found that our method achieves much better performance than existing methods~\cite{milioto2020iros,jiang2020pointgroup}. In terms of PQ, we have about 4.7\% point improvement, and particularly for the thing categories, our method significantly outperforms state-of-the-art in terms of PQ\textsuperscript{Th} and RQ\textsuperscript{Th} with a large margin of 10\% points. It indicates that our cylindrical partition and asymmetrical 3D convolution networks significantly benefit the recognition of the {\bf{things}} classes. It is worthy of noting that PointGroup and LPASD perform poorly on the outdoor LiDAR segmentation task which indicates that these indoor methods are not suitable for the challenging outdoor point clouds due to the different scenarios and inherent properties. Experimental results demonstrate the effectiveness of the proposed method and its good generalization ability. We show several samples of panoptic segmentation results in Fig.~\ref{fig:pano}, where different colors represent different vehicles. \begin{table*}[ht] \caption{LiDAR-based panoptic segmentation results on the validation set of SemanticKITTI.} \vspace{-3ex} \begin{center} \small{ \begin{tabular}{l|c|ccc|ccc|ccc|c} \hline Method & \textbf{PQ} & PQ\textsuperscript{$\dagger$} & RQ & SQ & PQ\textsuperscript{Th} & RQ\textsuperscript{Th} & SQ\textsuperscript{Th} & PQ\textsuperscript{St} & RQ\textsuperscript{St} & SQ\textsuperscript{St} & mIoU \\ \hline\hline KPConv \cite{thomas2019kpconv} + PV-RCNN \cite{shi2020pv} & 51.7 & 57.4 & 63.1 & \textbf{78.9} & 46.8 & 56.8 & \textbf{81.5} & \textbf{55.2} & \textbf{67.8} & \textbf{77.1} & 63.1 \\ PointGroup \cite{jiang2020pointgroup} & 46.1 & 54.0 & 56.6 & 74.6 & 47.7 & 55.9 & 73.8 & 45.0 & 57.1 & 75.1 & 55.7 \\ LPASD \cite{milioto2020iros} & 36.5 & 46.1 & - & - & - & 28.2 & - & - & - & - & 50.7 \\ \hline \hline Ours & \textbf{56.4} & \textbf{62.0} & \textbf{67.1} & 76.5 & \textbf{58.8} & \textbf{66.8} & 75.8 & 54.8 & 67.4 & \textbf{77.1} & \textbf{63.5} \\ \hline \end{tabular} } \end{center} \label{tab:semkitti_val} \end{table*} \begin{figure*}[t] \centering \includegraphics[width=0.9\linewidth]{pano.pdf} \vspace{-2ex} \caption{LiDAR-based panoptic segmentation results on SemanticKITTI dataset. For different vehicles, we use different colors to distinguish them.} \label{fig:pano} \end{figure*} \begin{table}[t] \caption{LiDAR-based 3D detection results on nuScenes dataset. CyAs denotes the {\bf{Cy}}lindrical partition and {\bf{As}}ymmetrical 3D convolution networks. SSNv2\textcolor{red}{$^\star$} is extracted from nuScenes Leaderboard.} \centering \begin{tabular*}{0.8\linewidth}{l|c|c} \hline Methods & mAP & NDS \\ \hline \hline PointPillar~\cite{lang2019pointpillars} & 30.5 & 45.3 \\ \hline PP + Reconfig~\cite{wang2020reconfigurable} & 32.5 & 50.6 \\ \hline SECOND~\cite{yan2018second} & 31.6 & 46.8\\ \hline SECOND~\cite{yan2018second} + Cylinder & 34.3 & 49.6\\ \hline SECOND~\cite{yan2018second} + Asym-CNN & 33.0 & 48.3\\ \hline SECOND~\cite{yan2018second} + CyAs & 36.4 & 51.7\\ \hline SSN~\cite{zhu2020ssn}& 46.3 & 56.9 \\ \hline SSN~\cite{zhu2020ssn} + CyAs & 47.7 & 58.2 \\ \hline SSNv2~\cite{zhu2020ssn}\textcolor{red}{$^\star$} & 50.6 & 61.6 \\ \hline SSNv2~\cite{zhu2020ssn}\textcolor{red}{$^\star$} + CyAs & 52.8 & 64.0 \\ \hline \end{tabular*} \label{tab:gene_nusc} \end{table} \begin{figure*}[t] \centering \includegraphics[width=0.9\linewidth]{3ddet.pdf} \caption{LiDAR-based 3D detection results on nuScenes dataset. Bounding boxes with Pink color and Blue color denote the ground truth and predictions, respectively.} \label{fig:3ddet} \end{figure*} \subsection{LiDAR-based 3D Detection} LiDAR 3D detection aims to localize and classify the multi-class objects in the point cloud. SECOND~\cite{yan2018second} first utilizes the 3D voxelization and 3D convolution networks to perform the single-stage 3D detection. In this experiment, we follow SECOND method and replace the regular voxelization and 3D convolution with the proposed cylindrical partition and asymmetrical 3D convolution networks, respectively. Similarly, to verify its scalability, we also extend the proposed modules to SSN~\cite{zhu2020ssn}. Furthermore, another strong baseline, SSNv2~\cite{zhu2020ssn}, is also adapted to verify the effectiveness of our method when the baseline is very competitive. The experiments are conducted on nuScenes dataset and the cylindrical partition also generates the $480\times360\times32$ representation. For the evaluation metrics, we follow the official metrics defined in nuScenes, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, mean average precision (mAP) and nuScenes detection score (NDS). For other experimental settings, including the optimization method, target assignment, anchor size and network architecture of multiple heads, we all follow the setting in SSN~\cite{zhu2020ssn}. The results are shown in Table~\ref{tab:gene_nusc}. PP + Reconfig~\cite{wang2020reconfigurable} is a partition enhancement approach based on PointPillar~\cite{lang2019pointpillars}, while our SECOND + CyAs performs better with similar backbone, which indicates the superiority of the cylindrical partition. To verify the effect of different components (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, Cylinder partition and Asymmetrical 3D convolution networks) of our method on LiDAR 3D detection, we design two variants, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, SECOND~\cite{yan2018second} + Cylinder and SECOND~\cite{yan2018second} + Asym-CNN. The results shown in Table~\ref{tab:gene_nusc} demonstrate that these two components in our method consistently improve the baseline method with 2.8\% points and 1.5\% points in terms of NDS, respectively. We then extend the proposed method (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, CyAs) to two baseline methods, termed as SECOND + CyAs and SSN + CyAs, respectively. By comparing these two models with their extensions, it can be observed that the proposed Cylindrical partition and Asymmetrical 3D convolution networks boost the performance consistently, even for the strong baseline \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, SSNv2, which demonstrates the effectiveness and scalability of our model. For different backbones, like SECOND and SSN, our method could consistently benefit them, showing its good generalization ability. Several qualitative results on nuScenes dataset are shown in Fig.~\ref{fig:3ddet}. \subsection{Ablation Studies} In this section, we perform the thorough ablation experiments on LiDAR-based semantic segmentation task to investigate the effect of different components in our method. We also design several variants of asymmetrical residual block to verify our claim that strengthening the horizontal and vertical kernels power the representation ability for driving-scene point cloud. For the 3D representation $480\times360\times32$ after cylindrical partition, we also try several other hyper-parameters to cross-validate these values. \begin{table}[t] \caption{Ablation studies for network components on SemanticKITTI validation set. PR denotes the point-wise refinement module. Asym-CNN denotes the asymmetrical residual block.} \label{table_net_components} \centering \setlength{\tabcolsep}{4.2pt} \begin{tabular*}{1.0\linewidth}{c c c c c | c} \hline {Baseline} & Cylinder & {Asym-CNN} & {DDCM} & {PR} & {mIoU} \\ \hline \hline {\checkmark} & & & & & 58.1 \\ \checkmark & \checkmark & & & & 61.0 \\ \checkmark & \checkmark & \checkmark & & & 63.8\\ \checkmark & \checkmark & \checkmark & \checkmark & & 65.2 \\ \checkmark & \checkmark & \checkmark & \checkmark & \checkmark & 65.9 \\ \hline \end{tabular*} \end{table} \myparagraph{Effects of Network Components} In this part, we make several variants of our model to validate the contributions of different components. The results on SemanticKITTI validation set are reported in Table~\ref{table_net_components}. Baseline method denotes the framework using 3D voxel partition (with cubic partition) and 3D convolution networks. It can be observed that cylindrical partition performs much better than cubic-based partition with about 3\% mIoU gain and asymmetrical 3D convolution networks also significantly boost the performance about 3\% improvement, which demonstrates that both cylindrical partition and asymmetrical 3D convolution networks are crucial in the proposed method. Furthermore, dimension-decomposition based context modeling delivers the effective global context features, which yields an improvement of 1.4\%. Point-wise refinement module further pushes forward the performance based on the strong model, about 0.7\%. Generally, the proposed cylindrical partition and asymmetrical 3D convolution networks make the most contribution to the performance improvement. \begin{table*}[t] \caption{Ablation studies for asymmetrical residual block on SemanticKITTI validation set.} \label{tab:asym_vari} \centering \begin{adjustbox}{width=\textwidth} \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c} \hline \textbf{Methods} & \textbf{mIoU} & \rotatebox{90}{car} & \rotatebox{90}{bicycle} & \rotatebox{90}{motorcycle} & \rotatebox{90}{truck} & \rotatebox{90}{other-vehicle} & \rotatebox{90}{person} & \rotatebox{90}{bicyclist} & \rotatebox{90}{motorcyclist} & \rotatebox{90}{road} & \rotatebox{90}{parking} & \rotatebox{90}{sidewalk} & \rotatebox{90}{other-ground} & \rotatebox{90}{building} & \rotatebox{90}{fence} & \rotatebox{90}{vegetation} & \rotatebox{90}{trunk} & \rotatebox{90}{terrain} & \rotatebox{90}{pole} & \rotatebox{90}{traffic} \\ \hline \hline Regular & 60.8 & 96.7 & 43.5 & 50.6 & 78.0 & 56.4 & 64.5 & 81.7 & 0.1 & 93.5 & 38.2 & 78.6 & 0.2 & 89.5 & 54.0 & 86.9 & 61.4 & 71.8 & 62.8 & 46.2 \\ \hline 1D-asymmetrical & 61.9 & 96.7 & 44.3 & 56.4 & 83.2 & 60.6 & 64.8 & 89.9 & 2.3 & 93.1 & 36.2 & 78.0 & 0.4 & 88.5 & 49.5 & 86.7 & 64.8 & 70.6 & 63.3 & 48.7 \\ \hline \hline Asymmetrical(ours) & 63.9 & 96.8 & 54.4 & 76.1 & 80.1 & 65.3 & 74.2 & 88.7 & 6.2 & 90.1 & 36.6 & 75.1 & 0.4 & 83.3 & 55.2 & 86.4 & 67.3 & 67.1 & 63.4 & 46.7 \\ \hline \end{tabular} \end{adjustbox} \end{table*} \myparagraph{Variants of Asymmetrical Residual Block} To verify the effectiveness of the proposed asymmetrical residual block, we design several variants of asymmetrical residual block to investigate the effect of horizontal and vertical kernel enhancement (as shown in Fig.~\ref{fig:asym_vari}). The first variant is the regular residual block without any asymmetrical structure. The second one is the 1D-asymmetrical residual block, which utilizes the 1D asymmetrical kernels without height and also strengthens the horizontal or vertical kernels in one-dimension. The third one is the proposed asymmetrical residual block, which strengthens both horizontal and vertical kernels. These variants strengthen the skeleton of convolution kernels step by step (from regular residual block to asymmetrical kernel without height, then to both horizontal and vertical kernels with height). We conduct the ablation studies on SemanticKITTI validation set. Note that we use the cylindrical partition as the partition method and stack these proposed variants to build the 3D convolution networks for this ablation experiment. We report the results in Table~\ref{tab:asym_vari}. It can be found that although the 1D-Asymmetrical residual block only powers the horizontal and vertical kernels in one-dimension, it still achieves 1.3\% gain in terms of mIoU and it obtains about more than 5\% performance gain for motorcycle, other-vehicle and bicyclist, which demonstrates the effectiveness of strengthening skeleton of convolution kernel, even without height dimension. After taking the height into the consideration, the proposed asymmetrical residual block further matches the object distribution in driving scene and powers the skeleton of kernels, which enhances the robustness to the sparsity. From Table~\ref{tab:asym_vari}, the proposed asymmetrical residual block significantly boosts the performance with about 3\% improvements, where large improvement can be observed on some instance categories (about 10\% gain), including bicycle, person, other-vehicle and motorcycle, because it matches the point distribution of object and enhances the representational power. \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{asym_variant2.pdf} \caption{We design three blocks for ablation studies of asymmetrical residual block, including (1) regular residual block , (2) 1D-asymmetrical residual block without height and (3) the proposed asymmetrical residual block.} \label{fig:asym_vari} \end{figure} \myparagraph{Size of 3D Representation} As mentioned in implementation details, we set the size of 3D representation to $480\times360\times32$. In this experiment, we use other hyper-parameters to cross-validate these values, including $600\times480\times40$ and $320\times240\times24$. They cover the denser and sparser representations compared with $480\times360\times32$ representation. Furthermore, we also introduce a cubic partition with size of $1000\times1000\times45$ as the counterpart to investigate the effectiveness and compactness of cylindrical partition. We conduct the experiments on SemanticKITTI validation set and all experiments are under same settings except the different representation size. The results are shown in Table~\ref{tab:sizeofrep}. It can be found that the 3D representation with $480\times360\times32$ performs better than other two representations with 2\% point improvement than $600\times480\times40$ and $320\times240\times24$. Since $320\times240\times24$ representation delivers compacter representation with larger cylindrical cells, it however might mis-split the points across different categories into same cell, which inevitably increases the information loss; While for $600\times480\times40$ representation, it contains fine-grained cylindrical cell, but generates the larger representation, which might burden the training of 3D convolution and cause the degradation of performance. Compared to the cubic partition with $1000\times1000\times45$, all cylindrical partitions achieve much better performance and this consistent performance gain demonstrates its effectiveness. From this experiment, we cross-validate the $480\times360\times32$ representation and investigate the effect of different size of 3D representations. \begin{table} \caption{Ablation studies for the size of 3D representation on SemanticKITTI validation set.} \setlength{\tabcolsep}{7.0pt} \centering \begin{tabular*}{0.7\linewidth}{c|c} \hline Size of Representation & mIoU \\ \hline \hline $1000\times1000\times45$ (cubic) & 58.1\\ \hline $320\times240\times24$ & 63.4\\ \hline $600\times480\times40$ & 64.1 \\ \hline $480\times360\times32$ & 65.9 \\ \hline \end{tabular*} \label{tab:sizeofrep} \end{table} \section{Discussion} \subsection{Comparison of Inference Time} \begin{table}[t] \vspace{-0.5ex} \caption{Comparison of inference time on SemanticKITTI dataset. All numbers represent the total time consisting of computation time and post-processing time. Results are directly taken from~\cite{semantickitti}.} \centering \begin{tabular*}{0.82\linewidth}{l|c|c} \hline Methods & Latency (ms) & mIoU(\%) \\ \hline \hline TangentConv~\cite{tatarchenko2018tangent} & 3000 & 40.9 \\ \hline RandLA~\cite{hu2020randla} & 800 & 53.9 \\ \hline KPConv~\cite{thomas2019kpconv} & 263 & 58.8\\ \hline MinkowskiNet~\cite{choy20194d} & 294 & 63.1 \\ \hline SPVNAS-lite~\cite{tang2020searching} & 110 & 63.7\\ \hline SPVNAS~\cite{tang2020searching} & 259 & 66.4\\ \hline \hline Ours & 170 & 67.8\\ \hline \end{tabular*} \label{tab:time1} \end{table} To investigate the efficiency of the proposed method, we further make a statistic of inference time compared to existing methods. In the experiment, we keep the setting unchanged and set the mode as the evaluation mode to calculate the inference time. The results of inference time of existing methods are directly token from~\cite{semantickitti}. The results are shown in Table~\ref{tab:time1}. Compared to 2D projection based method (inference time consists of computation time and post-processing time), \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, RandLA~\cite{hu2020randla}, our method achieves about \textbf{5.0}$\times$ speedup with 14\% performance improvement due to no requirement for post-processing. Moreover, compared to other 3D based methods, including MinkowskiNet~\cite{choy20194d} and SPVNAS~\cite{tang2020searching}, we also achieve the better performance and less inference time. The main reasons lie in two aspects: 1) the proposed cylindrical partition generates compacter representation compared to regular cubic partition. For example, the regular cubic partition often has the cell of $0.1 \times 0.1 \times 0.1$, and it thus generates a 3D representation of $1000\times1000\times45$, which is more than 4 times larger than the cylindrical partition. 2) the asymmetrical 3D convolution networks consume smaller computational overhead and less parameters compared to the regular 3D convolution networks. Specifically, using a convolution with kernel=$3\times1\times3$ followed by a $1\times3\times3$ convolution is equivalent to sliding a two layer network with the same receptive field as in a 3D convolution with kernel= $3\times3\times3$, but it has 33\% cheaper computational cost than a $3\times3\times3$ convolution with same number of output filters. The corporation of these two parts leads to the effective and efficient approach. \subsection{Comparison with other methods dealing with sparsity issue} Our proposed method utilizes the cylindrical partition and asymmetrical 3D convolution networks to handle the inherent difficulties, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, sparsity and varying density. Hence, we further compare the proposed method with other methods tackling the sparsity issue, to verify its effectiveness. Specifically, SPVNAS~\cite{tang2020searching} proposes a sparse point-voxel convolution to preserve the fine details and deal with sparsity. MinkowskiNet~\cite{choy20194d} adopts sparse tensors and proposes a generalized sparse convolution. We take them as the counterpart dealing with the sparsity issue and make a comparison with them. Note that in our implementation, we also use the sparse convolution~\cite{yan2018second} to build up the asymmetrical 3D convolution networks. \begin{table}[t] \vspace{-0.5ex} \caption{Comparison with other methods dealing with sparsity issue on SemanticKITTI validation set.} \setlength{\tabcolsep}{3.0pt} \centering \begin{tabular*}{1.0\linewidth}{l|c|c|c} \hline Methods &SparseConv& Latency (ms) & mIoU(\%) \\ \hline \hline MinkowskiNet~\cite{choy20194d} & \checkmark & 294 & 63.1 \\ \hline SPVNAS~\cite{tang2020searching} & \checkmark & 259 & 66.4\\ \hline \hline Ours& \checkmark & 170 & 67.8\\ \hline \end{tabular*} \label{tab:sparse1} \end{table} The results are shown in Table~\ref{tab:sparse1}. Compared to other methods handling the sparsity issue, our method achieves both better performance and efficiency, which also demonstrates the superiority of our method. \section{Introduction}\label{sec:introduction}} \IEEEPARstart{3}D {LiDAR} sensor has become an {indispensable device} in {modern} autonomous driving {vehicles}~\cite{ma2019trafficpredict}. It {captures} more precise and farther-away {distance measurements~\cite{xu2019depth} of the surrounding environments} than conventional visual cameras~\cite{wang2021probabilistic,wang2021fcos3d,peng2021side}. The measurements of the sensor naturally form 3D point clouds that can be used to realize a thorough scene understanding for autonomous driving planning and execution, in which LiDAR-based segmentation and detection are crucial for driving-scene perception and understanding. \begin{figure*} \centering \begin{subfigure}[t]{0.6\textwidth} \centering \includegraphics[width=1\linewidth]{teaser2.pdf} \caption{} \label{fig:2d_3d_conv} \end{subfigure} \hfil \begin{subfigure}[t]{0.3\textwidth} \includegraphics[width=\linewidth]{stat1-2.pdf} \caption{} \label{fig:stat1} \end{subfigure} \vspace{-1ex} \caption{(a) Range Image (2D projection) v.s. Cubic Partition v.s. Cylindrical Partition. From top row, it can be found that range image abandons the 3D topology, where 2d convolution processes points in different locations (far away from each other in green circles). From bottom part, cylindrical partition generates the more balanced point distribution than cubic partition (89\% v.s. 61\% cells containing points). (b) Applying the regular 3D voxel partition and 3D convolution directly (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, 3DVoxel) gets limited performance gain compared to projection-based (2D) methods~\cite{zhang2020polarnet, hu2020randla, milioto2019rangenet++, xu2020squeezesegv3}, while our method achieves a remarkable performance gain by further tackling the inherent difficulty of outdoor LiDAR point clouds (showing results on SemanticKITTI dataset). } \label{fig:teaser} \vspace{-3ex} \end{figure*} Recently, the advances in deep learning have significantly pushed forward the state of the art in image domain such as image segmentation and detection. Some existing LiDAR-based perception approaches follow this route to project the 3D point clouds onto a 2D space and process them via 2D convolution networks, including range image based~\cite{milioto2019rangenet++,wu2018squeezeseg} and bird's-eye-view image based~\cite{zhang2020polarnet,lang2019pointpillars}. However, this group of methods lose and alter the accurate 3D geometric information during the 3D-to-2D projection (as shown in the top row of Fig.~\ref{fig:2d_3d_conv}). A natural alternative is to utilize the 3D partition and 3D convolution networks to process the point cloud and maintain their 3D geometric relations. However, in our initial attempts, we directly apply the 3D voxelization~\cite{graham20183d, cciccek20163d} and 3D convolution networks to outdoor LiDAR point cloud, only to find very limited performance gain (as shown in Fig.~\ref{fig:stat1}). Our investigation into this issue reveals a key difficulty of outdoor LiDAR point cloud, namely sparsity and varying density, which is also the key difference to indoor scenes with dense and uniform-density points. However, previous 3D voxelization methods consider the point cloud as a uniform one and split them via the uniform cube, while neglecting the varying-density property of outdoor point cloud. Consequently, this effect to apply the 3D partition to outdoor point cloud is met with fundamental difficulty. Motivated by these findings, we propose a new framework to outdoor LiDAR segmentation that consists of two key components, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, 3D cylindrical partition and asymmetrical 3D convolution networks, which maintain the 3D geometric information and handle these issues from partition and networks, respectively. Here, cylindrical partition resorts to the cylinder coordinates to divide the point cloud dynamically according to the distance (Regions that are far away from the origin have much sparse points, thus requiring a larger cell), which produces a more balanced point distribution (as shown in Fig.~\ref{fig:2d_3d_conv}); while asymmetrical 3D convolution networks strengthen the horizontal and vertical kernels to match the point distribution of objects in the driving scene and enhance the robustness to the sparsity. Moreover, voxel based methods might divide the points with different categories into the same cell and cell label encoding would inevitably cause the information loss (for LiDAR-based segmentation tasks). To alleviate the interference of lossy label encoding, a point-wise module is introduced to further refine the features obtained from voxel-based network. Overall, the cooperation of these components well maintains the geometric relation and tackle the difficulty of outdoor point cloud, thus improving the effectiveness of 3D frameworks. Since the learned features from our model can be used for downstream tasks, we benchmark our model on a variety of LiDAR-based perception tasks such LiDAR-based semantic segmentation, panoptic segmentation and 3D detection. For semantic segmentation, we evaluate the proposed method on several large-scale outdoor datasets, including SemanticKITTI~\cite{behley2019semantickitti}, nuScenes~\cite{nuscenes} and A2D2~\cite{geyer2019a2d2}. Our method achieves the state-of-the-art on the leaderboard of SemanticKITTI (both single-scan and multi-scan challenges) and also outperforms the existing methods on nuScenes and A2D2 with a large margin. We also extend the proposed cylindrical partition and asymmetrical 3D convolution networks to LiDAR panoptic segmentation and LiDAR 3D detection. For panoptic segmentation and 3D detection, experimental results on SemanticKITTI and nuScenes, respectively, show its strong performance and good generalization capability. The contributions of this work mainly lie in three aspects: \begin{itemize} \item[(1)] We reposition the focus of outdoor LiDAR segmentation from 2D projection to 3D structure, and further investigate the inherent properties (difficulties) of outdoor point cloud. \item[(2)] We introduce a new framework to explore the 3D geometric pattern and tackle these difficulties caused by sparsity and varying density, through cylindrical partition and asymmetrical 3D convolution networks. \item[(3)] The proposed method achieves the state of art on LiDAR-based semantic segmentation, LiDAR panoptic segmentation and LiDAR point cloud 3D detection, which also demonstrates its strong generalization capability. \end{itemize} \section{Methodology} \label{sec:methods} \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{cylinder_stat3.pdf} \caption{The proportion of non-empty cells at different distances between cylindrical and cubic partition (The results are calculated on the training set of SemanticKITTI). It can be found that cylinder partition makes a higher non-empty proportion and more balanced point distribution, especially for farther-away regions.} \label{fig:stat3} \end{figure} \begin{figure*}[t] \centering \includegraphics[width=1.0\linewidth]{cylinder2new.pdf} \caption{The pipeline of cylindrical partition. We first transform the Cartesian coordinate to Cylinder coordinate and then assign the point-wise features to the structured representation based on the Point-Cylinder mapping table. The cylindrical features are obtained via max-pooling these point-wise features inside each cylinder.} \label{fig:cylinder} \end{figure*} \subsection{Framework Overview} As shown in the top and middle row of Fig.~\ref{fig:pipeline}, we elaborate the pipeline of our model in LiDAR-based segmentation and detection task. In the context of semantic segmentation, given a point cloud, the task is to assign the semantic label to each point. Based on the comparison between 2D and 3D representation and investigation of the inherent properties of outdoor LiDAR point cloud, we desire to obtain a framework which explores the 3D geometric information and handles the difficulty caused by sparsity and varying-density. To this end, we propose a new outdoor segmentation approach based on the 3D partition and 3D convolution networks. To handle these difficulties of outdoor LiDAR point cloud, namely sparsity and varying density, we first employ the cylindrical partition to generate the more balanced point distribution (more robust to varying density), then apply the asymmetrical 3D convolution networks to power the horizontal and vertical weights, thus well matching the object point distribution in driving scene and enhancing the robustness to the sparsity. Same backbone with cylindrical partition and asymmetrical convolution network is also adapted to LiDAR-based 3D detection (shown in the middle row of Fig.~\ref{fig:pipeline}). Specifically, the framework consists of two major components, including cylindrical partition and asymmetrical 3D convolution networks. The LiDAR point cloud is first divided by the cylindrical partition and the features extracted from MLP is then reassigned based on this partition. Asymmetrical 3D convolution networks are then used to generate the voxel-wise outputs. For segmentation tasks, a point-wise module is introduced to alleviate the interference of lossy cell-label encoding, thus refining the outputs. In the following sections, we will present these components in detail. \subsection{Cylindrical Partition} As mentioned above, outdoor-scene LiDAR point cloud possesses the property of varying density, where nearby region has much greater density than farther-away region. Therefore, uniform cells splitting the varying-density points would fall into an imbalanced distribution (for example, larger proportion of empty cells). While in the cylinder coordinate system, it utilizes the increasing grid size to cover the farther-away region, and thus more evenly distributes the points across different regions and gives an more balanced representation against the varying density. We perform a statistic to show the proportion of non-empty cells across different distances in Fig.~\ref{fig:stat3}. It can be found that with the distance goes far, cylindrical partition maintains a balanced non-empty proportion due to the increasing grid size while cubic partition suffers the imbalanced distribution, especially in the farther-away regions (about 6 times less than cylindrical partition). Moreover, unlike these projection-based methods project the point to the 2D view, cylindrical partition maintains the 3D grid representation to retain the geometric structure. The workflow is illustrated in Fig.~\ref{fig:cylinder}. We first transform the points on Cartesian coordinate system to the Cylinder coordinate system. This step transforms the points ($x, y, z$) to points ($\rho, \theta, z$), where radius $\rho$ (distance to origin in x-y axis) and azimuth $\theta$ (angle from x-axis to y-axis) are calculated. Then cylindrical partition performs the split on these three dimensions, note that in the cylinder coordinate, the farther-away the region is, the larger the cell will be. Point-wise features obtained from the MLP are reassigned based on the result of this partition to get the cylindrical features. Specifically, the point-cylinder mapping contains the index of point-wise features to cylinder. Based on this mapping function, point-wise features within same cylinder are mapped together and processed via max-pooling to get the cylindrical features. After these steps, we unroll the cylinder from 0-degree and get the 3D cylindrical representation $\mathbb{F}\in C \times H\times W \times L$, where $C$ denotes the feature dimension and $H, W, L$ mean the radius, azimuth and height. Subsequent asymmetrical 3D convolution networks will be performing on this representation. \begin{figure*}[t] \centering \includegraphics[width=1.0\linewidth]{fea_vis.pdf} \caption{Filter activation visualization. We visualize some filters at second downsampling block from regular 3D convolution networks (with cubic partition) (Fig.5 (a) and (b)) and asymmetrical 3D convolution networks (with cylindrical partition) (Fig.5 (c) and (d)), respectively. Since each filter in 3D convolution networks has size of H$\times$W$\times$L, we use the mean value of L dimension as the activation value. Fig (a) and (c) are extracted from 100th filter and Fig (b) and (d) are extracted from 120th filter. It can be observed that the filters from the proposed asymmetrical 3D convolution networks are sparsely activated in some certain regions while the regular convolution covers most parts.} \label{fig:acti} \end{figure*} \subsection{Asymmetrical 3D Convolution Network} Since the driving-scene point cloud carries out the specific object shape distribution, including car, truck, bus, motorcycle and other cubic objects, we aim to follow this observation to enhance the representational power of a standard 3D convolution. Moreover, recent literature~\cite{wang2019shape,ding2019acnet} also shows that the central crisscross weights count more in the square convolution kernel. In this way, we devise the asymmetrical residual block to strengthen the horizontal and vertical responses and match the object point distribution. Based on the proposed asymmetrical residual block, we further build the asymmetrical downsample block and asymmetrical upsample block to perform the downsample and upsample operation. Moreover, a dimension-decomposition based context modeling (termed as DDCM) is introduced to explore the high-rank global context in decomposite-aggregate strategy. We detail these components in the bottom of Fig.~\ref{fig:pipeline} \begin{figure} \centering \begin{subfigure}[t]{0.45\linewidth} \centering \includegraphics[width=1\linewidth]{fan-kernel_car.png} \caption{Car} \label{fig:asym1} \end{subfigure} \begin{subfigure}[t]{0.45\linewidth} \includegraphics[width=1\linewidth]{fan-kernel_motor.png} \caption{Motorcycle} \label{fig:asym2} \end{subfigure} \vspace{-1ex} \caption{An illustration of asymmetrical residual block, where two asymmetrical kernels are stacked to power the skeleton. It can be observed that asymmetrical residual block focuses on the horizontal and vertical kernels.} \label{fig:asym} \end{figure} \myparagraph{Asymmetrical Residual Block} Motivated by the observation and conclusion in~\cite{wang2019shape,ding2019acnet}, the asymmetrical residual block strengthens the horizontal and vertical kernels, which matches the point distribution of object in the driving scene and explicitly makes the skeleton of the kernel powerful, thus enhancing the robustness to the sparsity of outdoor LiDAR point cloud. We use the Car and Motorcycle as the example to show the asymmetrical residual block in Fig.~\ref{fig:asym}, where 3D convolutions are performing on the cylindrical grids. Moreover, the proposed asymmetrical residual block also saves the computation and memory cost compared to the regular square-kernel 3D convolution block. By incorporating the asymmetrical residual block, the asymmetrical downsample block and upsample block are designed and our asymmetrical 3D convolution networks are built via stacking these downsample and upsample blocks. \myparagraph{Dimension-Decomposition based Context Modeling} Since the global context features should be high-rank to have enough capacity to capture the large context varieties~\cite{zhang2019co}, it is hard to construct these features directly. We follow the tensor decomposition theory~\cite{chen2020tensor} to build the high-rank context as a combination of low-rank tensors, where we use three rank-1 kernels to obtain the low-rank features and then aggregate them together to get the final global context. \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{cylinder_stat2.pdf} \caption{Upper bound of mIoU with different label encoding methods (\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, majority and minority encoding). It can be found that no matter what encoding methods are, the information loss always occurs, which is also the reason for point-wise refinement. } \label{fig:stat2} \end{figure} \subsection{Sparse Activation Visualization} As mentioned above, the proposed cylindrical partition and asymmetrical 3D networks aim to tackle the difficulties caused by sparsity and varying-density in outdoor point cloud. We thus visualize some filter activations from regular 3D convolution networks (with regular cubic partition) and asymmetrical 3D convolution networks (with cylindrical partition), respectively. The results are shown in Fig.~\ref{fig:acti}. Fig.~\ref{fig:acti}(a) and (b) are extracted from regular 3D convolution networks, which are activated at almost regions; While the proposed asymmetrical 3D convolution networks strengthen sparser activations and focus on them (as shown in Fig.~\ref{fig:acti}(c) and (d)), they mainly focus on some certain regions. It demonstrates that the proposed model could adaptively handle the sparse point cloud input and focus on some certain regions. \subsection{Point-wise Refinement Module} Partition-based methods predict one label for each cell. Although partition-based methods effectively explore the large-range point cloud, however, this group of method, including cube-based and cylinder-based, inevitably suffers from the lossy cell-label encoding, \emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot, points with different categories are divided into same cell, and this case would cause the information loss for point cloud semantic segmentation task (as shown in the middle row of Fig.~\ref{fig:pipeline}). We make a statistic to show the effect of different label encoding methods with cylindrical partition in Fig.~\ref{fig:stat2}, where \emph{majority encoding} means using the major category of points inside a cell as the cell label and \emph{minority encoding} indicates using the minor category as the cell label. It can be observed that both of them cannot reach the 100 percent mIoU (ideal encoding) and inevitably have the information loss. Here, the point-wise refinement module is introduced to alleviate the interference of lossy cell-label encoding. We first project the cylindrical features to the point-wise based on the inverse point-cylinder mapping table (note that points inside same cylinder would be assigned to the same cylindrical features). Then the point-wise module takes both point features before and after 3D convolution networks as the input, and fuses them together to refine the output. We also show the detailed structure of MLPs in point-wise refinement module and cylindrical partition in Fig.~\ref{fig:prnet}. \begin{figure}[t] \centering \includegraphics[width=0.8\linewidth]{prnet.pdf} \caption{Detailed workflow of MLPs in Cylindrical Partition and Point-wise Refinement Module.} \label{fig:prnet} \end{figure} \subsection{Objective Function} For LiDAR-based semantic segmentation task, the total objective of our method consists of two components, including voxel-wise loss and point-wise loss. It can be formulated as $\mathbb{L} = \mathbb{L}_{voxel} + \mathbb{L}_{point}$. For the voxel-wise loss ($\mathbb{L}_{voxel}$), we follow the existing methods~\cite{cortinhal2020salsanext,hu2020randla} and use the weighted cross-entropy loss and lovasz-softmax~\cite{berman2018lovasz} loss to maximize the point accuracy and the intersection-over-union score, respectively. For point-wise loss ($\mathbb{L}_{point}$), we only use the weighted cross-entropy loss to supervise the training. During inference, the output from point-wise refinement module is used as the final output. For LiDAR-based panoptic segmentation task, except the loss of semantic segmentation, it also contains the loss of instance branch~\cite{hong2020lidar}, which utilizes center regression to achieve the clustering. For LiDAR-based 3D detection, we follow previous work~\cite{zhu2020ssn,yan2018second} to use the focal loss and smooth L1 loss for classification and regression, respectively. \section{Related Work} \begin{figure*} \centering \includegraphics[width=1.0\linewidth]{pipeline.pdf} \caption{(1): Top row is the overall framework for LiDAR segmentation. Here, LiDAR point cloud is fed into MLP to get the point-wise features and then these features are reassigned based on the cylindrical partition. Asymmetrical 3D convolution networks are then used to generate the voxel-wise outputs. Finally, a point-wise module is introduced to refine these outputs. (2): Middle part shows the workflow of LiDAR 3D detection, where point-wise refinement is not attended. (3): Bottom row elaborates four components, including Asymmetrical Downsample block (AD), Asymmetrical Upsample blcok (AU), Asymmetrical residual block (A) and Dimension-Decomposition based Context Modeling (DDCM).} \label{fig:pipeline} \end{figure*} \myparagraph{Deep Learning for Indoor-scene Point Cloud.} Indoor-scene point clouds carry out some properties, including generally uniform density, small number of points, and small range of the scene. Mainstream methods~\cite{qi2017pointnet, thomas2019kpconv, wu2019pointconv, wang2019dynamic,velivckovic2017graph, lyu2020learning, engelmann20203d, zhang2020fusion, yan2020pointasnl,wang2019graph,pham2019jsis3d,qi20173d} of indoor point cloud segmentation learn the point features based on the raw point directly, which are often based on the pioneering work, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, PointNet, and promote the effectiveness of sampling, grouping and ordering to achieve the better performance. Another group of methods utilize the clustering algorithm~\cite{wang2019dynamic,velivckovic2017graph} to extract the hierarchical point features. However, these methods focusing on indoor point cloud are limited to adapt to the outdoor point cloud under the property of varying density and large range of scenes, and the large number of points also result in the computational difficulties for these methods when deploying from indoor to outdoor. \myparagraph{Deep Learning for Outdoor-scene Point Cloud.} Most existing approaches for outdoor-scene point cloud~\cite{hu2020randla,cortinhal2020salsanext,zhao2021lif,milioto2019rangenet++,alonso20203d,zhang12356deep,landrieu2018large,hong2020lidar,cong2021input} focus on converting the 3D point cloud to 2D grids, to enable the usage of 2D Convolutional Neural Networks. SqueezeSeg~\cite{wu2018squeezeseg}, Darknet~\cite{behley2019semantickitti}, SqueezeSegv2~\cite{wu2019squeezesegv2}, and RangeNet++~\cite{milioto2019rangenet++} utilize the spherical projection mechanism, which converts the point cloud to a frontal-view image or a range image, and adopt the 2D convolution network on the pseudo image for point cloud segmentation or detection task. PolarNet~\cite{zhang2020polarnet} follows the bird's-eye-view projection, which projects point cloud data into bird's-eye-view representation under the polar coordinates. However, these 3D-to-2D projection methods inevitably loss and alter the 3D topology and fails to model the geometric information. Moreover, in most outdoor scenes, LiDAR device is often used to produce the point cloud data, where its inherent properties, \emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot, sparsity and varying density , are often neglected. \myparagraph{3D Voxel Partition.} 3D voxel partition is another routine of point cloud encoding~\cite{han2020occuseg,tchapmi2017segcloud,graham20183d,cciccek20163d,meng2019vv,cylinder3d1,cylinder3d2}. It converts a point cloud into 3D voxels, which mainly retains the 3D geometric information. OccuSeg~\cite{han2020occuseg}, SSCN~\cite{graham20183d} and SEGCloud~\cite{tchapmi2017segcloud} follow this line to utilize the voxel partition and apply regular 3D convolutions for LiDAR segmentation. It is worth noting that while the aforementioned efforts have shown encouraging results, the improvement in the outdoor LiDAR point cloud remains limited. As mentioned above, a common issue is that these methods neglect the inherent properties of outdoor LiDAR point cloud, namely, sparsity and varying density. Compared to these methods, our proposed method resorts to the 3D cylindrical partition and asymmetrical 3D convolution networks to tackle these difficulties. \myparagraph{Network Architectures for Feature Extraction}. Fully Convolutional Network~\cite{long2015fully} is the fundamental work for segmentation tasks in the deep-learning era. Built upon the FCN, many works aim to improve the performance via exploring the dilated convolution, multi-scale context modeling and attention modeling, including DeepLab\cite{chen2017deeplab, chen2018encoder} and PSP~\cite{zhao2017pyramid}. Recent work utilizes the neural architecture search to find the more effective backbone for the segmentation~\cite{liu2019auto,tang2020searching}. Particularly, U-Net~\cite{ronneberger2015u} proposes a symmetric architecture to incorporate the low-level features. With the great success of U-Net on 2D benchmarks and its good flexibility , many studies for LiDAR-based perception often adapt the U-Net to the 3D space~\cite{cciccek20163d}. We also follow this structure to construct our asymmetrical 3D convolution networks.
{'timestamp': '2021-09-14T02:19:46', 'yymm': '2109', 'arxiv_id': '2109.05441', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05441'}
arxiv
\section{Introduction}\label{sec1} \IEEEPARstart{M}{assive multiple-input multiple-output} (mMIMO) is a well-recognized radio frequency (RF) technology for highly spectrum-efficient communications \cite{6375940}. Current mMIMO technology has two main architectures, i.e., the analogue-digital hybrid architecture and the fully digital (FD) architecture (see \cite{1519678}). In the FD-mMIMO system, every antenna element is connected to a dedicated RF chain. It has been revealed that the energy consumption of each RF chain grows exponentially with the resolution of signal quantizers \cite{6457363, 761034}. This has recently motivated the use of low-resolution (mainly $1$-$3$ bit) quantizers for FD-mMIMO (e.g. \cite{5351659, DBLP:journals/corr/RisiPL14, 6891254}). The information-theoretic study of low-resolution quantized FD-mMIMO can be found in the literature (e.g. \cite{6891254, 7106472, 7080890}). In the scope of estimation and detection theory, digital signal processing problems such as channel estimation, synchronization and signal detection can be fundamentally changed due to the use of low-resolution quantizers \cite{6987288, 7088639, 9311778 }. This is because wireless systems become non-linear and non-Gaussian, and such violates the hypothesis of linear and Gaussian process that is commonly adopted in the conventional MIMO systems. Specifically for the signal detection problem, the maximum-likelihood detection becomes even more complicated as it is no longer equivalent to the integer least-squares problem \cite{4475570,9145094}. This is particularly true for FD-mMIMO systems with $1$-bit quantizers. In order to improve the computational efficiency, a number of near-maximum-likelihood algorithms have been reported in the literature (e.g. \cite{7439790, 8240630, 8345169}). However, they are still too complex to implement in practice. Approximate message passing (AMP) algorithms could offer near Bayesian-optimum solutions with much lower computational complexities (e.g. \cite{7355388, 7426735, 8234637}). Nevertheless, linear algorithms are practically more appealing for their lower complexities and simple architectures. The foundation of linear detection algorithms lies in a linear system model. Therefore, the central task of linear algorithm design is to find a good linear approximation of the non-linear communication system. In the literature, one of the widely used linear approximation models is the additive quantization noise model (AQNM) originally proposed in \cite{mezghani11}. It assumes the quantization distortion to be additive white Gaussian noise (AWGN) and correlated with the input of the quantizer. With the AQNM model, the LMMSE channel equalization and symbol-by-symbol detection algorithm has been extensively studied. Moreover, the AQNM model has been employed for the information-theoretic study of the achievable rate, capacity bounds or spectral efficiencies in \cite{7307134, 7308988, 7876856, 7896590, 7420605}. In \cite{Mezghani2012}, a modified-AQNM model has been proposed by making the quantization noise uncorrelated with the input signal through Wiener-Hopf filtering. This modified version renders the derivation of auto-covariances and cross-covariances involved in the LMMSE analysis much easier. When the input signal is white Gaussian, we show in Section \ref{sec2b2} that the modified-AQNM is equivalent to the original AQNM model. Using the Bussgang's theory\footnote{Please see \cite{Bussgang52} for the detail of Bussgang's theory.}, the modified-AQNM model has been further generalized. Specifically for the $1$-bit quantization, the quantization noise is actually far from the Gaussian assumption. Then, the Bussgang's theory has been used in \cite{Mezghani2012} to derive an exact form of the relevant auto-covariances and cross-covariances for the LMMSE channel equalizer. Other relevant works that use the Bussgang's theory for linear receiver design or performance analysis can be found in \cite{nguyen2019linear,7931630,7894211}. The hypothesis of Gaussian quantization noise renders the AQNM model and its variations not sufficiently accurate for some cases (see the detailed discussion in \cite{8337813}). Moreover, it has been observed that the AQNM-based LMMSE channel equalizer can introduce a scalar ambiguity in the signal amplitude. This scalar ambiguity is not a problem for constant-modulus modulations such as M-ary phase-shift-keying (M-PSK). However, it is detrimental to non-constant-modulus modulations such as M-ary quadrature-amplitude-modulation (M-QAM), and thus it must be appropriately handled for instance through the energy normalization \cite{7439790,nguyen2019linear,tsefunda}. After all, the major concern is that the inaccuracy of the AQNM models could disadvantage the receiver optimization as far as non-constant-modulus modulations are concerned \cite{9144509,7247358}. Arguably, the generalized-AQNM model does take into account the scaling ambiguities. However, we find the current studies rather intuitive, and that a more rigorous analytical study is needed to develop a deeper understanding of the quantization distortion as well as its impact on the LMMSE channel equalizer. This forms the major motivation of our work. The major contribution of our work lies in the employment of Hermite polynomials to develop the aforementioned deeper understanding. This study results in a novel linear approximation model using the second-order Hermite expansion (SOHE). In brief, the SOHE model can be described by the following vector form (see the detail in Section \ref{sec3}) \begin{equation}\label{eqn001} \mathbf{y}=\mathcal{Q}_b(\mathbf{r})\approx\lambda_b\mathbf{r}+\mathbf{q}_b, \end{equation} where $\mathcal{Q}_b(\cdot)$ is the $b$-bit uniform quantizer introduced in \cite{Proakis2007}, $\mathbf{r}, \mathbf{y}\in\mathbb{C}^{K\times 1}$ are the input and output of the quantizer, respectively, $\lambda_b$ is the coefficient of the first-order Hermite kernel which is a function of the resolution of the quantizer ($b$), and $\mathbf{q}_b\in\mathbb{C}^{K\times 1}$ is the quantization distortion with its characteristics related to the resolution of the quantizer ($K$: the size of relevant vectors). The SOHE model differs from the existing AQNM models mainly in two folds: {\em 1)} The Hermite coefficient ($\lambda_b$) in the SOHE model describes how the signal energy changes with respect to the resolution of the quantizer. The relationship between $\lambda_b$ and the resolution $b$ is mathematically formulated, based on which the characteristics of $\lambda_b$ are exhibited through our analytical work. {\em 2)} The quantization distortion ($\mathbf{q}_b$) is modeled as the second-order Hermite polynomial of the input signal ($\mathbf{r}$). There is no imposed assumption for the quantization distortion to be white Gaussian as well as their correlation behavior with the input signal. It will be shown in Section \ref{sec3}, through mathematical analysis, that the cross-correlation between $\mathbf{q}_b$ and the input $\mathbf{r}$ depends on the stochastic behavior of the input signal. When the input is an independent white Gaussian process, the quantization distortion can be considered to be uncorrelated with the input signal. With the above distinctive features, we find that the SOHE model can be used to explain almost all interesting phenomena observed so far in the research of low-resolution quantized MIMO signal detection. When using the SOHE model for the LMMSE analysis, our analytical work shows that the current LMMSE algorithm should be enhanced by incorporating a symbol-level normalization mechanism, and thereby resulting in an enhanced-LMMSE (e-LMMSE) channel equalizer. The performance gain of e-LMMSE is demonstrated through extensive computer simulations in Rayleigh fading channels. In addition, as response to the reviewers' comments, we enrich our technical contribution with the SOHE-based LMMSE channel estimation approach. It is found that the SOHE-LMMSE channel estimator can offer comparable sum spectral efficiency (SE) with the state-of-the-art (SOTA) because the performance is limited by the channel estimation error. The rest of this paper is organized as follows. Section II presents the system model, preliminaries and problem statement. Section III presents the Hermite expansion model. Section IV presents the LMMSE analysis. Section V presents the simulation results, and finally Section VI draws the conclusion. \subsubsection*{Notations} Regular letter, lower-case bold letter, and capital bold letter represent scalar, vector, and matrix, respectively. $\Re(\cdot)$ and $\Im(\cdot)$ represent the real and imaginary parts of a complex number, respectively. The notations $[\cdot]^T$, $[\cdot]^H$, $[\cdot]^*$, $[\cdot]^{-1}$, $\left \| \cdot \right \|$, $\mathrm{trace}(\cdot)$ and $\mathbb{D}(\cdot)$ represent the transpose, Hermitian, conjugate, inverse, Euclidean norm, trace and a matrix formed by the diagonal of a matrix (a vector or a scalar if appropriate), respectively. $\mathbb{E}\left [ \cdot \right ]$ denotes the expectation, $\mathbf{I}$ denotes the identity matrix, and $\otimes$ denotes the Kronecker product. \section{System Model, Preliminaries and\\ Problem Statement}\label{sec2} This section introduces the mathematical model of the uplink MIMO signal reception with low-resolution quantizers. This is then followed by a review of current linear approximation models as well as their related LMMSE channel equalizers. This review is important in the sense that it can help to understand the SOTA as well as their differences from the SOHE model. It is perhaps worth noting that we do not put an emphasis on the mMIMO system mainly to keep our work as generic as possible. \subsection{System Model}\label{sec2a} Similar to many other works in the SOTA analysis (e.g. \cite{7307134, 7876856, 7896590, 7420605}), we also consider a narrowband FD-mMIMO network, where a set of single-antenna transmitters $(N)$ simultaneously send their messages to a receiver having a large number of receive antennas $(K)$. Denote $s_n$ to be the information-bearing symbol sent by the $n^\mathrm{th}$ transmitter ($n=0,...,N-1$). It is commonly assumed that $s_n$ is drawn from a finite alphabet-set with equal probability and fulfills: $\mathbb{E}(s_n)=0$, $\mathbb{E}(s_ns_n^*)=1$, $\mathbb{E}(s_ns_m^*)=0$, $_{\forall n\neq m}$. With the ideal quantization, the received discrete-time signal at the baseband ($\mathbf{r}$) is expressible as \begin{equation}\label{eqn002} \mathbf{r}=\sum_{n=0}^{N-1}\mathbf{h}_ns_n+\mathbf{v}, \end{equation} where $\mathbf{h}_n\in\mathbb{C}^{K\times1}$ is the channel vector corresponding to the $n^\mathrm{th}$ transmitter to the receiver link, and $\mathbf{v}\in\mathbb{C}^{K\times1}$ is the white Gaussian thermal noise with zero mean and auto-covariance $N_0\mathbf{I}$. Define $\mathbf{H}\triangleq[\mathbf{h}_0, ..., \mathbf{h}_{N-1}]$ and $\mathbf{s}\triangleq[s_0,...,s_{N-1}]^T$. The linear model \eqref{eqn002} can be rewritten into the following matrix form \begin{equation}\label{eqn003} \mathbf{r}=\mathbf{H}\mathbf{s}+\mathbf{v}. \end{equation} Feeding $\mathbf{r}$ into the $b$-bit low-resolution quantizer results in \begin{equation}\label{eqn004} \mathbf{y}=\mathcal{Q}_b(\Re(\mathbf{r}))+j\mathcal{Q}_b(\Im(\mathbf{r})), \end{equation} where the quantization is individually performed in the real and imaginary domains. To reconstruct the signal block $\mathbf{s}$ at the receiver (i.e., the signal detection), the channel knowledge $\mathbf{H}$ is usually assumed in the literature (e.g. \cite{5592653, 8320852, 8610159, 7155570}). There are also quite a few published works discussing about the channel estimation as well as the signal reconstruction based upon various channel knowledge imperfections (e.g. \cite{7439790, 7355388, 7247358, 5501995, 708938}). Those are indeed very interesting research issues. However, in order to make our work well focused on the signal reconstruction, we assume the availability of $\mathbf{H}$ throughout the paper and describe the signal reconstruction procedure as the following input-output relationship \begin{equation}\label{eqn005} \hat{\mathbf{s}}=g(\mathbf{y}, \mathbf{H}), \end{equation} where $\hat{\mathbf{s}}$ is the reconstructed version of $\mathbf{s}$. In the following contents, our discussion will be focused on the linear approximation models and LMMSE analysis. Optimum and near-optimum approaches are not relevant to our discussion and therefore skipped. \subsection{Linear Approximation Models and LMMSE Analysis}\label{sec2b} Our SOTA analysis shows that there are mainly three linear models to approximate the non-linear model \eqref{eqn004}, and they can lead to different LMMSE formulas. \subsubsection{The AQNM Model}\label{sec2b1} this model can be mathematically described by (see \cite{mezghani11, 5351659}) \begin{equation}\label{eqn006} \mathbf{y}\approx\mathbf{z}_A\triangleq\mathbf{r}+\mathbf{q}_A. \end{equation} There are two assumptions for the AQNM model: \begin{itemize} \item[A1)] The quantization distortion $\mathbf{q}_A$ is AWGN; \item[A2)] $\mathbf{q}_A$ is correlated with the input signal $\mathbf{r}$. \end{itemize} With this linear approximation model, the LMMSE channel equalizer ($\mathbf{G}^\star$) can be obtained by solving the following MMSE objective function \begin{IEEEeqnarray}{ll} \mathbf{G}^\star&=\underset{\mathbf{G}}{\arg\min}~\mathbb{E}\|\mathbf{s}-\mathbf{G}\mathbf{y}\|^2,\label{eqn007}\\ &\approx\underset{\mathbf{G}}{\arg\min}~\mathbb{E}\|\mathbf{s}-\mathbf{G}\mathbf{z}_A\|^2\label{eqn008}. \end{IEEEeqnarray} The solution to \eqref{eqn008} is provided in \cite{mezghani11}, i.e., \begin{equation}\label{eqn009} \mathbf{G}^\star=\mathbf{H}^H(N_0\mathbf{I}+\mathbf{HH}^H+\mathrm{nondiag}(\rho_b\mathbf{HH}^H))^{-1}, \end{equation} where $\rho_b$ is the distortion factor indicating the relative amount of quantization noise generated, and it is a function of $b$; see the specific discussion in the relevant literature \cite{1057548, 6891254, 7106472}. \subsubsection{The Modified-AQNM Model}\label{sec2b2} the mathematical form of this linear model is given by (see \cite{Mezghani2012}): \begin{equation}\label{eqn010} \mathbf{y}\approx\mathbf{z}_B\triangleq\mathbf{C}_{yr}\mathbf{C}_{rr}^{-1}\mathbf{r}+\mathbf{q}_B, \end{equation} where $\mathbf{C}_{yr}$ is the cross-covariance matrix between $\mathbf{y}$ and $\mathbf{r}$, $\mathbf{C}_{rr}$ is the auto-covariance matrix of $\mathbf{r}$, and $\mathbf{q}_B$ is the quantization distortion. Different from the AQNM model in \eqref{eqn006}, the assumption here is: \begin{itemize} \item[A3)] the quantization distortion $(\mathbf{q}_B)$ is uncorrelated with the input signal $\mathbf{r}$. \end{itemize} Moreover, the condition A1) is not always assumed. Define $\overline{\mathbf{H}}\triangleq\mathbf{C}_{yr}\mathbf{C}_{rr}^{-1}\mathbf{H}$ and $\mat{\varepsilon}\triangleq\mathbf{C}_{yr}\mathbf{C}_{rr}^{-1}\mathbf{v}+\mathbf{q}_B$. The modified-AQNM model \eqref{eqn010} can be represented by the following canonical form \begin{equation}\label{eqn011} \mathbf{z}_B=\overline{\mathbf{H}}\mathbf{s}+\mat{\varepsilon}. \end{equation} The auto-covariance matrix of $\mat{\varepsilon}$ is given by \cite[(9)]{Mezghani2012}, \begin{equation}\label{eqn012} \mathbf{C}_{\varepsilon\varepsilon}=\mathbf{C}_{yy}-\mathbf{C}_{yr}\mathbf{C}_{rr}^{-1}\mathbf{C}_{ry} +N_0\mathbf{C}_{yr}\mathbf{C}_{rr}^{-1}\mathbf{C}_{rr}^{-1}\mathbf{C}_{ry}. \end{equation} This is however too complex for the LMMSE analysis. Applying the assumption A1) onto the quantization distortion $\mathbf{q}_B$, it has been shown that the following approximation of covariance matrices applies \begin{equation}\label{eqn013} \mathbf{C}_{ry}\approx(1-\rho_b)\mathbf{C}_{rr}\approx\mathbf{C}_{yr}, \end{equation} \begin{equation}\label{eqn014} \mathbf{C}_{\varepsilon\varepsilon}\approx(1-\rho_b)^2N_0\mathbf{I}+(1-\rho_b)\rho_b\mathbb{D}(\mathbf{C}_{rr}). \end{equation} Applying \eqref{eqn013} into \eqref{eqn011} results in \begin{equation}\label{eqn015} \mathbf{z}_B\approx(1-\rho_b)\mathbf{H}\mathbf{s}+\mat{\varepsilon}. \end{equation} Then, the LMMSE objective function reads as \begin{equation}\label{eqn016} \mathbf{G}^\star=\underset{\mathbf{G}}{\arg\min}~\mathbb{E}\|\mathbf{s}-\mathbf{G}\mathbf{z}_B\|^2. \end{equation} Solving \eqref{eqn016} results in \begin{equation}\label{eqn017} \mathbf{G}^\star=(1-\rho_b)^{-1}\mathbf{H}^H\Big(\mathbf{C}_{rr}+\frac{\rho_b}{1-\rho_b}\mathbb{D}(\mathbf{C}_{rr}) \Big)^{-1}, \end{equation} where $\mathbf{C}_{rr}=\mathbf{HH}^H+N_0\mathbf{I}$. This equation seems to be different from \eqref{eqn009}. However, if we incorporate the term $(1-\rho_b)^{-1}$ into the auto-covariance term inside the bracket, \eqref{eqn017} immediately turns into \eqref{eqn009}. Arguably, we can consider the linear approximations \eqref{eqn006} and \eqref{eqn010} to be equivalent when the assumption A1) is adopted. \subsubsection{The Generalized-AQNM Model}\label{sec2b3} the modified-AQNM model can be extended to the following generalized version (see \cite{Mezghani2012}) \begin{equation}\label{eqn018} \mathbf{z}_C=\mathbf{\Lambda}_b\mathbf{r}+\mathbf{q}_C, \end{equation} where the quantization distortion $\mathbf{q}_C$ is assumed to be uncorrelated with $\mathbf{r}$ (i.e., the assumption A3), and $\mathbf{\Lambda}_b$ is a diagonal matrix with its characteristics related to the low-resolution quantizer. Consider the quantizer $y=\mathcal{Q}_b(x),~x\in(-\infty, \infty)$, to be a stair function with its input range being divided into $M=2^b$ sub-ranges \footnote{ The dynamic of sub-ranges is promised by the automatic gain control (AGC), which aims at keeping the amplitude of the output signal $y$ substantially constant or to vary only within a small range \cite{664234, 1092057}. In order to focus on the analysis of the low-resolution quantization process, the ideal AGC is assumed in this paper.} . Define $(\tau_m, \tau_{m+1})$ to be the $m^\mathrm{th}$ sub-range. The quantizer can be represented by \begin{equation}\label{eqn019} \mathcal{Q}_b(x)=x_m,~x\in(\tau_m, \tau_{m+1}),~_{m=0, ..., M-1,} \end{equation} where in general $x_m$ can be an appropriately chosen value within the range of $(\tau_m, \tau_{m+1})$ depending on the design specification \cite{1057548,Liu2021vtc}; and $\tau_0=-\infty$, $\tau_{M}=\infty$. Then, the diagonal matrix $\mathbf{\Lambda}_b$ is expressed by \begin{IEEEeqnarray}{ll}\label{eqn020} \mathbf{\Lambda}_b&=\mathbb{D}(\mathbf{C}_{rr})^{-\frac{1}{2}} \sum_{m=0}^{M-1}\frac{x_m}{\sqrt{\pi}}\Big( \exp(-\tau_m^2\mathbb{D}(\mathbf{C}_{rr})^{-1})\nonumber\\ &\quad\quad\quad\quad\quad\quad\quad\quad-\exp(-\tau_{m+1}^2\mathbb{D}(\mathbf{C}_{rr})^{-1})\Big). \end{IEEEeqnarray} Generally, the analysis of $\mathbf{C}_{\varepsilon\varepsilon}$ is highly complex, and it does not result in a closed-form solution. Specifically for the special case of symmetric $1$-bit quantization, the assumption of Gaussian quantization noise is not suitable. Using the Bussgang's theorem, the approximations \eqref{eqn013}-\eqref{eqn014} can now be replaced by the exact forms (a slightly alternated version from \cite{Mezghani2012, nguyen2019linear}) \begin{equation}\label{eqn021} \mathbf{C}_{yr}=\sqrt{\frac{2}{\pi}}\mathbb{D}(\mathbf{C}_{rr})^{-\frac{1}{2}}\mathbf{C}_{rr}, \end{equation} \begin{IEEEeqnarray}{ll}\label{eqn022} \mathbf{C}_{\varepsilon\varepsilon}=&\frac{2}{\pi}\Big[\arcsin\Big(\mathbb{D}(\mathbf{C}_{rr})^{-\frac{1}{2}}\mathbf{C}_{rr}\mathbb{D}(\mathbf{C}_{rr})^{-\frac{1}{2}}\Big)-\nonumber\\ &\mathbb{D}(\mathbf{C}_{rr})^{-\frac{1}{2}}\mathbf{C}_{rr}\mathbb{D}(\mathbf{C}_{rr})^{-\frac{1}{2}}+ N_0\mathbb{D}(\mathbf{C}_{rr})^{-1}\Big]. \end{IEEEeqnarray} Applying the above results for the LMMSE analysis leads to \begin{equation}\label{eqn023} \mathbf{z}_B=\sqrt{\frac{2}{\pi}}\mathbb{D}(\mathbf{C}_{rr})^{-\frac{1}{2}}\mathbf{H}\mathbf{s}+\mat{\varepsilon}. \end{equation} With \eqref{eqn018}-\eqref{eqn020}, it is rather trivial to obtain the following form of LMMSE \begin{equation}\label{eqn024} \mathbf{G}^\star=\sqrt{\frac{2}{\pi}}\mathbb{D}(\mathbf{C}_{rr})^{-\frac{1}{2}}\mathbf{H} \Big(\mathbf{C}_{\varepsilon\varepsilon}+\frac{2}{\pi}\mathbb{D}(\mathbf{C}_{rr})^{-1}\mathbf{HH}^H\Big)^{-1}. \end{equation} Here, we emphasize that \eqref{eqn024} holds only for the $1$-bit quantizer. \subsection{Statement of The Research Problem} Section \ref{sec2b} shows already intensive research and appealing contributions on the linear approximation models as well as their relevant LMMSE analaysis. Nevertheless, there is still a need for a more extensive and rigorous study on this issue, which can make the linear approximation research more comprehensive and accurate. Moreover, a more comprehensive study could help to develop novel understanding of the behavior of LMMSE channel equalizer in the context of low-resolution MIMO signal reception. The following sections are therefore motivated. \section{Hermite Polynomial Expansion for Linear Approximation}\label{sec3} This section presents the Hermite polynomial expansion of the low-resolution quantization function as well as key characteristics of the SOHE model. \subsection {Hermite Polynomial Expansion and The SOHE Model} We start from the Laplace's Hermite polynomial expansion (see the definition in \cite[Chapter 22]{Poularikas_1999}) which is employed to represent the quantization function $y=\mathcal{Q}_b(x),~x\in(-\infty, \infty)$. The Hermite transform of $\mathcal{Q}_b(x)$ is given by (see \cite{60086}) \begin{equation}\label{eqn025} \omega_l=\frac{1}{\sqrt{\pi}2^ll!}\int_{-\infty}^{\infty}\mathcal{Q}_b(x)\exp(-x^2)\beta_l(x)\mathrm{d}x, \end{equation} where $\beta_l(x)$ is the Rodrigues' formula specified by \begin{equation}\label{eqn026} \beta_l(x)=(-1)^l\exp(x^2)\Big[\frac{\partial^l}{\partial x^l}\exp(-x^2)\Big]. \end{equation} With this result, the Hermite polynomial expansion of $\mathcal{Q}_b(x)$ is given by \begin{equation}\label{eqn027} \mathcal{Q}_b(x)=\lim_{L\rightarrow\infty}\sum_{l=1}^{L}\omega_l\beta_l(x). \end{equation} The expression of $\omega_l$ can be simplified by plugging \eqref{eqn026} into \eqref{eqn025}, i.e., \begin{equation}\label{eqn028} \omega_l=\frac{(-1)^l}{\sqrt{\pi}2^ll!}\int_{-\infty}^{\infty}\mathcal{Q}_b(x)\Big[\frac{\partial^l}{\partial x^l}\exp(-x^2)\Big]\mathrm{d}x. \end{equation} Applying \eqref{eqn019} into \eqref{eqn028} results in \begin{equation}\label{eqn029} w_l=\frac{(-1)^l}{\sqrt{\pi}2^ll!}\sum_{m=0}^{M-1}x_m\int_{\tau_m}^{\tau_{m+1}} \Big[\frac{\partial^l}{\partial x^l}\exp(-x^2)\Big]\mathrm{d}x. \end{equation} The SOHE model is based on the second-order Hermite expansion as below (i.e., $L=2$ in \eqref{eqn027}) \begin{IEEEeqnarray}{ll}\label{eqn030} \mathcal{Q}_b(x)&=\sum_{l=1}^{2}w_l\beta_l(x)+O(w_3\beta_3(x)),\\ &=\lambda_bx+q_b(x),\label{eqn031} \end{IEEEeqnarray} where $\lambda_b$ is the coefficient corresponding to the first-order Hermite kernel, and $q_b$ is the second-order approximation of the quantization noise. Their mathematical forms are specified by \begin{equation}\label{eqn032} \lambda_b=2\omega_1, \end{equation} \begin{equation}\label{eqn033} q_b(x)=4\omega_2x^2-2\omega_2+O(\omega_3\beta_3(x)). \end{equation} The derivation from \eqref{eqn030} to \eqref{eqn031} is by means of computing \eqref{eqn026} for $l=1,2$. The mathematical work is rather trivial and thus omitted. {\em Remark 1:} The SOHE model in \eqref{eqn031} is certainly not accurate enough to capture the exact characteristics of the low-resolution quantizer. This is also true for all other existing linear approximation models. An accurate Hermite model often requires $L=100$ or more, and this is however too complex for an analytical study. Nevertheless, we will show that the SOHE model can already reflect key characteristics of the low-resolution quantizer. \subsection{The Scalar-SOHE Model and Characteristics}\label{3b} The SOHE model is a linear approximation of the low-resolution quantizer, and thus it is not very different from other existing linear models if solely based on their mathematical forms. On the other hand, the key parameters of SOHE (i.e., $\lambda_b$ and $q_b(x)$) show different characteristics from the others. {\em 1)} Characteristics of the Hermite coefficient $\lambda_b$ can be summarized by the following statement. \begin{thm}\label{thm01} Consider the case of symmetric $b$-bit quantization with the following setup in \eqref{eqn029} \begin{equation}\label{eqn034} x_m=\left\{\begin{array}{ll} \tau_{m+1},&\tau_{m+1}>0\\ \tau_m,&\tau_{m+1}<0 \end{array}\right. \end{equation} The Hermite coefficient $\lambda_b$ has the following properties: \begin{equation}\label{eqn035} \lambda_b\geq 1~\mathrm{and} \lim_{b\rightarrow\infty}\lambda_b=1. \end{equation} \end{thm} \begin{IEEEproof} See Appendix \ref{A}. \end{IEEEproof} With the ideal AGC, we assume that the input and output signals can be optimally scaled to meet the quantization boundaries. {\em Theorem \ref{thm01}} provides two implications: {\em 1)} low-resolution quantizers can introduce a scalar ambiguity $\lambda_b$, which often amplifies the input signal in the digital domain. The principle on how the signal is amplified is analytically explained in Appendix \ref{A}; {\em 2)} In the SOHE model, the scalar ambiguity vanishes with the increase of resolution ($b$ or $M$). This is in line with the phenomenon that can be observed in reality. In other words, the SOHE model as well as the proof in Appendix \ref{A} can well explain the phenomenon of scalar ambiguity occurred in our practice. {\em 2)} Unlike other linear approximation models, the SOHE model does not impose the assumptions A1) and A2) (see Section \ref{sec2b}) onto the quantization noise $q_b$. Instead, $q_b$ is described as a function of the input signal $x$, with their statistical behaviors being analytical studied here. \begin{thm}\label{thm02} Suppose: C1) the input signal $x$ follows $\mathbb{E}(x)=0$. The cross-correlation between $x$ and $q_b$ depends on the third-order central moments of $x$. When the input signal $(x)$ is AWGN, the quantization noise can be considered to be uncorrelated with the input signal. Moreover, for the case of $b\rightarrow\infty$, the following result holds \begin{equation}\label{eqn036} \lim_{b\rightarrow\infty}q_b(x)=0. \end{equation} \end{thm} \begin{IEEEproof} See Appendix \ref{B}. \end{IEEEproof} The implication of {\em Theorem \ref{thm02}} lies in two folds: {\em 1)} the quantization noise cannot be easily assumed to be uncorrelated with the input signal. {\em Theorem \ref{thm02}} provides sufficient conditions for the hypothesis of uncorrelated quantization noise; {\em 2)} due to the use of second-order expansion for quantization function, it is possible that the SOHE-based quantization noise cannot well represent the characteristics of ideal quantization like \eqref{eqn036}. However, {\em Theorem \ref{thm02}} confirms that with the increasing of resolutions, the quantization noise which is a function of the input signal would approximate to zero. {\em Remark 2:} It is worthwhile to note that, for complex-valued signals, the quantization process is applied individually in the real and imaginary domains. Therefore, {\em Theorems \ref{thm01}-\ref{thm02}} apply straightforwardly to the complex-valued input signal. \subsection{The Vector-SOHE Model and Characteristics} The vector representation of the SOHE model has no fundamental difference from the scalar-SOHE model presented in \eqref{eqn031}. It can be obtained by applying \eqref{eqn031} into \eqref{eqn004} \begin{IEEEeqnarray}{ll}\label{eqn037} \mathbf{y}&=\lambda_b\mathbf{r}+\mathbf{q}_b,\\ &=\lambda_b\mathbf{H}\mathbf{s}+\underbrace{\lambda_b\mathbf{v}+\mathbf{q}_b}_{\triangleq\mat{\varepsilon}_b}.\label{eqn038} \end{IEEEeqnarray} The vector form of the quantization noise is specified by \begin{equation}\label{eqn039} \mathbf{q}_b=4\omega_2\Big(\Re(\mathbf{r})^2+j\Im(\mathbf{r})^2\Big)-2\omega_2, \end{equation} where $\Re(\mathbf{r})^2$ or $\Im(\mathbf{r})^2$ denotes the corresponding real-vector with the Hadamard power of $2$. With {\em Theorem \ref{thm02}}, we can reach the following conclusion about the vector-SOHE model. \begin{cor}\label{cor1} Suppose that C2) each element of $\mathbf{H}$ is independently generated; and C3) the number of transmit antennas ($N$) is sufficiently large. The following cross-covariance matrix can be obtained \begin{equation}\label{eqn040} \mathbf{C}_{qv}=\mathbb{E}(\mathbf{q}_b\mathbf{v}^H)=\mathbf{0}. \end{equation} \end{cor} \begin{IEEEproof} The condition C2) ensures that each element of the vector $[\mathbf{Hs}]$ is a sum of $N$ independently generated random variables. With the condition C3), the central limit theorem tells us that each element of $[\mathbf{Hs}]$ is asymptotically AWGN. Since the thermal noise $\mathbf{v}$ is AWGN and independent from $[\mathbf{Hs}]$, the received signal $\mathbf{r}$ is approximately AWGN. In this case, {\em Theorem \ref{thm02}} tells us \begin{equation}\label{eqn041} \mathbf{C}_{qr}=\mathbb{E}(\mathbf{q}_b\mathbf{r}^H)=\mathbf{0}. \end{equation} Plugging \eqref{eqn003} into \eqref{eqn041} results in \begin{IEEEeqnarray}{ll}\label{eqn042} \mathbf{C}_{qr}&=\mathbb{E}(\mathbf{q}_b(\mathbf{Hs}+\mathbf{v})^H),\\ &=\mathbb{E}(\mathbf{q}_b(\mathbf{Hs})^H)+\mathbf{C}_{qv}=\mathbf{0}.\label{eqn043} \end{IEEEeqnarray} Since $\mathbf{v}$ is independent from $[\mathbf{Hs}]$, the only case for \eqref{eqn043} to hold is that both cross-covariance terms are zero. \eqref{eqn040} is therefore proved. \end{IEEEproof} \begin{cor}\label{cor2} Given the conditions C2) and C3), the auto-covariance matrix of the quantization noise ($\mathbf{C}_{qq}$) has the following asymptotical form \begin{equation}\label{eqn044} \mathbf{C}_{qq}=4\omega_2^2\Big(4\sigma_r^4\mathbf{I}+(2\sigma_r^4-\sigma_r^2+1)(\mathbf{1}\otimes\mathbf{1}^T)\Big), \end{equation} where $\sigma_{r}^2$ denotes the variance of $r_k, _{\forall k}$ when $N\rightarrow\infty$. \end{cor} \begin{IEEEproof} See Appendix \ref{C}. \end{IEEEproof} \begin{thm}\label{thm03} Suppose that C4) the information-bearing symbols $s_n, _{\forall n},$ have their third-order central moments fulfilling the condition: $\mathbb{E}(\Re(s_n)^3)=0$; $\mathbb{E}(\Im(s_n)^3)=0$. Then, the following cross-covariance holds \end{thm} \begin{equation}\label{eqn045} \mathbf{C}_{\varepsilon s}=\mathbb{E}(\mat{\varepsilon}_b\mathbf{s}^H)=\mathbf{0}. \end{equation} \begin{IEEEproof} The cross-covariance in \eqref{eqn045} can be computed as follows \begin{IEEEeqnarray}{ll} \mathbf{C}_{\varepsilon s}&=\mathbb{E}((\lambda_b\mathbf{v}+\mathbf{q}_b)\mathbf{s}^H),\label{eqn046}\\ &=\lambda_b\mathbf{C}_{vs}+\mathbb{E}(\mathbf{q}_b\mathbf{s}^H),\label{eqn047}\\ &=\mathbf{C}_{qs}\label{eqn048}. \end{IEEEeqnarray} The derivation from \eqref{eqn047} to \eqref{eqn048} is due to the mutual independence between $\mathbf{s}$ and $\mathbf{v}$. Appendix \ref{D} shows \begin{equation}\label{eqn049} \mathbf{C}_{qs}=\mathbf{0}. \end{equation} The result \eqref{eqn045} is therefore proved. It is perhaps worthwhile to note that in wireless communications, $s_n$ is normally centrosymmetric (such as M-PSK and M-QAM) and equally probable. In this case, it is not hard to find that the condition C4) does hold in reality. \end{IEEEproof} In summary, {\em Corollary \ref{cor1}} exhibits the conditions for the quantization noise to be uncorrelated with the thermal noise as well as the noiseless part of the received signal. The condition C3) indicates the need for a sufficiently large number of transmit-antennas ($N$). However, this does not mean to require a very large $N$ in practice. Let us take an example of $N=8$. Each element of $\mathbf{r}$ is a superposition of $(2N)=16$ independently generated real random-variables, and this can already lead to a reasonable asymptotical result. {\em Corollary \ref{cor2}} exhibits the auto-covariance matrix of $\mathbf{q}_b$, which is an asymptotical result for $N\rightarrow\infty$. The exact form of $\mathbf{C}_{qq}$ is very tedious and we do not have the closed-form. Nevertheless, \eqref{eqn045} already provides sufficient physical essence for us to conduct the LMMSE analysis. Finally, {\em Theorem \ref{thm03}} shows that the quantization noise is uncorrelated with the information-bearing symbols. All of these results are useful tools to our LMMSE analysis in Section \ref{sec4}. \section{LMMSE Analysis with The Vector-SOHE Model}\label{sec4} The primary aim of this section is to employ the vector-SOHE model \eqref{eqn037}-\eqref{eqn038} to conduct the LMMSE analysis, with which those interesting phenomena observed in the current LMMSE algorithm can be well explained. In addition, a better understanding of the behavior of the current LMMSE algorithm helps to find us an enhanced version particularly for signals with non-constant modulus modulations. \subsection{The SOHE-Based LMMSE Analysis}\label{sec4a} Vector-SOHE is still a linear model. It does not change the classical form of the LMMSE, i.e., $\mathbf{G}^\star=\mathbf{C}_{sy}\mathbf{C}_{yy}^{-1}$ still holds. Despite, the cross-covariance matrix $\mathbf{C}_{sy}$ can now be computed by \begin{IEEEeqnarray}{ll} \mathbf{C}_{sy}&=\mathbb{E}\Big(\mathbf{s}(\lambda_b\mathbf{H}\mathbf{s}+\mat{\varepsilon}_b)^H\Big),\label{eqn050}\\ &=\lambda_b\mathbf{C}_{ss}\mathbf{H}^H+\mathbf{C}_{s\varepsilon},\label{eqn051}\\ &=\lambda_b\mathbf{H}^H.\label{eqn052} \end{IEEEeqnarray} The derivation from \eqref{eqn051} to \eqref{eqn052} is due to the fact $\mathbf{C}_{s\varepsilon}=\mathbf{0}$ (see {\em Theorem \ref{thm03}}) as well as the assumption that $x_n, \forall n,$ are uncorrelated with respect to $n$ (see the assumption above \eqref{eqn002}). The auto-covariance matrix $\mathbf{C}_{yy}$ can be represented by \begin{equation} \mathbf{C}_{yy}=\lambda_b^2\mathbf{HH}^H+\mathbf{C}_{\varepsilon\varepsilon},\label{eqn053} \end{equation} where \begin{IEEEeqnarray}{ll}\label{eqn054} \mathbf{C}_{\varepsilon\varepsilon}&=\lambda_b^2N_0\mathbf{I}+\mathbf{C}_{qq}+\lambda_b(\mathbf{C}_{qv}+\mathbf{C}_{vq}),\\ &=\lambda_b^2N_0\mathbf{I}+\mathbf{C}_{qq}+2\lambda_b\Re(\mathbf{C}_{qv}).\label{eqn055} \end{IEEEeqnarray} Then, the LMMSE formula can be represented by \begin{equation}\label{eqn056} \mathbf{G}^\star=\lambda_b^{-1}\mathbf{H}^H(\mathbf{HH}^H+\lambda_b^{-2}\mathbf{C}_{\varepsilon\varepsilon})^{-1}. \end{equation} Provided the conditions C2) and C3), \eqref{eqn056} turns into (see {\em Corollary \ref{cor1}}) \begin{equation}\label{eqn057} \mathbf{G}^\star=\lambda_b^{-1}\mathbf{H}^H(\mathbf{HH}^H+N_0\mathbf{I}+\lambda_b^{-2}\mathbf{C}_{qq})^{-1}, \end{equation} where $\mathbf{C}_{qq}$ can be substituted by \eqref{eqn044} in {\em Corollary \ref{cor2}}. \subsection{Comparison between Various LMMSE Formulas}\label{sec4b} Given that the generalized-AQNM model (see Section \ref{sec2b3}) was only studied for the $1$-bit quantizer, we mainly conduct the LMMSE comparison between the SOHE model and the (modified) AQNM model. As shown in Section \ref{sec2b2}, the modified-AQNM model does not give a different LMMSE formula from the AQNM model when the Gaussian quantization noise is assumed. Therefore, our study is quickly focused on the comparison with the AQNM model. Basically, there are two major differences in their LMMSE forms: {\em 1)} The SOHE-LMMSE formula has a scaling factor $\lambda_b^{-1}$, which plays the role of equalizing the scalar ambiguity inherent in the SOHE model (see \eqref{eqn037}-\eqref{eqn038}). As shown in {\em Theorem \ref{thm01}}, this scalar ambiguity is introduced in the low-resolution quantization procedure. It amplifies the signal energy in the digital domain and vanishes with the increase of resolutions. This theoretical conclusion coincides well with the phenomenon observed in the literature (e.g. \cite{nguyen2019linear,9144509}). {\em 2)} In the AQNM-LMMSE formula \eqref{eqn009}, the impact of the quantization noise is described by the term $\mathrm{nondiag}(\rho\mathbf{HH}^H)$. This implies that the quantization noise is modeled as a linear distortion. However, such is not the case for the SOHE-LMMSE formula. As shown in \eqref{eqn045} and \eqref{eqn057}, the auto-covariance matrix $\mathbf{C}_{qq}$ involves the terms $\sigma_r^2$ and $\sigma_r^4$; and higher-order components are approximated in the SOHE model. Although \eqref{eqn045} is only an asymptotical and approximate result, it carries a good implication in the sense that the quantization noise would introduce non-linear effects to the LMMSE. Due to the modeling mismatch, the AQNM-LMMSE algorithm can suffer additional performance degradation. Denote $\mathbf{G}^\star_{\eqref{eqn009}}$ and $\mathbf{G}^\star_{\eqref{eqn057}}$ to be the corresponding LMMSE formulas with respect to the AQNM and SOHE models. Section \ref{sec2a} indicates that they share the same size, i.e., $(N)\times(K)$. Assuming that $\mathbf{G}^\star_{\eqref{eqn009}}$ has the full row rank, we are able to find a $(N)\times(N)$ matrix $\mathbf{\Theta}$ fulfilling \begin{equation}\label{eqn058} \mathbf{\Theta}\mathbf{G}^\star_{\eqref{eqn009}}=\mathbf{G}^\star_{\eqref{eqn057}}. \end{equation} Denote $(\mathbf{G}^\star_{\eqref{eqn009}})^\dagger$ to be the pseudo inverse of $\mathbf{G}^\star_{\eqref{eqn009}}$. The matrix $\mathbf{\Theta}$ can be obtained through \begin{equation}\label{eqn059} \mathbf{\Theta}=\mathbf{G}^\star_{\eqref{eqn057}}\Big(\mathbf{G}^\star_{\eqref{eqn009}}\Big)^\dagger. \end{equation} Therefore, the impact of the modeling mismatch inherent in the AQNM-LMMSE can be mitigated through a linear transform. Suppose that the matrix $\mathbf{G}^\star_{\eqref{eqn009}}$ has the full row rank. The modeling-mismatch induced performance degradation inherent in the AQNM-LMMSE algorithm can be mitigated through the linear transform specified in \eqref{eqn058}, where the scaling factor $\lambda_b$ is incorporated in the matrix $\mathbf{\Theta}$. \subsection{Enhancement of The AQNM-LMMSE Algorithm} The SOHE-LMMSE formula describes more explicitly the impact of non-linear distortion in the channel equalization. However, the SOHE-LMMSE formula cannot be directly employed for the channel equalization mainly due to two reasons: {\em 1)} the auto-covariance matrix $\mathbf{C}_{qq}$ does not have a closed-form in general; and {\em 2)} the scalar $\lambda_b$ defined in \eqref{eqn032} comes only from the first-order Hermite kernel. However, other odd-order Hermite kernels also contribute to $\lambda_b$. The omission of the third- and higher-order Hermite kernels can make the computation of $\lambda_b$ inaccurate. Fortunately, the analysis in \eqref{eqn058} and\eqref{eqn059} show that the SOHE-LMMSE formula can be translated into the AQNM-LMMSE formula through a linear transform. In other words, there is a potential to enhance the AQNM-LMMSE algorithm by identifying the linear transform $\mathbf{\Theta}$. Denote $\hat{\mathbf{s}}_{\eqref{eqn057}}\triangleq\mathbf{G}^\star_{\eqref{eqn057}}\mathbf{y}$ and $\hat{\mathbf{s}}_{\eqref{eqn009}}\triangleq\mathbf{G}^\star_{\eqref{eqn009}}\mathbf{y}$ to be the outputs of the SOHE-LMMSE channel equalizer and the AQNM-LMMSE channel equalizer, respectively. Applying the result \eqref{eqn058}-\eqref{eqn059} yields \begin{equation}\label{eqn060} \hat{\mathbf{s}}_{\eqref{eqn009}}=\mathbf{\Theta}^{-1}\hat{\mathbf{s}}_{\eqref{eqn057}}. \end{equation} Generally, it is not easy to identify $\mathbf{\Theta}$ and remove it from $\hat{\mathbf{s}}_{\eqref{eqn009}}$. On the other hand, if $\mathbf{G}^\star_{\eqref{eqn057}}$ and $\mathbf{G}^\star_{\eqref{eqn009}}$ are not too different, \eqref{eqn059} implies that $\mathbf{\Theta}$ can be considered to be approximately diagonal. In this case, the linear transform reduces to symbol-level scalar ambiguities. Assume that the channel-equalized result $\hat{\mathbf{s}}_{\eqref{eqn057}}$ does not have such scalar ambiguities. It is easy to understand the scalar ambiguities of $\hat{\mathbf{s}}_{\eqref{eqn009}}$ come from $\lambda_b\mathbf{G}^\star_{\eqref{eqn009}}\mathbf{H}$. In other words, we can have the following approximation \begin{equation}\label{eqn061} \mathbf{\Theta}^{-1}\approx\lambda_b\mathbb{D}\Big(\mathbf{G}^\star_{\eqref{eqn009}}\mathbf{H}\Big). \end{equation} In \eqref{eqn061}, $\lambda_b$ is the only unknown notation which must be determined. {\em Theorem \ref{thm01}} shows that the effect of $\lambda_b$ is the block-level energy amplification, of which the value can be computed using \eqref{appa6}. Finally, we conclude the following form of enhanced LMMSE channel equalizer (eLMMSE) \begin{equation}\label{eqn063} \mathbf{G}_e=\frac{1}{\lambda_b}\mathbb{D}\Big(\mathbf{G}^\star_{\eqref{eqn009}}\mathbf{H}\Big)^{-1}\mathbf{G}^\star_{\eqref{eqn009}}. \end{equation} \section{Simulation Results and Discussion}\label{sec5} Computer simulations were carried out to elaborate our theoretical work in Section \ref{sec3} and Section \ref{sec4}. Similar to the AQNM models, the SOHE model cannot be directly evaluated through computer simulations. Nevertheless, their features can be indirectly demonstrated through the evaluation of their corresponding LMMSE channel equalizers. Given various LMMSE channel equalizers discussed in Section \ref{sec2} and Section \ref{sec4}, it is perhaps useful to provide a brief summary here for the sake of clarification: \begin{itemize} \item AQNM-LMMSE: this is the LMMSE channel equalizer shown in \eqref{eqn009}. As shown in Section \ref{sec2b2}, the LMMSE channel equalizer \eqref{eqn017} is equivalent to \eqref{eqn009}; and thus it is not demonstrated in our simulation results. \item B-LMMSE: this is the LMMSE channel equalizer shown in \eqref{eqn024}. This channel equalizer is specially designed and optimized for the $1$-bit quantizer. Therefore, it will only be demonstrated in our simulation results for the $1$-bit quantizer. \item N-LMMSE: this is the AQNM-LMMSE channel equalizer normalized by the term $\|\mathbf{G}^\star_{\eqref{eqn009}}\mathbf{y}\|$. \item NB-LMMSE: this is the B-LMMSE channel equalizer normalized by the term $\|\mathbf{G}^\star_{\eqref{eqn024}}\mathbf{y}\|$. Both the N-LMMSE and NB-LMMSE channel equalizers have been studied in \cite{7439790,nguyen2019linear,tsefunda}. \item e-LMMSE: this is the e-LMMSE channel equalizer proposed in \eqref{eqn063}. As shown in Section \ref{sec4}, this e-LMMSE channel equalizer is driven by the SOHE model. \end{itemize} \begin{figure}[tb] \centering \includegraphics[scale=0.25]{1bit_MSE_comparisons_dB.eps} \caption{ The MSE performance as a function of Eb/N0 for the $N$-by-$K$ multiuser-MIMO systems with $1$-bit quantizers, \protect\tikz[baseline]{\protect\draw[line width=0.2mm, dashed] (0,.5ex)--++(0.6,0) ;}~$(N/K)=(2/32)$, \protect\tikz[baseline]{\protect\draw[line width=0.2mm] (0,.5ex)--++(0.6,0) ;}~$(N/K)=(4/64)$, \protect\tikz[baseline]{\protect\draw[line width=0.2mm, dash dot] (0,.5ex)--++(0.6,0) ;}~$(N/K)=(8/128)$.}\label{fig01} \end{figure} In our computer simulations, the e-LMMSE channel equalizer is compared to the SOTA (i.e., AQNM-LMMSE, B-LMMSE, N-LMMSE and NB-LMMSE) in terms of their MSE as well as bit-error-rate (BER) performances. The MSE is defined by \begin{equation}\label{eqn064} \mathrm{MSE}\triangleq\frac{1}{(N)(I)}\sum_{i=0}^{I-1}\|\mathbf{G}_i^\star\mathbf{y}_i-\mathbf{s}_i\|^2, \end{equation} where $I$ denotes the number of Monte Carlo trials. All the simulation results were obtained by taking average of sufficient number of Monte Carlo trials. For each trial, the wireless MIMO narrowband channel was generated according to independent complex Gaussian distribution (Rayleigh in amplitude), and this is the commonly used simulation setup in the literature \cite{7458830, 6987288}. In addition, the signal-to-noise ratio (SNR) is defined by the average received bit-energy per receive antenna to the noise ratio (Eb/N0), and the transmit power for every transmit antenna is set to be identical. The low-resolution quantization process follows the design in \cite{7037311}, which for 1-bit quantizer, binary quantization is taken; for quantizer other than 1-bit (i.e., 2, 3-bit), the ideal AGC is assumed and the quantization is determined by quantization steps \cite{1057548}. \begin{figure*}[t] \centering \includegraphics[scale=0.35]{MSE_23bit_comparisons_dB.eps} \caption{The MSE performance as a function of Eb/N0 for the $N$-by-$K$ multiuser-MIMO systems with $1$-bit quantizers, \protect\tikz[baseline]{\protect\draw[line width=0.2mm, dashed] (0,.5ex)--++(0.6,0) ;}~$(N/K)=(2/32)$, \protect\tikz[baseline]{\protect\draw[line width=0.2mm] (0,.5ex)--++(0.6,0) ;}~$(N/K)=(4/64)$, \protect\tikz[baseline]{\protect\draw[line width=0.2mm, dash dot] (0,.5ex)--++(0.6,0) ;}~$(N/K)=(8/128)$.}\label{fig02} \end{figure*} According to the measures used in computer simulations, we divide the simulation work into two experiments. One is designed to examine the MSE performance, and the other is for the BER performance. In our simulation results, we demonstrate the performances mainly for $16$-QAM. This is due to two reasons: {\em 1)} all types of LMMSE channel equalizers offer the same performances for M-PSK modulations. This phenomenon has already been reported in the literature and also discussed in Section \ref{sec1}; and {\em 2)} higher-order QAM modulations exhibit almost the same basic features as those of $16$-QAM. On the other hand, they perform worse than $16$-QAM due to their increased demand for the resolution of quantizers. Those observations are not really novel and thus abbreviated. \subsubsection*{Experiment 1}\label{exp1} The objective of this experiment is to examine the MSE performance of various LMMSE channel equalizers. For all simulations, we keep the transmit antenna to receive antenna ratio to be a constant (e.g. $N/K=1/16$). \figref{fig01} depicts the MSE performances of various LMMSE channel equalizers as far as the $1$-bit quantizer is concerned. Generally, it can be observed that all the MSE performances get improved by increasing the size of MIMO. This phenomenon is fully in line with the principle of mMIMO. It can also be observed that both the AQNM-LMMSE and the B-LMMSE channel equalizers perform poorly throughout the whole SNR range. This is because the AQNM models do not capture the scaling ambiguity as described in the SOHE model. When the normalization operation is applied, the AQNM-LMMSE and the B-LMMSE channel equalizers turn into their corresponding N-LMMSE and NB-LMMSE equalizers, respectively. Interestingly, their performances get significantly improved, and thereby outperforming the e-LMMSE channel equalizer for most of cases. On one hand, this is the additional evidence showing the missing of scaling ambiguity in the AQNM models; and on the other hand, it is shown that the NB-LMMSE is indeed the optimized LMMSE channel equalizer for the $1$-bit quantizer. Nevertheless, we can see that the e-LMMSE approach still offers very comparable MSE performances with the N-LMMSE and NB-LMMSE approaches. This provides the indirect evidence showing that the SOHE model offers a good approximation for the $1$-bit quantizer. Then, we carry on our simulations for $2$- and $3$-bit low-resolution quantizers, respectively, and illustrate their MSE performances in \figref{fig02}. It is perhaps worth emphasizing that the B-LMMSE and NB-LMMSE channel equalizers are not examined here since they are devised only for the $1$-bit quantizer. The first thing coming into our sight is that the e-LMMSE shows the best MSE performance for almost all the demonstrated cases. This is a very good evidence to support our theoretical work about the SOHE model as well as the SOHE-based LMMSE analysis. \begin{figure*}[t] \centering \includegraphics[scale=0.27]{two_123bit_enhanced_comparison.eps} \caption{The BER performance as a function of Eb/N0 for $N= 2$ transmitters, $16$-QAM systems with different resolutions of quantizers, \protect\tikz[baseline]{\protect\draw[line width=0.2mm] (0,.5ex)--++(0.6,0) ;}~$K=32$ receive antennas, \protect\tikz[baseline]{\protect\draw[line width=0.2mm, dash dot] (0,.5ex)--++(0.6,0) ;}~$K=16$ receive antennas.}\label{fig03} \end{figure*} \begin{figure*}[t] \centering \includegraphics[scale=0.27]{four_123bit_enhanced_comparison.eps} \caption{The BER performance as a function of Eb/N0 for $N= 4$ transmitters, $16$-QAM systems with different resolutions of quantizers, \protect\tikz[baseline]{\protect\draw[line width=0.2mm] (0,.5ex)--++(0.6,0) ;}~$K=64$ receive antennas, \protect\tikz[baseline]{\protect\draw[line width=0.2mm, dash dot] (0,.5ex)--++(0.6,0) ;}~$K=32$ receive antennas.}\label{fig04} \end{figure*} When going down to the detail, specifically for the $2$-bit quantizer, the N-LMMSE approach demonstrates very comparable performance with the e-LMMSE approach in the case of larger MIMO (i.e. $(N/K)=(8/128)$). However, its performance gets quickly degraded with the decrease of the MIMO size. Take the example of Eb/N0$=5$ dB. For the case of $(N/K)=(8/128)$, both the e-LMMSE and the N-LMMSE approaches have their MSEs at around $-22.6$ dB, while the AQNM-LMMSE has its MSE at around $-16.8$ dB. Both the e-LMMSE and the N-LMMSE outperform the AQNM-LMMSE by around $6$ dB. When the size of MIMO reduces to $(N/K)=(4/64)$, the e-LMMSE shows the best MSE (around $-21.2$ dB). The MSE for N-LMMSE and AQNM-LMMSE becomes $-18.9$ dB and $-17.7$ dB, respectively. The N-LMMSE underperforms the e-LMMSE by around $2.3$ dB, although it still outperforms the AQNM-LMMSE by around $1.2$ dB. By further reducing the size of MIMO to $(N/K)=(2/32)$, the e-LMMSE has its MSE performance degraded to $-19.6$ dB. The MSE for N-LMMSE and AQNM-LMMSE now becomes $-14.9$ dB and $-17.4$ dB, respectively. The e-LMMSE outperforms the AQNM-LMMSE by around $2.2$ dB and the N-LMMSE by around $4.7$ dB. The major reason for this phenomenon to occur is that the AQNM model assumes the quantization distortion and the input signal to be Gaussian. This assumption becomes less accurate with the use of less transmit antennas. Moreover, the use of less receive antennas has the spatial de-noising ability reduced. The term used for normalization gets more negatively influenced by the noise as well as the quantization distortion. The SOHE model does not assume the input signal and the quantization distortion to be Gaussian, and thus it gets the least negative impact. \begin{figure*}[t] \centering \includegraphics[scale=0.27]{eight_123bit_enhanced_comparison.eps} \caption{The BER performance as a function of Eb/N0 for $N= 8$ transmitters, $16$-QAM systems with different resolutions of quantizers, \protect\tikz[baseline]{\protect\draw[line width=0.2mm] (0,.5ex)--++(0.6,0) ;}~$K=128$ receive antennas, \protect\tikz[baseline]{\protect\draw[line width=0.2mm, dash dot] (0,.5ex)--++(0.6,0) ;}~$K=64$ receive antennas.}\label{fig05} \end{figure*} Due to the same rationale, the similar phenomenon can also be observed for the $3$-bit quantizer. Again, the e-LMMSE approach shows the best performance for almost all the cases. Apart from that, there are two notable differences that worth a mention: {\em 1)} the performance of AQNM-LMMSE is quite close to that of e-LMMSE for all sizes of MIMO. This is because the $3$-bit quantizer is of reasonably good resolution for $16$-QAM modulations, and this largely mitigates the discrimination between the AQNM model and the SOHE model; and 2) the N-LMMSE performs really poorly when compared with the others. This implies the inaccuracy of using the term $\|\mathbf{G}^\star_{\eqref{eqn009}}\mathbf{y}\|$ for the normalization. After all, the experiment about the MSE evaluation confirms our theoretical work in Sections \ref{sec2}-\ref{sec4} and demonstrates the major advantages of the SOHE model as well as the e-LMMSE channel equalizer from the MSE perspective. \subsubsection*{Experiment 2}\label{exp2} It is common knowledge that an MMSE-optimized approach is not necessarily optimized for the detection performance. This motivates us to examine the average-BER performance for various LMMSE channel equalizers in this experiment. Basically, this experiment is divided into three sub-tasks, with each having a fixed number of transmit antennas. \figref{fig03} depicts the case of $N=2$ transmit antennas. Generally, the use of more receive antennas can largely improve the BER performance. This conclusion is true for all types of examined low-resolution quantizers. In other words, all LMMSE channel equalizers can enjoy the receiver-side spatial diversity. Specifically for the $1$-bit quantizer, the AQNM-based LMMSE approaches (i.e., AQNM-LMMSE and B-LMMSE) generally underperform their corresponding normalized version (i.e., N-LMMSE and NB-LMMSE). This phenomenon fully coincides with their MSE behaviors shown in {\em Experiment 1}- \figref{fig01}. The e-LMMSE approach does not demonstrate remarkable advantages in this special case. It offers the best BER at the SNR range around Eb/N0 $=2$ dB, and then the BER grows with the increase of SNR. Such phenomenon is not weird, and this occurs quite often in systems with low-resolution quantizers and other non-linear systems due to the physical phenomenon called stochastic resonance \cite{RevModPhys.70.223}. Similar phenomenon also occurs in the AQNM-LMMSE approach. It means that, for low-resolution quantized systems, additive noise could be constructive to the signal detection at certain SNRs, especially for the QAM constellations (e.g. \cite{7247358, 7894211, 9145094, jacobsson2019massive, She2016The}). The theoretical analysis of constructive noise in the signal detection can be found in Kay's work \cite{809511} ( interested readers please see Appendix \ref{E} for the elaboration of the phenomenon of constructive noise.) Interestingly, the normalized approaches do not show considerable stochastic resonance phenomenon within the observed SNR range. \begin{figure*}[t] \centering \includegraphics[scale=0.27]{four_123bit_SE_comparison.eps} \caption{The sum SE as a function of Eb/N0 for $N= 4$ transmitters for systems with different resolutions of quantizers, different LMMSE based channel estimators and ZF channel equalizer. \protect\tikz[baseline]{\protect\draw[line width=0.2mm] (0,.5ex)--++(0.6,0) ;}~$K=64$ receive antennas, \protect\tikz[baseline]{\protect\draw[line width=0.2mm, dash dot] (0,.5ex)--++(0.6,0) ;}~$K=32$ receive antennas.}\label{fig06} \end{figure*} When the resolution of quantizer increases to $b=2$ bit, the e-LMMSE approach demonstrates the significant performance gain for most of cases. For instance, the e-LMMSE significantly outperforms the AQNM-LMMSE for the higher SNR range (i.e., Eb/N0 $>0$ dB). The N-LMMSE approach performs the worst in all the cases. This observation is well in line with our observation in the MSE performance (see \figref{fig02}), and they share the same rationale. When the resolution of quantizer increases to $b=3$ bit, both the e-LMMSE and the AQNM-LMMSE approaches offer excellent BER performances. Their performances are very close to each other, and the e-LMMSE only slightly outperforms the AQNM-LMMSE for the case of $K=16$. This reason for this phenomenon is the same as that for the MSE performance, which has also been explained in {\em Experiment 1}. In a short summary, the e-LMMSE approach shows significant advantages for $2$-bit quantizers. This is the case where the SOHE model offers a better mathematical description than the AQNM models, and at the same time the resolution is not high enough to support higher-order modulations. This is particularly true for the case of $N=2$ transmit antennas, where the input signal and quantization distortion can be assumed to be white Gaussian. Now, we increase the number of transmit antennas $(N)$ to investigate how the BER performance will be influenced. Accordingly, the number of receive antennas $(K)$ is also increased. The BER results for the case of $N=4$ are plotted in \figref{fig04}. Let us begin with the $3$-bit quantizer. We have almost the same observation as for the case of $N=2$ transmit antennas. The e-LMMSE approach performs slightly better than the AQNM-LMMSE approach. The performance difference is not really considerable. When it comes to the case of $2$-bit quantizer, their difference in BER gets largely increased, and the e-LMMSE approach demonstrates significant advantages. It is worth noting that the N-LMMSE approach offers comparable performances with the AQNM-LMMSE approach. This is because the increase of transmit antennas brings the input signal and quantization distortion closer to the white Gaussian. This rationale is also explained in the MSE analysis. For the case of $1$-bit quantizer, there is no much new phenomenon observed in comparison with the case of $N=2$ transmit antennas; apart from that the stochastic resonance phenomenon becomes less significant. When the number of transmit antennas increases to $N=8$, the BER results are plotted in \figref{fig05}. For the case of $3$-bit quantizer, the e-LMMSE approach demonstrates slightly more considerable gain, and the N-LMMSE approach gets its performance even closer to the others. Similar phenomenon can be observed for the case of $2$-bit quantizer, where the N-LMMSE offers considerably close performance to the e-LMMSE approach. The AQNM-LMMSE approach performs the worst. This phenomenon is also observed in the MSE analysis. Again, for the $1$-bit quantizer, the NB-LMMSE approach offers the best BER performance, as it is devised and optimized for this special case. Similar to the phenomenon observed in {\em Experiment 1}, the performance of e-LMMSE is not the best for the $1$-bit quantized system. This is because, for the $1$-bit quantized system, there exists an optimum LMMSE channel equalizer using the arcsine law \cite{Mezghani2012,Papoulis_2002}. Despite, the proposed e-LMMSE approach can still provide comparable performance over the closed-form approach. When it comes to the $3$-bit quantizer, it can be found that e-LMMSE has only a slight BER gain over the AQNM-LMMSE. It is known that one of the characteristics of SOHE model is that it is not based on the Gaussian quantization noise assumption. However, when the resolution of quantizer rises to $3$-bit, the distribution of quantization noise very approximates to the Gaussian distribution and such results in similar performances between e-LMMSE and AQNM-LMMSE. \subsubsection*{Experiment 3}\label{exp3} As response to the reviewers' comments, we add this experiment to examine the SOHE-based channel estimation and its corresponding channel equalization. For this experiment, SOTA approaches can include those results reported in \cite{7931630, 7894211,rao2021massive}. It is perhaps worth noting that the literature \cite{rao2021massive} considers the use of sigma-delta quantizer, which takes advantage of oversampling to achieve an enhanced performance. This is however not the case for our work as well as those in \cite{7931630, 7894211}. For the sake of fair comparison, we only conduct the performance comparison between our work and the result in \cite{7931630, 7894211}. In this experiment, the performance is evaluated through the sum SE defined by \cite{rao2021massive} \begin{equation}\label{eqn067} \mathrm{SE} =\frac{T-P}{T}\sum_n^NR_n, \end{equation} where $T$ is the length of the coherence interval, and $R_n$ the achievable rate for each transmitter-to-receiver link defined in \cite{7931630, 7894211}. This is because the sum SE is the widely considered metric in the SOTA \cite{7931630, 7894211,rao2021massive}, where $T$ is commonly set to $200$. Similar to \eqref{eqn003}, the mathematical model for low-resolution quantized mMIMO channel estimation is given in the vectorized form \begin{equation}\label{eqn065} \mathbf{r}_p = \bar{\mathbf{\Phi}}\bar{\mathbf{h}}+\bar{\mathbf{v}}_p, \end{equation} where $\bar{\mathbf{h}}=\mathrm{vec}(\mathbf{H})$, $\bar{\mathbf{\Phi}}=(\mathbf{\Phi} \otimes \mathbf{I}_K)$ and $\mathbf{\Phi}\in \mathbb{C}^{N\times P}$ is the pairwise orthogonal pilot matrix, which is composed of submatrices of the discrete Fourier transform (DFT) operator \cite{Biguesh_1bit}. During training, all $N$ users simultaneously transmit their pilot sequences of $P$ symbols to the BS. Feeding \eqref{eqn065} to the low-resolution quantizer, we should have the output $\mathbf{y}_p \in \mathbb{C}^{KP\times 1}$, which is similar to \eqref{eqn004}. Regarding the LMMSE channel estimation algorithms, we should have the closed-form B-LMMSE estimator for 1-bit quantized model in \cite{7931630} and AQNM-LMMSE and N-LMMSE estimators for other resolutions. Those channel estimators are compared with the SOHE-LMMSE channel estimator in \eqref{eqn063}. Given the LMMSE estimator $\mathbf{W}^*$, the channel estimate can be expressed as $\hat{\mathbf{H}}=\mathrm{unvec}(\mathbf{W}^*\mathbf{y}_b)$. For the sake of fairness, we employ the zero-forcing (ZF) algorithm for the channel equalization as it has been used by the SOTA, i.e., $\mathbf{G}_{\text{ZF}} = \mathbf{\hat{\mathbf{H}}}^H(\hat{\mathbf{H}}\hat{\mathbf{H}}^H)^{-1}$. \figref{fig06} depicts the sum SE performance of various LMMSE channel estimators while $N=4$ transmitters and $K= 32, 64$ receive antennas are considered. The length of the pilot is considered as $P=N$. Similar to the phenomenon observed in above experiments, the rising up of the number of receive antennas and resolution of quantizers can offer significant SE gain. When the resolution of quantizer is $b=1$ bit, the B-LMMSE algorithm has the best sum SE over other LMMSE channel estimators, and the gap can be approximately 4 bit/s/Hz. This phenomenon is not wired as the B-LMMSE is the closed-form algorithm for 1-bit quantized model \cite{7931630}. SOHE-LMMSE and AQNM-LMMSE channel estimators do not demonstrate advantages in this special scenario, but it can be found that SOHE-LMMSE can achieve almost the same sum SE as the N-LMMSE channel estimator, while AQNM-LMMSE approach performs the worst in such model. When the resolution of quantizer increases to $b=2$ bit, all three types (i.e., SOHE-LMMSE, AQNM-LMMSE and N-LMMSE) of channel estimators share the similar sum SE. For instance, they can have their sum SE reaching at 16 bit/s/Hz for $K=32$ and 20 bit/s/Hz for $K=64$ for the four-user system. When it comes to the case of 3-bit quantizer, we have almost the same observation as for the case of $b=2$ bit quantizer. The performance difference between all three types of channel estimators is not really considerable for high Eb/N0. When the Eb/N0 $>$ 0dB, for $K=64$, the AQNM-LMMSE channel estimator can slightly outperform the N-LMMSE and SOHE-LMMSE channel estimators. As it is discussed in Section \ref{sec4}-\ref{sec5}, the scalar ambiguity will be detrimental for QAM modulations. However, the setup of each element of the pilot matrix $\mathbf{\Phi}$ follows unit power and all pilot sequences are pairwise orthogonal; similar to the analysis for LMMSE channel equalization for PSK constellations, the scalar ambiguity does not show any side effect on such case. This explains the reason why the SOHE-LMMSE channel estimator has the same sum SE compared with current version LMMSE algorithms. \section{Conclusion} In this paper, a novel linear approximation method, namely SOHE, has been proposed to model the low-resolution quantizers. The SOHE model was then extended from the real-scalar form to the complex-vector form, and the latter was applied and extensively studied in the low-resolution quantized multiuser-MIMO uplink signal reception. It has been shown that the SOHE model does not require those assumptions employed in the AQNM model as well as its variations. Instead, it uses the first-order Hermite kernel to model the signal part and the second-order Hermite kernel to model the quantization distortion. Such equipped us with sufficient flexibility and capacity to develop deeper and novel understanding of the stochastic behavior and correlation characteristics of the quantized signal as well as the non-linear distortion. Through our intensive analytical work, it has been unveiled that the low-resolution quantization could result in a scalar ambiguity. In the SOHE model, this scalar ambiguity is characterized by the coefficient of the first-order Hermite kernel. However, it is not accurately characterized in other linear approximation models due to the white-Gaussian assumption. When applying the SOHE model for the LMMSE analysis, it has been found that the SOHE-LMMSE formula carries the Hermite coefficient, which equips the SOHE-LMMSE channel equalizer with the distinct ability to remove the scalar ambiguity in the channel equalization. It has been shown that the SOHE-LMMSE formula involves higher-order correlations, and this prevents the implementation of the SOHE-LMMSE channel equalizer. Nevertheless, it was also found that the SOHE-LMMSE formula could be related to the AQNM-LMMSE formula through a certain linear transform. This finding motivated the development of the e-LMMSE channel equalizer, which demonstrated significant advantages in the MSE and BER performance evaluation. All of the above conclusions have been elaborated through extensive computer simulations in the independent Rayleigh-fading channels. \appendices \section{Proof of Theorem \ref{thm01}}\label{A} With the equations \eqref{eqn028} and \eqref{eqn032}, the coefficient $\lambda_b$ can be computed as follows \begin{IEEEeqnarray}{ll}\label{appa1} \lambda_b&=\frac{-1}{\sqrt{\pi}}\sum_{m=0}^{M-1}x_m\int_{\tau_m}^{\tau_{m+1}} \Big[\frac{\partial}{\partial x}\exp(-x^2)\Big]\mathrm{d}x,\\ &=\frac{-1}{\sqrt{\pi}}\sum_{m=0}^{M-1}x_m\int_{\tau_m}^{\tau_{m+1}}(-2x)\exp(-x^2)\mathrm{d}x,\label{appa2}\\ &=\frac{1}{\sqrt{\pi}}\sum_{m=0}^{M-1}x_m\Big( \exp(-\tau_m^2)-\exp(-\tau_{m+1}^2) \Big).\label{appa3} \end{IEEEeqnarray} We first examine the limit of $\lambda_b$ when $b\rightarrow\infty$. It is equivalent to the following case \begin{IEEEeqnarray}{ll} \lim_{b\rightarrow\infty}\lambda_b &=\frac{1}{\sqrt{\pi}}\lim_{M\rightarrow\infty}\sum_{m=0}^{M-1}x_m\Big( \exp(-\tau_m^2)\nonumber \\&\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad-\exp(-\tau_{m+1}^2)\Big). \label{appa4} \end{IEEEeqnarray} For $M\rightarrow\infty$, the discrete-time summation in \eqref{appa4} goes back to the integral in \eqref{eqn028}. Since it is an ideal quantization, we have $x_m=x$, and thereby having \begin{equation}\label{appa5} \lim_{b\rightarrow\infty}\lambda_b=\frac{2}{\sqrt{\pi}}\int_{-\infty}^{\infty}x^2\exp(-x^2)\mathrm{d}x=1. \end{equation} The derivation of \eqref{appa5} can be found in \cite[p. 148]{Papoulis_2002}. For the symmetric quantization, \eqref{appa3} can be written into \begin{equation}\label{appa6} \lambda_b =\frac{2}{\sqrt{\pi}}\sum_{m=M/2}^{M-1}x_m\Big( \exp(-\tau_m^2)-\exp(-\tau_{m+1}^2) \Big). \end{equation} Consider the particular range of $x\in(\tau_m, \tau_{m+1}]$ and $\tau_m>0$, in which $\exp(-x^2)$ is a monotonically decreasing function of $x$. Then, we have \begin{equation}\label{appa7} \exp(-\tau_m^2)\geq\exp(-x^2),~x\in(\tau_m, \tau_{m+1}]. \end{equation} and consequently have \begin{equation}\label{appa8} (\tau_{m+1})\exp(-\tau_m^2)\geq\int_0^{\tau_{m+1}}\exp(-x^2)\mathrm{d}x. \end{equation} Applying \eqref{eqn034} and \eqref{appa8} into \eqref{appa6} results in \begin{IEEEeqnarray}{ll}\label{appa9} \lambda_b&=\frac{2}{\sqrt{\pi}}\sum_{m=M/2}^{M-1}\tau_{m+1}\Big( \exp(-\tau_m^2)-\exp(-\tau_{m+1}^2)\Big),\\ &\geq\frac{2}{\sqrt{\pi}}\sum_{m=M/2}^{M-1}\Big[\int_0^{\tau_{m+1}}\exp(-x^2)\mathrm{d}x\nonumber\\ &\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad-(\tau_{m+1})\exp(-\tau_{m+1}^2)\Big],\\ &\geq\frac{2}{\sqrt{\pi}}\int_0^{\infty}\exp(-x^2)\mathrm{d}x=1.\label{appa11} \end{IEEEeqnarray} {\em Theorem \ref{thm01}} is therefore proved. \section{Proof of Theorem \ref{thm02}}\label{B} With the quantization noise model \eqref{eqn033}, the cross-correlation between $x$ and $q_b$ can be computed by \begin{IEEEeqnarray}{ll}\label{appb1} \mathbb{E}(xq_b)&\approx\mathbb{E}(x(4\omega_2x^2-2\omega_2)),\\ &\approx4\omega_2\mathbb{E}(x^3)-2\omega_2\mathbb{E}(x).\label{appb2} \end{IEEEeqnarray} With the condition C1), \eqref{appb2} is equivalent to \begin{equation}\label{appb3} \mathbb{E}(xq_b)\approx 4\omega_2\mathbb{E}(x^3). \end{equation} When $x$ is AWGN, the third-order term $\mathbb{E}(x^3)$ in \eqref{appb3} equals to 0 (see \cite[p. 148]{Papoulis_2002}). This leads to the observation that $\mathbb{E}(xq_b)=0$ and then the first part of {\em Theorem \ref{thm02}} is therefore proved. To prove the limit \eqref{eqn036}, we first study the coefficient $\omega_2$ in \eqref{eqn033}. For $b\rightarrow\infty$, $\omega_2$ goes back to the formula specified in \eqref{eqn028}. Then, we can compute $\omega_2$ as follows \begin{IEEEeqnarray}{ll} \omega_2&=\frac{1}{8\sqrt{\pi}}\int_{-\infty}^{\infty}x\Big[\frac{\partial^2}{\partial x^2}\exp(-x^2)\Big]\mathrm{d}x,\label{appb4}\\ &=\frac{1}{8\sqrt{\pi}}\int_{-\infty}^{\infty}x\Big[(-2+4x^2)\exp(-x^2)\Big]\mathrm{d}x,\label{appb5}\\ &=-\frac{1}{4\sqrt{\pi}}\int_{-\infty}^{\infty}x\exp(-x^2)\mathrm{d}x\nonumber\\ &\quad\quad\quad\quad\quad\quad+\frac{1}{2\sqrt{\pi}}\int_{-\infty}^{\infty}x^3\exp(-x^2)\mathrm{d}x.\label{appb6} \end{IEEEeqnarray} It is well known that (also see \cite[p. 148]{Papoulis_2002}) \begin{equation}\label{appb7} \int_{-\infty}^{\infty}x^l\exp(-x^2)\mathrm{d}x=0, ~l=1, 3; \end{equation} and thus we can obtain $\omega_2=0$ for the case of $b\rightarrow\infty$. Applying this result into \eqref{eqn033} leads to the conclusion in \eqref{eqn036}. \section{Proof of {\em Corollary \ref{cor2}}}\label{C} With \eqref{eqn039}, we can compute $\mathbf{C}_{qq}$ as follows \begin{IEEEeqnarray}{ll} \mathbf{C}_{qq} &=\mathbb{E}(\mathbf{q}_b\mathbf{q}_b^H),\label{app08}\\ &=4\omega_2^2\Big(4\underbrace{\mathbb{E}\Big(\Re(\mathbf{r})^2+j\Im(\mathbf{r})^2\Big)\Big(\Re(\mathbf{r})^2-j\Im(\mathbf{r})^2\Big)^T}_{\triangleq\mathbf{C}_{qq}^{(1)}}-\nonumber\\ &\quad2\underbrace{\mathbb{E}\Big(\Big(\Re(\mathbf{r})^2+j\Im(\mathbf{r})^2\Big)\otimes\mathbf{1}^T\Big)}_{\triangleq\mathbf{C}_{qq}^{(2)}}-\nonumber\\ &\quad2\underbrace{\mathbb{E}\Big(\mathbf{1}\otimes\Big(\Re(\mathbf{r})^2-j\Im(\mathbf{r})^2\Big)^T\Big)}_{\triangleq\mathbf{C}_{qq}^{(3)}}+\mathbf{1}\otimes\mathbf{1}^T.\Big) \label{app09} \end{IEEEeqnarray} We start from $\mathbf{C}_{qq}^{(2)}$ in \eqref{app09}. Given the conditions C3) and C4), the proof in {\em Corollary \ref{cor1}} shows that $\mathbf{r}$ is asymptotically zero-mean complex Gaussian with the covariance to be approximately $\sigma_r^2\mathbf{I}$. \begin{IEEEeqnarray}{ll} \mathbf{C}_{qq}^{(2)}&=\Big(\mathbb{E}\Big(\Re(\mathbf{r})^2\Big)+j\mathbb{E}\Big(\Im(\mathbf{r})^2\Big)\Big)\otimes\mathbf{1}^T,\label{app10}\\ &=\frac{\sigma_r^2}{2}(\mathbf{1}+j\mathbf{1})\otimes\mathbf{1}^T,\label{app11} \end{IEEEeqnarray} Analogously, the following result holds \begin{equation} \mathbf{C}_{qq}^{(3)}=\frac{\sigma_r^2}{2}\mathbf{1}\otimes(\mathbf{1}-j\mathbf{1})^T.\label{app12} \end{equation} Then, we can obtain \begin{equation}\label{app13} 2\Big(\mathbf{C}_{qq}^{(2)}+\mathbf{C}_{qq}^{(3)}\Big)=\sigma_r^2\mathbf{1}\otimes\mathbf{1}^T. \end{equation} Now, we come to the last term $\mathbf{C}_{qq}^{(1)}$, which can be computed as follows \begin{IEEEeqnarray}{ll} \mathbf{C}_{qq}^{(1)}&=\mathbb{E}\Big(\Re(\mathbf{r})^2\Re(\mathbf{r}^T)^2\Big) +\mathbb{E}\Big(\Im(\mathbf{r})^2\Im(\mathbf{r}^T)^2\Big)+\nonumber\\ &\quad j\Big(\mathbb{E}\Big(\Im(\mathbf{r})^2(\Re(\mathbf{r}^T)^2\Big)-\mathbb{E}\Big(\Re(\mathbf{r})^2(\Im(\mathbf{r}^T)^2\Big)\Big). \label{app14} \end{IEEEeqnarray} Since $\Re(\mathbf{r})$ and $\Im(\mathbf{r})$ follow the identical distribution, we can easily justify \begin{IEEEeqnarray}{ll}\label{app15} \mathbb{E}\Big(\Re(\mathbf{r})^2\Re(\mathbf{r}^T)^2\Big)&=\mathbb{E}\Big(\Im(\mathbf{r})^2\Im(\mathbf{r}^T)^2\Big), \\ \mathbb{E}\Big(\Im(\mathbf{r})^2(\Re(\mathbf{r}^T)^2\Big)&=\mathbb{E}\Big(\Re(\mathbf{r})^2(\Im(\mathbf{r}^T)^2\Big). \label{app16} \end{IEEEeqnarray} Applying \eqref{app15} into \eqref{app14} results in \begin{equation}\label{app17} \mathbf{C}_{qq}^{(1)}=2\mathbb{E}\Big(\Re(\mathbf{r})^2\Re(\mathbf{r}^T)^2\Big). \end{equation} Plugging \eqref{app17} and \eqref{app13} into \eqref{app09} yields \begin{equation}\label{app17a} \mathbf{C}_{qq}=4\omega_2^2\Big(8\mathbb{E}\Big(\Re(\mathbf{r})^2\Re(\mathbf{r}^T)^2\Big)+(1-\sigma_r^2)(\mathbf{1}\otimes\mathbf{1}^T)\Big). \end{equation} It is not hard to derive (see \cite[p. 148]{Papoulis_2002}) \begin{equation}\label{app18} \mathbb{E}\Big(\Re(r_k)^4\Big)=\frac{3\sigma_r^4}{4}. \end{equation} \begin{IEEEeqnarray}{ll} \mathbb{E}\Big(\Re(r_k)^2\Re(r_m)^2\Big)&=\mathbb{E}\Big(\Re(r_k)^2\Big)\mathbb{E}\Big(\Re(r_m)^2\Big), _{\forall k\neq m,}\label{app19}\\ &=\frac{\sigma_r^4}{4}.\label{app20} \end{IEEEeqnarray} Applying \eqref{app18} and \eqref{app20} into \eqref{app17} yields \begin{equation}\label{app21} \mathbf{C}_{qq}^{(1)}=\frac{\sigma_r^4}{2}(2\mathbf{I}+\mathbf{1}\otimes\mathbf{1}^T). \end{equation} Further applying \eqref{app21} into \eqref{app17a} yields the result \eqref{eqn044}. {\em Corollary \ref{cor2}} is therefore proved. \section{Proof of \eqref{eqn049}}\label{D} Consider the element-wise cross-correlation between the $m^\mathrm{th}$ element of $\mathbf{q}_b$ (denoted by $q_m$) and the $k^\mathrm{th}$ element of $\mathbf{s}$, i.e., \begin{IEEEeqnarray}{ll} \mathbb{E}\Big(q_ms_k^*\Big)&=\mathbb{E}\Big(\Re(s_k)\Re(q_m)+\Im(s_k)\Im(q_m)\Big)+\nonumber\\ &\quad j\mathbb{E}\Big(\Re(s_k)\Im(q_m)-\Im(s_k)\Re(q_m)\Big),\label{app01}\\ &=2\mathbb{E}\Big(\Re(s_k)\Re(q_m)\Big).\label{app02} \end{IEEEeqnarray} Using \eqref{eqn033}, we can obtain \begin{IEEEeqnarray}{ll} \mathbb{E}\Big(\Re(s_k)\Re(q_m)\Big)&=\mathbb{E}\Big(\Re(s_k)(4\omega_2\Re(r_m)^2-2\omega_2)\Big),\nonumber\label{app03}\\ &=4\omega_2\mathbb{E}\Big(\Re(s_k)\Re(r_m)^2\Big).\label{app04} \end{IEEEeqnarray} The term $\Re(r_m)$ can be represented by \begin{equation}\label{app05} \Re(r_m)=\Re(s_k)\Re(h_{m,k})+\gamma_m+\Re(v_m), \end{equation} where $\gamma_m$ is the sum of all corresponding terms that are uncorrelated with $\Re(s_k)$, and $h_{m,k}$ is the $(m,k)^\mathrm{th}$ entry of $\mathbf{H}$. Define $\epsilon_m\triangleq\gamma_m+\Re(v_m)$. We apply \eqref{app05} into \eqref{app04} and obtain \begin{IEEEeqnarray}{ll} \mathbb{E}&\Big(\Re(s_k)\Re(r_m)^2\Big)=\Re(h_{m,k})^2\mathbb{E}\Big(\Re(s_k)^3\Big)+\nonumber\\ &\quad\quad\underbrace{2\Re(h_{m,k})\mathbb{E}\Big(\Re(s_k)^2\epsilon_m\Big)+\mathbb{E}\Big(\Re(s_k)\epsilon_m^2\Big)}_{=0}.\label{app06} \end{IEEEeqnarray} Plugging \eqref{app06} into \eqref{app04} yields \begin{equation}\label{app07} \mathbb{E}\Big(\Re(s_k)\Re(q_m)\Big)=4\omega_2\Re(h_{m,k})^2\mathbb{E}\Big(\Re(s_k)^3\Big). \end{equation} The condition C4) ensures that the third-order central moments $\mathbb{E}\Big(\Re(s_k)^3\Big)=0$. Hence, we can conclude $\mathbb{E}\Big(q_ms_k^*\Big)=0, \forall m,k$. The result \eqref{eqn049} is therefore proved. \section{Elaborative Explanation of the Phenomenon of Constructive Noise}\label{E} As response to the review comment, we find it important to elaborate the phenomenon of constructive noise in the low-resolution signal detection. To better explain the phenomenon, we consider the case where two different information-bearing symbol blocks termed $\mathbf{s}^{(1)}$ and $\mathbf{s}^{(2)}$, $\mathbf{s}^{(1)}\neq\mathbf{s}^{(2)}$, are transmitted to the receiver separately. In the case of very high SNR or perhaps more extremely the noiseless case, their corresponding received blocks can be expressed by \begin{equation}\label{appe1} \mathbf{r}^{(1)}=\mathbf{H}\mathbf{s}^{(1)},~\mathbf{r}^{(2)}=\mathbf{H}\mathbf{s}^{(2)}, \end{equation} where the noise $\mathbf{v}$ is omitted for now because it is negligibly small. In this linear system, there exists a perfect bijection between $\mathbf{s}$ and $\mathbf{r}$ and we have $\mathbf{r}^{(1)}\neq \mathbf{r}^{(2)}$. For this reason, the receiver can reconstruct the information-bearing symbol block from $\mathbf{r}$ without error. The noise will only introduce the detrimental impact to the signal detection. However, such is not the case for the system with low-resolution ADC. To make the concept easy to access, we consider the special case of $1$-bit ADC, the output of which is \begin{equation}\label{appe2} \mathbf{y}^{(1)}=\mathcal{Q}_b(\mathbf{H}\mathbf{s}^{(1)}),~\mathbf{y}^{(2)}=\mathcal{Q}_b(\mathbf{H}\mathbf{s}^{(2)}). \end{equation} The nonlinear function $\mathcal{Q}_b(\cdot)$ can destroy the input-output bijection as hold in the linear system. Here, we use a simple numerical example to explain the phenomenon. To fulfill the condition $\mathbf{s}^{(1)}\neq\mathbf{s}^{(2)}$, we let $\mathbf{s}^{(1)}=[-1+3j, 3-j]^T$ and $\mathbf{s}^{(2)}=[-3+1j, 1-3j]^T$. Moreover, to simply our discussion, we let $\mathbf{H}=[\mathbf{I}_{2\times2}, \mathbf{I}_{2\times2}]^T$. Then, the output of the $1$-bit ADC is given by \begin{equation}\label{appe3} \mathbf{y}^{(1)}=\mathbf{y}^{(2)}=[-1+j, 1-j, -1+j, 1-j]^T. \end{equation} In the probability domain, we have \begin{equation}\label{appe4} \mathrm{Pr}(\mathbf{y}^{(1)}\neq\mathbf{y}^{(2)}|\mathbf{H}, \mathbf{x}^{(1)}, \mathbf{x}^{(2)})=0. \end{equation} It means that there is no bijection between $\mathbf{y}$ and $\mathbf{s}$ in this case; and for this reason, the receiver is not able to successfully reconstruct $\mathbf{s}$ from $\mathbf{y}$ even in the noiseless case. Now, we increase the noise power (or equivalently reduce the SNR). Due to the increased randomness, we understand that a positive-amplitude signal can become a negative-amplitude signal. Denote $s$ to be a real scalar drawn from the discrete finite-set $\{-3, -1, 1, 3\}$ and $v$ the Gaussian noise. It is trivial to have \begin{equation}\label{appe5} \mathrm{Pr}(s+v>0|s=-1)>\mathrm{Pr}(s+v>0|s=-3). \end{equation} As shown in \cite{9145094}, with the decrease of SNR from a large value (e.g., the noiseless case), the difference between these two probabilities will quickly increase at the beginning, and then converge to a certain non-zero value. It means that the noise helps to discriminate the ADC output $\mathbf{y}^{(1)}$ and $\mathbf{y}^{(2)}$, i.e., \begin{equation}\label{appe6} \mathrm{Pr}(\mathbf{y}^{(1)}\neq\mathbf{y}^{(2)}|\mathbf{H}, \mathbf{x}^{(1)}, \mathbf{x}^{(2)})\neq 0, \end{equation} and the probability increases with the decrease of SNR, and this helps the signal detectability \cite{809511}. Since the probability converges to a certain value at some SNR, further reducing the SNR will not improve the signal detectability but will only degrade the detection performance. For the general case, the converged probability of \eqref{appe6} can be found in \cite{9145094}, i.e., \begin{equation}\label{rev01} \mathrm{Pr}(\mathbf{y}^{(1)}=\mathbf{y}^{(2)}|\mathbf{s}^{(1)}\neq\mathbf{s}^{(2)}) =\frac{(\mathcal{L}^N)(\mathcal{L}^N-1)}{2^{(2K+1)}}, \end{equation} where $\mathcal{L}$ is the modulation order. Finally, when the resolution of the quantizer increases, the communication system becomes closer to linear, for which the noise becomes less constructive. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2021-09-14T02:15:26', 'yymm': '2109', 'arxiv_id': '2109.05334', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05334'}
arxiv
\section{Introduction} \label{sec:intro} \IEEEPARstart{I}{n} recent years, personalized recommender systems have emerged in an extensive range of Web applications to predict the preferences of its users and provide them with new and relevant items based on the scarce data about the users and/or items~\cite{koren2009matrix}. There are two major paradigms of recommender systems: (i) content-based filtering systems; (ii) collaborative filtering systems. Content-based filtering approach exploits a profile of users' preferences and/or properties of the items to carry out the recommendation task. On the other hand, collaborative filtering approach recommends new items to the users based on similarity measures between users and items. The main advantage of collaborative filtering over content-based filtering is that they do not require domain knowledge since the embeddings are automatically learned, and the more interactions the users have with the items, the more accurate and relevant the new recommendations are. Inspired by the Netflix challenge, a well-known technique to predict the missing ratings in collaborative filtering frameworks is low-rank matrix completion, which is the main interest of this paper. Given partial observation of a matrix of users by items, the goal is to develop an algorithm to accurately predict the values of the missing ratings. One of the prime challenges of collaborative filtering systems that rely on user-item interactions is the ``cold start problem'' in which high-quality recommendations are not feasible for the new users/items that bear little or no information. One prominent technique to overcome the problem with cold start users is to incorporate the community information into the framework of recommender systems in order to enhance the recommendation quality. Motivated by the social homophily theory \cite{mcpherson2001birds} that users within the same community are more likely to share similar preferences, socially-aware collaborative filtering approach exploits the social network among the users and provides recommendations based on the similarity measures of the users that have direct or indirect social relationship with a given user. A plethora of research works have explored the idea of exploiting the information inferred by social graphs to enhance the performance of recommender systems from an algorithmic perspective \cite{koren2009matrix,tang2013social,cai2010graph,jamali2010matrix,li2009relation,ma2011recommender,kalofolias2014matrix,ma2008sorec,ma2009learning,guo2015trustsvd,zhao2017collaborative,chouvardas2017robust,massa2005controversial,golbeck2006filmtrust,jamali2009trustwalker,jamali2009using,yang2012bayesian,yang2012top,monti2017geometric,berg2017graph}. However, few works dedicated to developing theoretical insights on the usefulness of graph side-information on the quality of recommendation, and characterizing the maximal achievable gain due to side-information, e.g., \cite{chiang2015matrix,rao2015collaborative}. Recently, a number of works \cite{ahn2018binary,yoon2018joint,tan2019community,jo2020discrete} have investigated the problem of interest from an information-theoretic perspective. Ahn et~al. \cite{ahn2018binary} considered a matrix completion problem with $n$ users and $m$ items, and studied a simplified model where there are two clusters of users, and the users of each cluster share the same rating over the items. A sharp threshold on the sample complexity is derived as a function of the quality of the social graph information, and the gain due to the information provided by social graph is theoretically quantified. Furthermore, the authors proposed an efficient rating estimation algorithm that provably achieves the minimum sample complexity for reliable recovery of the ground truth rating matrix. Follow-up works have investigated different models of the matrix completion problem proposed in \cite{ahn2018binary}. Yoon et~al. \cite{yoon2018joint} considered a general setting where there are $K$ hidden communities of possibly different sizes, and each community is associated to only one feature, and hence the users of each community are assumed to provide the same binary rating over the items. Unlike \cite{ahn2018binary,yoon2018joint} where one-sided graph side-information (i.e., user-to-user similarity graph) is considered, Zhang et~al. \cite{tan2019community} studied the benefits of two-sided graph side-information depicted by user-to-user and item-to-item similarity graphs. Interestingly, the theoretical analysis demonstrates that there is a synergistic effect, under some scenarios, stemmed from considering two pieces of graph side-information. This implies that observing both graphs is necessary in order to slash the sample complexity under those scenarios. Jo et~al. \cite{jo2020discrete} relaxed the assumption in \cite{ahn2018binary} on the preference matrix whose element at row $i$ and column $j$ denotes the probability that user $i$ likes item $j$, and proposed a new model in which the unknown entries of the preference matrix can take discrete values drawn from a known finite set of probabilities. While the works of \cite{ahn2018binary,yoon2018joint,tan2019community,jo2020discrete} lay out the theoretical foundation for the problem, they impose a number of strict assumptions on the system model such as the users of the same cluster have same ratings over all items, which limits the practicality of the proposed models for real-world data. A natural hypothesis in the theory of recommender systems is that the unknown rating matrix has an intrinsic structure of being low rank. This hypothesis is sensible because it is generally believed that only a few factors contribute to one's preference. Prior works \cite{ahn2018binary,yoon2018joint,tan2019community,jo2020discrete} assume that each cluster is represented by a rank-one matrix, and users within a cluster share the same rating vector over items. In this work, we relax this assumption and study a more generalized framework where each cluster is represented by a rank-$r$ matrix. More specifically, we consider a matrix completion problem where the users are categorized into $c$ clusters, each of which comprises $g$ sub-clusters, or what we call ``groups'', producing a hierarchical structure in which the features of different groups within a cluster are broadly similar to each other, however, they are different from the features of the groups in other clusters. The goal is to reliably retrieve the rating matrix under the proposed generalized model, utilizing the information provided by the noisy partial observation of the rating matrix, as well as the hierarchical social graph. \subsection{Related Works} \label{subsec:related} \subsubsection{Connection to Low-Rank Matrix Completion Problem} The objective of low-rank matrix completion, a recurring problem in collaborative filtering \cite{koren2009matrix}, is to recover an unknown low-rank matrix from partial, and possibly noisy, sampling of its entries \cite{nguyen2019low} . Since the rank minimization problem is NP-hard, accurate reconstruction is generally ill-posed and computationally intractable. However, exploiting the fact that the structure of the matrix is of low-rank makes the exploration for solution worthwhile. One direction of research is geared towards studying low-rank matrix completion where the observed subset of matrix entries are exactly known. Under certain conditions, upper bounds on the number of observed entries, which are uniformly drawn at random, are developed to ensure successful reconstruction with high probability \cite{candes2009exact,keshavan2010matrix,candes2010power}. A fundamental open question in the literature of low-rank matrix completion with exact observation is how to find a low-rank matrix that is consistent with the partial observation of its entries. This question stems from the fact that the sparse basis of the low-rank matrix is unknown, and that the basis are drawn from a continuous space. Performance guarantees provided by existing algorithms only hold when certain incoherence assumptions on the singular vectors of the matrix are satisfied. By and large, theoretical guarantees on the reconstruction performance are not established even for the rank-one case, and hence, our understanding of the problem is far from complete. Numerous algorithms for low-rank matrix completion have been proposed over the years. If the rank information of the original low-rank matrix is unknown, various techniques based on nuclear norm minimization are proposed \cite{fazel2002matrix,candes2009exact,keshavan2010matrix,candes2010power,cai2010singular,fornasier2011low,mohan2012iterative}. On the other hand, if the rank is known in advance, techniques based on Frobenius norm minimization are proposed \cite{lee2010admira,wang2014rank,tanner2016low,wen2012solving,dai2705set,vandereycken2013low,hu2012fast,gotoh2018dc}. Another interesting and practical research direction is investigating low-rank matrix completion when the observed entries are contaminated by noise. The objective is to seek a low-rank matrix that best approximates the original matrix, and find an upper bound on the root-mean squared error \cite{candes2010matrix,keshavan2010matrix}. \subsubsection{Algorithms for Recommender Systems with Graph Side-Information} The idea of exploring the value of incorporating graph side-information into collaborative filtering approaches has gained a lot of attention from the research community \cite{tang2013social}. There are two primary approaches of collaborative learning \cite{koren2009matrix}: (i) latent factor approach, and (ii) neighborhood approach. Latent factor approach learns latent features for users and items from the observed ratings. Most successful realizations of this approach hinge on matrix factorization which characterizes the latent characteristics of users and items by two low-rank user- and item-feature matrices inferred from the rating patterns. One direction to integrate graph side-information in this approach is through adding some regularization terms in the loss function of the matrix factorization model \cite{cai2010graph,jamali2010matrix,li2009relation,ma2011recommender,kalofolias2014matrix}. Another direction is to develop matrix factorization frameworks that fuse the user-item rating matrix with the social network of the users \cite{ma2008sorec,ma2009learning,guo2015trustsvd,zhao2017collaborative}. Moreover, a robust online matrix completion on graphs is designed and analyzed in \cite{chouvardas2017robust} that exploits the graph information to recover the incomplete rating matrix entires in the presence of outlier noise. On the other hand, for neighborhood approach, the prediction of rating information is based on computing the relationships among items or users. The recommendation accuracy in this approach can be enhanced by incorporating the information provided by the social graphs into the neighborhood definition \cite{massa2005controversial,golbeck2006filmtrust,jamali2009trustwalker,jamali2009using,yang2012bayesian,yang2012top}. Lately, recent works have proposed novel architectures for graph convolutional neural networks that fully exploit the structure of item/user graphs \cite{monti2017geometric,berg2017graph}. Few works have provided theoretical insights on the usefulness of side-information for matrix completion problem, e.g., \cite{chiang2015matrix,rao2015collaborative}. Chiang et~al. \cite{chiang2015matrix} proposed a dirty statistical model to exploit the feature-based side information, yet to be robust to feature noise, in matrix completion applications. They provided theoretical guarantees that the proposed model achieves lower sample complexity than the standard matrix completion (with no graph information) under the condition that the features are not too noisy. Rao et~al. \cite{rao2015collaborative} proposed a scalable graph regularized matrix completion, and derived consistency guarantees to demonstrate the gain due to the graph side-information. It is worth mentioning that the maximal achievable gain due to graph side-information is not characterized in these works. \subsubsection{Connection to Community Detection in Stochastic Block Model} Stochastic Block Model (SBM) \cite{holland1983stochastic} with two communities, which is also known as the planted bisection model, is an extension to Erd\"{o}s-R\'{e}nyi (ER) random graph model that exhibits community structure. It is based on the assumption that agents (nodes) in a network (graph) connect depending on their community assignment, unlike Erd\"{o}s-R\'{e}nyi (ER) model in which agents connect independently. The goal is to reconstruct the community assignment upon observing the unlabeled graph. This problem has been well investigated from an information-theoretic perspective where a sharp threshold is characterized for exact recovery of communities \cite{abbe2017community,abbe2015exact,abbe2015community,jog2015information,mossel2015reconstruction,hajek2017information,saad2018community,saad2018exact,saad2018recovering}. Inspired by applications in physics, computational social science, and machine learning, several generalizations of the classical SBM have been developed to explore the benefits of considering various types of side-information in the task of community recovery. Generalizations have been made to incorporate infinite number of blocks \cite{kemp2006learning}, probabilistic block membership \cite{airoldi2008mixed,ball2011efficient}, heterogeneous degree within blocks \cite{karrer2011stochastic}, weighted edges between nodes \cite{aicher2013adapting}, and node attributes \cite{yang2013community}. One crucial and practical generalization to SBM, that we consider in this work, is the hierarchical (nested) organization of blocks, where vertices are partitioned into blocks, each of which is further partitioned into sub-blocks \cite{clauset2008hierarchical,peixoto2014hierarchical,lyzinski2016community,cohen2019hierarchical}. The edge probabilities in a hierarchical random graphs are inhomogeneous and determined by the topology structure. \subsubsection{Connection to Clustering Problem with Side-Information} There has been some recent works that investigate the clustering problem with side-information, where the learner is allowed to interact with a domain expert. Ashtiani et~al. \cite{ashtiani2016clustering} proved that having access to few pairwise queries leads to more efficient k-means clustering, which is NP-hard in general. Mazumdar et~al. \cite{mazumdar2017query} explored the benefits of the similarity matrix, that is used to cluster similar points together, to slash the adaptive query complexity. In both works, information-theoretic lower bounds are proved, and efficient clustering algorithms are designed. Matrix Completion problem with graph side-information can be seen as a natural extension to clustering problem if we shift our focus to recovering the structure of (hierarchical) clusters instead of reconstructing the rating matrix. \subsection{Main Contributions} \label{sebsec:contributions} The main contributions of this paper are summarized as follows. We conduct a rigorous theoretical study and characterize an information-theoretic threshold for optimal rating matrix recovery, rather than starting with a certain algorithmic approach. We establish matching upper and lower bounds on the sample complexity for reliable recovery of the rating matrix, and hence exactly characterize the optimal sample complexity that is a function of the quality of social graph side-information. In the proof of achievability bound, we show that probability of error of the maximum likelihood estimator vanishes for sufficiently large number of users and items, if all sufficient conditions are met. On the other hand, the proof of the converse bound is based on the genie-aided maximum likelihood estimator. Under each necessary condition, we present examples of a genie-aided estimator to prove that the probability of error does not vanish for sufficiently large number of users and items. While numerous low-complexity matrix completion algorithms have been proposed, it remains an open problem to develop optimization algorithms with provable performance guarantees for a generic class of matrices \cite{nguyen2019low}. This work makes substantial progress on this long-standing open problem. We also emphasize on the fact that this work is a non-trivial extension of \cite{ahn2018binary} and \cite{yoon2018joint}, as will be delineated in the following sections. A preliminary version of the main results of this paper has been reported in \cite{elmahdy2020matrix} for $(c,g,r,q)=(2,3,2,2)$. In this paper, we characterize the optimal sample complexity result for any $(c,g,r,q)$, and present the complete achievability and converse proofs. \subsection{Notation} \label{subsec:notation} Row vectors and matrices are denoted by lowercase letters (e.g., $v$) and uppercase letters (e.g., $X$), respectively. Random matrices are denoted by boldface uppercase letters (e.g., $\mathbf{X}$), while their realizations are denoted by uppercase letters (e.g., $X$). Sets are denoted by calligraphic letters (e.g., $\mathcal{Z}$). Let $\mathbb{F}_{q}$ be a finite field of order $q$ for some prime number $q$. Let $\mathbf{0}_{n \times m}$ and $\mathbf{1}_{n \times m}$ be all-zero and all-one matrices of dimension $n \times m$, respectively. For a matrix $X \in \mathbb{F}_{q}^{n \times m}$, let $X^\intercal$ denote the transpose of $X$. Let $X(r,t)$ denote the matrix entry at row $r$ and column $t$. Furthermore, let $X(i,:)$ and $X(:,j)$ denote the $i^{\text{th}}$ row and $j^{\text{th}}$ column of matrix $X$, respectively. Furthermore, for sets $\mathcal{I}$ and $\mathcal{J}$, the submatrix of $X$, that is obtained by rows $i\in\mathcal{I}$ and columns $j\in\mathcal{J}$, is denoted by $X(\mathcal{I},\mathcal{J})$. Let $\numDiffElmnt{X}{Y}$ denote the number of different entries between matrices $X$ and $Y$ for $X,Y \in \mathbb{F}_{q}^{n \times m}$. For $u,v \in \mathbb{F}_q^{1 \times m}$, we use $[u;\:v]$ to denote $[u^\intercal \ v^\intercal]^\intercal$. Let $v(t)$ denote the $t^{\text{th}}$ entry of $v$. Moreover, the Hamming distance between two vectors $u$ and $v$ is denoted by $\hamDist{u}{v}$. It is defined as the number of entries in which $u$ and $v$ differ. Let $\left\| u \right\|_1$ denote the $\ell_1$ norm of vector $u$. For an integer $n \geq 1$, let $[n]$ denote the set of integers $\{1,2,\ldots,n\}$. For integers $n$ and $m$ where $n \leq m$, define $[n:m]$ as $\{n, n+1, \cdots, m\}$. Let $\{0,1,\cdots,q-1\}^n$ be the set of all $n$-digit sequences whose digits are drawn from $\mathbb{F}_q$. Moreover, we use $\indicatorFn{\cdot}$ to denote the indicator function. Finally, $\mathcal{G}=([n], \mathcal{E})$ denotes an undirected graph $\mathcal{G}$ where $[n]$ is the set of $n$ vertices labeled by integers in $[n]$; and $\mathcal{E}$ is the set of undirected edges. The elements of $\mathcal{E}$ are given by pairs $(a,b)$ for $a,b \in [n]$. \subsection{Paper Outline} \label{subsec:outline} The remainder of this paper is organized as follows. We first present the problem formulation of the rating matrix and hierarchical similarity graph in Section~\ref{subsec:probForm}. Then, the main results are presented in Section~\ref{subsec:mainRes}. In Section~\ref{sec:interpretation}, information-theoretic interpretation of the main results is provided, and extensive numerical results are presented. Next, the achievability proof is presented in Section~\ref{sec:achv}, while the converse proof is presented in Section~\ref{sec:conv}. In Section~\ref{sec:expResults}, we present simulation results that corroborate our main results. Finally, the paper is concluded and directions for future research are discussed in Section~\ref{sec:conclusion}. \section{Problem Formulation} \label{subsec:probForm} Consider a rating matrix $X \in \mathbb{F}_{q}^{n \times m}$ where $n$ denotes the number of users and $m$ denotes the number of items. The ratings of the $r^{\text{th}}$ user over $m$ items are given by the rating vector that corresponds to the $r^{\text{th}}$ row of $X$ for $r \in [n]$. The user similarity graphs (e.g., social graphs) are leveraged as side-information during the matrix completion procedure to enhance the item recommendation quality. More specifically, we consider a hierarchical similarity graph that consists of $c$ disjoint clusters, and each cluster comprises $g$ disjoint sub-clusters (or that we call ``groups''). For the sake of tractable mathematical analysis, we assume equal-sized clusters and groups. The theoretical guarantees, however, hold as long as the group sizes are order-wise same (See Section~\ref{subsec:mainRes}). According to social homophily theory~\cite{mcpherson2001birds}, users within the same community (i.e., who are more likely to be connected in a social graph) are more likely to share similar preferences of items. This results in a low rank structure of the rating matrix since the rows of the rating matrix associated with such users are highly likely to be similar \cite{nguyen2019low}. To capture this crucial fact in our model, we make the following assumptions: (i) the rating vectors of the users who belong to the same group are equal, and hence there are $gc$ distinct rating vectors in total; (ii) the rating vectors of the groups of a given cluster are different, yet intimately-related to each other through a linear subspace of $r$ basis vectors for some integer $r \leq g$. Let $\vecV{i}{x}$ denotes the rating vector of the users in cluster $x$ and group $i$ for $x \in [c]$ and $i \in [g]$. Let $\ratingCluster{x} \in \mathbb{F}_{q}^{g \times m}$ denote a matrix whose rows are the rating vectors of the groups in cluster~$x$ for $x \in [c]$. The set of $g$ rows of $\ratingCluster{x}$ (i.e., set of $g$ rating vectors of the groups in cluster~$x$) is spanned by any subset of $r$ rows of $\ratingCluster{x}$. Let $\gtMat$ denote the ground truth rating matrix. Each instance of the problem corresponds to a rating matrix $\gtMat$, which can be represented by a set of rating vectors $\mathcal{V}_0 = \{ \vecU{i}{x}: x\in [c], i\in [g]\}$ and a user partitioning $\mathcal{Z}_0$. For instance, consider a problem with $n=12$ users in $c=2$ clusters and $g=3$ groups. If the rating matrix is given by \begin{align} \gtMat = \begin{bmatrix} \vecU{1}{1};\:\: \vecU{2}{1};\:\: \vecU{1}{2};\:\: \vecU{3}{2};\:\: \vecU{3}{1};\:\: \vecU{2}{1};\:\: \vecU{2}{2};\:\: \vecU{1}{2};\:\: \vecU{3}{1};\:\: \vecU{3}{2};\:\: \vecU{2}{2};\:\: \vecU{1}{1} \end{bmatrix}, \end{align} then we have the set of rating vectors as \begin{align} \mathcal{V}_0 &= \left\{ \vecU{1}{1},\: \vecU{2}{1},\: \vecU{3}{1},\: \vecU{1}{2},\: \vecU{2}{2},\: \vecU{3}{2} \right\}, \end{align} and the user partitioning as \begin{align} \mathcal{Z}_0 &= \left\{ Z_0(1,1)\!=\!\{1,12\},\: Z_0(1,2)\!=\!\{2,6\},\: Z_0(1,3)\!=\!\{5,9\},\: Z_0(2,1)\!=\!\{3,8\},\: Z_0(2,2)\!=\!\{7,11\},\: Z_0(2,3)\!=\!\{4,10\} \right\}. \end{align} Formally, $\mathcal{Z}_0$ is a family of subsets of $[n]$ that partitions the set of all users $[n]$ into $c$ clusters and $g$ groups (per cluster). That is, \begin{align} \mathcal{Z}_0 = \left\{ \left\{Z_0(x,i)\right\}_{x \in [c],\: i \in [g]}: Z_0(x,i) \subseteq [n],\: Z_0(x,i) \cup Z_0(y,j) = \varnothing \mbox{ for } (x,i) \neq (y,j), \: \bigcup_{x\in[c]} \bigcup_{i\in[g]} Z_0(x,i) = [n] \right\}, \label{eq:Z_defn} \end{align} where $Z_0(x,i)$ denotes the set of users who belong to cluster $x$ and group $i$ for $x \in [c]$ and $i \in [g]$. The main goal of the problem of interest is to find the best estimate of $\gtMat$ with the knowledge of two types of observations: \begin{enumerate \item partial and noisy observation $Y$ of $\gtMat$. For every $r \in [n]$ and $t \in [m]$, let $Y(r,t) \in \mathbb{F}_q \cup \{*\}$, where $*$ denotes no~observation. Let the set of observed entries of $\gtMat$ be denoted by $\Omega=\{(r,t)\in [n]\times [m]: Y(r,t)\neq *\}$. The partial observation is modeled by assuming that each entry of $\gtMat$ is observed with probability $p \in [0,1]$, independently from others. Moreover, the potential noise in the observation is modeled by considering a random uniform noise distribution, that is, the noise is not adversarial (i.e., not deterministic). In particular, we assume that each observed entry $\gtMat(r,t)$, for $(r,t) \in \Omega$, can be possibly flipped to any element of the set $\{0,1,\ldots, q\} \setminus \gtMat(r,t)$ with a uniform probability of $\theta/(q-1)$ for $\theta \in [0, (q-1)/q)$. The reasons behind choosing this noise model are: (i) the uniform noise distribution is the worst case distribution in discrete channels; and (ii) this model captures the fact that there may exist a fraction of group members whose ratings are close to the majority ratings, yet they are not exactly identical. Hence, the majority ratings can be considered as the ground truth, while the ratings of this fraction of users can be seen as noisy version of the ground truth. Furthermore, since this fraction of users have some ratings that are different from the majority, each of such ratings can take a value that is randomly and uniformly selected from the set of all possible ratings different from that of the majority; \item user similarity graph ${\mathcal{G}=([n], \mathcal{E})}$. A~vertex represents a user, and an edge captures a social connection between two users. The set $[n]$ of vertices is partitioned into $c$ disjoint clusters, each of which is of size $n/c$ users. Each cluster is further partitioned into $g$ disjoint groups, each of which is of size $n/(cg)$ users. The user similarity graph is generated as per the hierarchical stochastic block model (HSBM)~\cite{abbe2017community,lyzinski2016community}, which is a generative model for random graphs exhibiting hierarchical cluster behavior. In this model, each two nodes in the graph are connected by an edge, independent of all other nodes, with probabilities given by \begin{align} \begin{split} \alphaEdge &:= \mathbb{P} \left[(a,b) \in \mathcal{E}: a,b \in \grpG{i}{x} \right], \text{ for } x \in [c],\: i \in [g], \\ \betaEdge &:= \mathbb{P} \left[(a,b) \in \mathcal{E}: a \in \grpG{i}{x}, b \in \grpG{j}{x}\right], \text{ for } x \in [c],\: i,j \in [g],\: i \neq j, \\ \gammaEdge &:= \mathbb{P} \left[(a,b) \in \mathcal{E}: a \in \grpG{i}{x}, b \in \grpG{j}{y}\right], \text{ for } x,y \in [c],\: x \neq y,\: i,j \in [g]. \end{split} \label{eq:edge_prob_defn} \end{align} Here, we assume that edge probabilities are scaling with the size of the problem. In particular, we assume \begin{align} \alphaEdge = \alpha \frac{\log n}{n}, \quad \betaEdge = \beta \frac{\log n}{n}, \quad \gammaEdge = \gamma \frac{\log n}{n}, \label{eq:edge_prob_assump} \end{align} where $\alpha$, $\beta$ and $\gamma$ are positive real numbers such that $\alpha \geq \beta \geq \gamma$. In other words, there is an edge between two users in the \emph{same group} within a cluster with probability $\alphaConst \frac{\log n}{n}$; there is an edge between two users in \emph{different groups} but within the \emph{same cluster} with probability $\betaConst \frac{\log n}{n}$; and there is an edge between two users in \emph{different clusters} with probability $\gammaConst \frac{\log n}{n}$. Note that the considered edge probabilities guarantee the disappearance of isolated vertices (i.e., vertices of degree zero) in the user similarity graph, which is a necessary property for exact recovery in stochastic block model (SBM) \cite{abbe2015community}. Furthermore, motivated by the social homophily theory~\cite{mcpherson2001birds}, we study the problem of interest when users within the same group (or cluster) are more likely to be connected than those in different groups (or clusters). That is why we assume that $\alphaConst \geq \betaConst \geq \gammaConst$. \end{enumerate} Let $\psi$ denote an estimator (decoder) that takes as input a pair $(Y,\mathcal{G})$ where $Y$ is the incomplete and noisy rating matrix and $\mathcal{G}$ is the user similarity graph, and outputs a completed rating matrix $X\in \mathbb{F}_{q}^{n \times m}$. Note that both the set of rating vectors $\mathcal{V}$ and the user partitioning\footnote{To be more precise, $\mathcal{Z}$ can be recovered from $X$ up to a relabeling of the clusters and groups, i.e., we can only identify which users belong to the same group/cluster, but the label associated to a group/cluster cannot be identified.} $\mathcal{Z}$ can be recovered from the completed rating matrix $X$ and vice versa. Hence, with slightly abuse of notation, we may interchangeably use $X$ or $(\mathcal{V}, \mathcal{Z})$ as the output of the estimator. The former notation is adopted when we are interested in the entries of the rating matrix, while the latter notation is used when we are interested in either the set of rating vectors or the user partitioning. One key parameter, that is instrumental in expressing the main result (see Section~\ref{subsec:mainRes}) as well as proving the main theorem, is the discrepancy between the rating vectors. Let $\intraTau$ be the minimum normalized Hamming distance among distinct pairs of rating vectors of groups \emph{within the same cluster}. Let $\interTau$ be the counterpart with respect to distinct pairs of rating vectors \emph{across different clusters}. More formally, $\intraTau$ and $\interTau$ are given by \begin{align} \begin{split} \intraTau &= \frac{1}{m} \: \min_{x \in [c]} \: \min_{\substack{i,j \in [g] \\ i \neq j}} \hamDist{\vecU{i}{x}}{\vecU{j}{x}}, \\ \interTau &= \frac{1}{m} \min_{\substack{i,j \in [g] \\ x,y \in [c], x\neq y}} \hamDist{\vecU{i}{x}}{\vecU{j}{y}}. \end{split} \end{align} As will be elaborated in the next section, our result hinges on $\delta \coloneqq (\intraTau, \interTau)$. We provide theoretical guarantees for the recovery of all rating matrices $M$ in which the rating vectors maintain a minimum level of dissimilarity. Formally, we define $\matSet$ to be the set of rating matrices $M=(\mathcal{V},\mathcal{Z})$ such that the following properties are satisfied: \begin{itemize} \item the set of rating vectors $\mathcal{V}$ must satisfy the property that the minimum normalized Hamming distance among the rating vectors in different groups within the same cluster and those in different clusters are not smaller that $\intraTau$ and $\interTau$, respectively; \item the user partitioning $\mathcal{Z}$ must satisfy the property that the size of clusters is $c/n$ users, while the size of the groups is $c/(ng)$ users. \end{itemize} The performance metric we consider to provide theoretical guarantees on the quality of recommendation is the worst-case probability of error $P_e$. In other words, the quality of the estimator is defined by its accuracy of estimation of the \emph{most difficult} ground truth matrix $M=(\mathcal{V},\mathcal{Z})\in \matSet$. Therefore, we apply a minimax optimization approach wherein the objective is to find the estimator that minimizes the maximum risk (i.e., minimizes the worst-case probability of error). This can be expressed as \begin{align} \label{eq:errorProb_wc} \inf_{\psi} P_e^{(\delta)} (\psi) = \inf_{\psi} \max_{M \in \matSet} \mathbb{P}\left[\psi(Y, \mathcal{G}) \neq M \right]. \end{align} Based on the proposed problem formulation and performance metric, we aim at characterizing the optimal sample complexity (i.e., the minimum number of entries of the rating matrix that is required to be observed), concentrated around $nmp^{\star}$ in the limit of $n$ and $m$, for exact rating matrix recovery. Here, $p^{\star}$ denotes a sharp threshold on the observation probability such that the following conditions, in the limit of $n$ and $m$, are satisfied: \begin{itemize \item when $p > p^{\star}$, there exists an estimator such that the error probability can be made arbitrarily close to 0; \item when $p < p^{\star}$, the error probability does not converge to zero no matter what and whatsoever. \end{itemize} \section{Main Results} \label{subsec:mainRes} \begin{theorem}[Optimal Sample Complexity] \label{thm:p_star} Let $m = \omega(\log n)$ and $\log m = o(n)$. Let $q,\theta,c,g$ and $r$ be constants such that $q$ is prime, $\theta \in [0,(q-1)/q)$, and $r \leq g$. For any constant $\epsilon >0$, if \begin{align} p \geq\! \frac{1}{\left(\!\!\sqrt{1\!-\!\theta} \!-\!\! \sqrt{\frac{\theta}{q-1}}\right)^{\!\!2}} \max \!\left\{\! \frac{gc (1\!+\!\epsilon)}{g\!-\!r\!+\!1} \frac{\log m }{n}, \frac{\log n}{\intraTau m} \!\left(\!\!(1\!+\!\epsilon) \!-\! \frac{\left(\sqrt{\alphaConst} \!-\!\! \sqrt{\betaConst}\right)^{\!2}}{gc}\!\right)\!, \frac{\log n}{\interTau m} \!\left(\!\!(1\!+\!\epsilon) \!-\! \frac{\left(\sqrt{\alphaConst} \!-\!\! \sqrt{\gammaConst}\right)^{\!2} \!\!+\! (g\!-\!1) \!\left(\sqrt{\betaConst} \!-\!\! \sqrt{\gammaConst}\right)^{\!2}}{gc} \!\right) \!\!\right\}\!\!, \label{eq:pstar-general_achv} \end{align} then there exists an estimator $\psi$ that outputs a rating matrix $X \in \matSet$ given $Y$ and ${\cal G}$ such that $\lim_{n \rightarrow \infty} P_e^{(\delta)} (\psi) = 0$; conversely, if \begin{align} p \leq\! \frac{1}{\left(\!\!\sqrt{1\!-\!\theta} \!-\!\! \sqrt{\frac{\theta}{q-1}}\right)^{\!\!2}} \max \!\left\{\! \frac{gc (1\!-\!\epsilon)}{g\!-\!r\!+\!1} \frac{\log m }{n}, \frac{\log n}{\intraTau m} \!\left(\!\!(1\!-\!\epsilon) \!-\! \frac{\left(\sqrt{\alphaConst} \!-\!\! \sqrt{\betaConst}\right)^{\!2}}{gc}\!\right)\!, \frac{\log n}{\interTau m} \!\left(\!\!(1\!-\!\epsilon) \!-\! \frac{\left(\sqrt{\alphaConst} \!-\!\! \sqrt{\gammaConst}\right)^{\!2} \!\!+\! (g\!-\!1) \!\left(\sqrt{\betaConst} \!-\!\! \sqrt{\gammaConst}\right)^{\!2}}{gc} \!\right) \!\!\right\}\!\!, \label{eq:pstar-general_conv} \end{align} then $ \lim_{n \rightarrow \infty} P_e^{(\delta)}(\psi) \neq 0$ for any estimator $\psi$. Therefore, the optimal observation probability $p^{\star}$ is given by \begin{align} p^{\star} = \frac{1}{\left(\sqrt{1\!-\!\theta} \!-\! \sqrt{\frac{\theta}{q-1}}\right)^2} \max \!\left\{\! \frac{gc}{g\!-\!r\!+\!1} \frac{\log m }{n},\: \frac{\log n}{\intraTau m} \left(\!1 \!-\! \frac{\left(\sqrt{\alphaConst} \!-\! \sqrt{\betaConst}\right)^2}{gc}\!\right),\: \frac{\log n}{\interTau m} \left(\!1-\frac{\left(\sqrt{\alphaConst} \!-\! \sqrt{\gammaConst}\right)^2 \!+\! (g\!-\!1) \!\left(\sqrt{\betaConst} \!-\! \sqrt{\gammaConst}\right)^2}{gc} \!\right) \!\!\right\}\!. \label{eq:pstar-general} \end{align} \end{theorem} \begin{IEEEproof} We provide a concise proof sketch of Theorem~\ref{thm:p_star}, along with the technical distinctions with respect to the prior works~\cite{ahn2018binary,yoon2018joint}. We defer the complete achievability proof to Section~\ref{sec:achv}, and the converse proof to Section~\ref{sec:conv}. The achievability proof is based on maximum likelihood estimation (MLE). We first evaluate the likelihood for a given clustering/grouping of users and the corresponding rating matrix. Next, we provide an upper bound on the worst-case probability of error, which is given by the probability that the likelihood of the ground truth rating matrix is less than that of a candidate rating matrix. Finally, we perform typical and atypical error analyses and demonstrate that if $p > p^\star$, where $p^\star$ is given by \eqref{eq:pstar-general}, the likelihood is maximized only by the ground-truth rating matrix, and hence the worst-case probability of error vanishes, in the limit of $n$ and $m$. This completes the achievability proof. On the other hand, the converse (impossibility) proof hinges on the genie-aided maximum likelihood estimation. We first establish a lower bound on the error probability, and show that it is minimized when employing the maximum likelihood estimator. Next, we prove that if $p$ is smaller than any of the three terms in the RHS of~\eqref{eq:pstar-general}, then there exists another solution that yields a larger likelihood, compared to the ground-truth matrix. More precisely, for any estimator and any ground truth rating matrix, we have the following three cases: \begin{itemize} \item if $p \leq \frac{(1-\epsilon) gc \log m}{(\sqrt{1-\theta}- \sqrt{\theta / (q-1)})^2 (g-r+1) n}$, there exists a class of matrices that is obtained by replacing one column of the ground truth rating matrix with a carefully chosen sequence, and yields a larger likelihood than the one of the ground truth rating matrix; \item if $p \leq \frac{\log n }{ (\sqrt{1-\theta}- \sqrt{\theta / (q-1)})^2 \intraTau m} ((1\!-\!\epsilon) - \frac{(\sqrt{\alphaConst} - \sqrt{\gammaConst})^{2}}{gc})$, there exists a class of rating matrices which is obtained by swapping the rating vectors of two users in the same cluster yet from distinct groups such that the hamming distance between their rating vectors is~$m \intraTau$. We show that the likelihood of any rating matrix from this class is greater than the one of the ground truth rating matrix; \item and finally, if $p \leq \frac{\log n }{ (\sqrt{1-\theta}- \sqrt{\theta / (q-1)})^2 \interTau m} ((1\!-\!\epsilon) - \frac{(\sqrt{\alphaConst} - \sqrt{\gammaConst})^{2} + (g-1) (\sqrt{\betaConst} - \sqrt{\gammaConst})^{2}}{gc})$, there exists a class of rating matrices which is obtained by swapping the rating vectors of two users in distinct clusters such that the hamming distance between their rating vectors is~$m \interTau$. We demonstrate that any rating matrix from this class yields a larger likelihood than the one of the ground truth rating matrix. \end{itemize} For each case, we show that the maximum likelihood estimator will fail in the limit of $n$ and $m$ by selecting one of the rating matrices from the respective class instead of the ground truth rating matrix. This completes the converse proof, and concludes the proof of Theorem~\ref{thm:p_star}. The technical distinctions with respect to the prior works~\cite{ahn2018binary,yoon2018joint} are four folded: (i) the likelihood computation requires more involved combinatorial arguments due to the hierarchical structure of the similarity graph; (ii) sophisticated upper/lower bounding techniques are developed in order to exploit the relational structure across different groups; (iii) novel typical and atypical error analyses are derived for the achievability proof; and (iv) novel failure proof techniques are proposed in the converse proof. \end{IEEEproof} The assumptions $m = \omega(\log n)$ and $\log m = o(n)$ are introduced in order to be able to apply large deviation theories, as will be shown in the proof of Theorem~\ref{thm:p_star}. These assumptions are also practically relevant as they eliminate the possibility of having extremely tall and wide matrices, respectively. The following remark demonstrates that the problem setting considered in \cite{elmahdy2020matrix} is a special case of the general setting considered in this paper, and their result is subsumed by our generalized result presented in Theorem~\ref{thm:p_star}. \begin{remark} Setting $(c,g,r,q)=(2,3,2,2)$, the optimal observation probability $p^{\star}$ reduces to \begin{align} p^{\star} = \frac{1}{ \left(\sqrt{1- \theta} - \sqrt{\theta} \right)^2} \:\max \left \{ 3 \:\frac{\log m}{n}, \: \frac{\log n}{\intraTau m} \left(1 - \frac{\left(\sqrt{\alphaConst} - \sqrt{\betaConst}\right)^2}{6}\right), \: \frac{\log n}{\interTau m} \left(1- \frac{\left(\sqrt{\alphaConst} - \sqrt{\gammaConst}\right)^2}{6} - \frac{\left(\sqrt{\betaConst} - \sqrt{\gammaConst}\right)^2}{3} \right) \right\}, \label{eq:pstar} \end{align} which is equal to the shape threshold on $p$ characterized\footnote{The optimal sample complexity for general $(c,g,r,q)$, given by \eqref{eq:pstar-general}, is conjectured by \cite{elmahdy2020matrix}. However, the achievability and converse proofs are provided only for $(c,g,r,q)=(2,3,2,2)$ in \cite{elmahdy2020matrix}. In this paper, we present complete achievability and converse proofs for any $(c,g,r,q)$.} by \cite{elmahdy2020matrix} under the setting of $(c,g,r,q)=(2,3,2,2)$. \end{remark} \section{Information-Theoretic Interpretation of Theorem~\ref{thm:p_star}} \label{sec:interpretation} \begin{JA_AE} We investigate the relationship between the optimal sample complexity $nmp^\star$, where $p^\star$ is characterized by \eqref{eq:pstar-general} in Theorem~\ref{thm:p_star}, and different parameters related to the rating matrix as well as the hierarchical user similarity graph. \subsection{Minimum Hamming Distance} \label{subsec:min_hamdist} The optimal sample complexity increases as $\intraTau$ (or $\interTau$) decreases. This is due to the fact that as the Hamming distance between rating vectors of two users in different groups within the same cluster (or in different clusters) decreases, it becomes harder to distinguish the rating vectors, and hence it leads to imperfect user grouping (or clustering). Thus, one has to sample more entries of the rating matrix in order to exactly recover the rating matrix. \subsection{Observation Noise} \label{subsec:obs_noise} It is evident that the optimal sample complexity increases as $\theta$ increases. Furthermore, as $\theta$ approaches $(q-1)/q$, each sampled entry of the rating matrix can take any of the $q$ possible values with a uniform probability of $1/q$, and hence an infinite sample complexity is theoretically required to exactly recover the entries of the rating matrix. \subsection{Quality of the Hierarchical Similarity Graph} \label{subsec:quality_graph} In order to better illustrate the relationship between the optimal sample complexity and the quality of the hierarchical graph, we define the following quality parameters: \begin{align} \Ig \coloneqq \left(\sqrt{\alpha} - \sqrt{\beta}\right)^2, \quad \IcOne \coloneqq \left(\sqrt{\alpha} - \sqrt{\gamma}\right)^2, \quad \IcTwo \coloneqq \left(\sqrt{\beta} - \sqrt{\gamma}\right)^2. \end{align} Intuitively, as $\Ig$ increases, it becomes easier to distinguish users in different groups within the same cluster. On the other hand, larger values of $\IcOne$ and $\IcTwo$ leads to better user clustering. The optimal sample complexity reads different values depending on the quality parameters of the hierarchical graph. More specifically, we define three regimes as follows: \begin{enumerate} \item the first term in the RHS of \eqref{eq:pstar-general} is activated when $\Ig, \IcOne$ and $\IcTwo$ are large enough so that the grouping and clustering information are reliable. Hence, this regime is coined as \emph{``perfect clustering/grouping regime''}; \item the second term in the RHS of \eqref{eq:pstar-general} is activated when $\Ig$ is small such the grouping information is not reliable, Therefore, this regime is coined as \emph{``grouping-limited regime''}; \item the third term in the RHS of \eqref{eq:pstar-general} is activated when $\IcOne$ and $\IcTwo$ are small such that the clustering information is not reliable, and\footnote{It is evident from \eqref{eq:pstar-general} and $\alphaConst \geq \betaConst \geq \gammaConst$ that the third term in the RHS of \eqref{eq:pstar-general} is inactive whenever $\intraTau \leq \interTau$.} $\intraTau > \interTau$. Thus, this regime is coined as \emph{``clustering-limited regime''}. \end{enumerate} In what follows, we analyze the optimal sample complexity under each regime, and highlight the novel technical contributions in the achievability proof (See Section~\ref{sec:achv}) as well as the converse proof (See Section~\ref{sec:conv}). For illustrative simplicity, we focus on the noiseless case where $\theta = 0$. \subsubsection{Perfect Clustering/Grouping Regime} The optimal sample complexity reads $(gc / (g-r+1)) m \log m$. Since the grouping and clustering information are reliable, one can recover the groups and clusters from the similarity graph. However, further increments of the values of these quality parameters do not yield further improvement in the sample complexity, and hence the sample complexity gain from the similarity graph is saturated in this regime. Moreover, it should be noted that a naive generalization of~\cite{ahn2018binary, yoon2018joint} requires $c r m \log m$ observations since there are $r$ independent rating vectors to be estimated for each the $c$~clusters, and each rating vector requires $m \log m$ observations under the considered random sampling due to the coupon-collecting effect. On the other hand, we leverage the relational structure (i.e, linear dependency) across rating vectors of different group, reflected by the underlying linear MDS code structure (to be detailed in Section~\ref{sec:achv}), and hence this serves to estimate the $rc$~rating vectors more efficiently, precisely by a factor of $r(g-r+1)/g$ improvement, thus yielding $(gc / (g-r+1)) m \log m$. \subsubsection{Grouping-Limited Regime} The optimal sample complexity reads \begin{align*} \frac{1}{\intraTau} \left(1 - \frac{\left(\sqrt{\alphaConst} - \sqrt{\betaConst}\right)^2}{gc}\right) n \log n &= \frac{1}{\intraTau} \left(1 - \frac{\Ig}{gc}\right) n \log n, \end{align*} which is a decreasing function of $\Ig$. This sample complexity coincides with that of~\cite{yoon2018joint} in which the considered similarity graph consists of only $gc$ clusters. This implies that exploiting the relational structure across different groups does not help improving sample complexity when grouping information is not reliable. Furthermore, since the clustering information is reliable, clusters can be recovered from the similarity graph. However, further increments of $\IcOne$ and $\IcTwo$ do not yield further reduction in the sample complexity, and hence the sample complexity gain from these two quality parameters is saturated in this regime. \subsubsection{Clustering-Limited Regime} The optimal sample complexity reads \begin{align*} \frac{1}{\interTau} \left(1-\frac{\left(\sqrt{\alphaConst} - \sqrt{\gammaConst}\right)^2 + (g-1) \left(\sqrt{\betaConst} - \sqrt{\gammaConst}\right)^2}{gc} \right) n \log n &= \frac{1}{\interTau} \left(1-\frac{\IcOne + (g-1) \IcTwo}{gc} \right) n \log n, \end{align*} which is a decreasing function of $\IcOne$ and $\IcTwo$. This is the most challenging scenario which has not been explored by any prior works. Since the clustering information is not reliable, it is not possible to recover the groups and clusters from the similarity graph. Moreover, it should be noted that when $\beta = \gamma$, i.e., groups and clusters are indistinguishable, we have $\Ig = \IcOne$ and $\IcTwo = 0$. As a result, it boils down to a problem setting of $gc$ clusters, and hence the optimal sample complexity reads \begin{align*} \frac{1}{\interTau} \left(1-\frac{\left(\sqrt{\alphaConst} - \sqrt{\gammaConst}\right)^2}{gc} \right) n \log n &= \frac{1}{\interTau} \left(1-\frac{\Ig}{gc} \right) n \log n, \end{align*} Comparing to the optimal sample complexity expression for the grouping-limited regime, the only distinction appears in the denominator, in which $\intraTau$ is replaced with $\interTau$ due to the fact that $\interTau < \intraTau$. \begin{figure} \centering \subfloat[$\intraTau = \frac{1}{3}$ and $\interTau = \frac{1}{6}$.]{\includegraphics[width=0.45\textwidth]{3reg.pdf} \label{fig:3reg}} \hfil \subfloat[$\intraTau = \frac{1}{6}$ and $\interTau = \frac{1}{3}$.]{\includegraphics[width=0.45\textwidth]{2reg.pdf} \label{fig:2reg}} \caption{Let $(n,m,\theta,c,g,r,q)=(4000,500,0,10,5,3,5)$. (a) The different regimes of the optimal sample complexity reported in \eqref{eq:pstar-general} for $\intraTau > \interTau$. (b) The different regimes of the optimal sample complexity reported in \eqref{eq:pstar-general} for $\intraTau < \interTau$. For both sub-figures, diagonal stripes, dots, and horizontal stripes refer to perfect clustering/grouping regime, grouping-limited regime, and clustering-limited regime, respectively. } \label{fig:regions} \end{figure} Consider a problem setting where $n=4000$, $m=500$, $\theta=0$, $c=10$, $g=5$, $r=3$ and $q=5$. Fig.~\ref{fig:3reg} and Fig.~\ref{fig:2reg} depict the different regimes of the optimal sample complexity as a function of $(\Ig,\IcTwo)$. In Fig.~\ref{fig:3reg}, where $\intraTau = 1/3$ and $\interTau = 1/6$, the region depicted by diagonal stripes corresponds to perfect clustering/grouping regime and the first term in the RHS of \eqref{eq:pstar-general} is active. The graph quality parameters $\Ig$, $\IcTwo$, and consequently $\IcOne$ are large, and graph information is rich enough to perfectly retrieve the clusters and groups. The region depicted by dots corresponds to grouping-limited regime, where the second term in the RHS of \eqref{eq:pstar-general} is active. In this regime, graph information suffices to exactly recover the clusters, but we need to rely on rating observation to exactly recover the groups. Finally, the third term in the RHS of \eqref{eq:pstar-general} is active in the region captured by horizontal stripes. This indicates the clustering-limited regime, where neither clustering nor grouping is exact without the side information of the rating vectors. On the other hand, Fig.~\ref{fig:2reg} depicts the case where $\intraTau = 1/6$ and $\interTau = 1/3$. It is worth noting that in practically-relevant systems, we have $\intraTau < \interTau$, i.e., rating vectors of users in the same cluster are expected to be more similar than those in a different cluster. Therefore, the third regime, i.e., clustering-limited regime, vanishes in Fig.~\ref{fig:2reg}. \subsection{Benefit of Hierarchical Graph Structure} \begin{figure} \centering \includegraphics[width=0.5\textwidth]{comp.pdf} \caption{ Let $(n,m,\theta,c,g,r,q)=(4000,500,0,10,5,3,5)$. Comparison between the sample complexity reported in \eqref{eq:pstar-general} and that of \cite{yoon2018joint} for $\beta=5$, $\gamma = 1$, $\intraTau = 1/3$ and $\interTau = 1/6$. } \label{fig:baselineComp} \end{figure} Consider a problem setting where $n=4000$, $m=500$, $\theta=0$, $c=10$, $g=5$, $r=3$ and $q=5$. Fig.~\ref{fig:baselineComp} compares the optimal sample complexity, as a function of $\Ig$, between the one reported in~\eqref{eq:pstar-general} and that of \cite{yoon2018joint} for $\intraTau = 1/3$, $\interTau = 1/6$, $\beta = 5$ and $\gamma = 1$. It should be noted that \cite{yoon2018joint} leverages neither the hierarchical structure of the graph, nor the linear dependency among the rating vectors. Thus, the problem formulated in Section~\ref{subsec:probForm} will be translated to a graph that consists of $gc$ clusters whose rating vectors are linearly independent in the setting of \cite{yoon2018joint}. Also note that the minimum hamming distance for \cite{yoon2018joint} is $\interTau$. In Fig.~\ref{fig:baselineComp}, we can see that the noticeable gain in the sample complexity of our result in the diagonal parts of the plot (i.e., clustering-limited and grouping-limited regimes on the left side) is due to leveraging the hierarchical graph structure, while the improvement in the sample complexity in the flat part of the plot (i.e, perfect clustering/grouping regime) is a consequence of exploiting the relational structure (i.e., linear dependency) among the rating vectors within each cluster. \end{JA_AE} \section{The Achievability proof} \label{sec:achv} In this section, we prove the achievability part of Theorem~\ref{thm:p_star}, that is if the condition on $p$ in \eqref{eq:pstar-general_achv} holds, then there exists an estimator $\psi$ such that $\lim_{n \rightarrow \infty} P_e^{(\delta)}(\psi) = 0$. To this end, we prove that $\lim_{n \rightarrow \infty} P_e^{(\delta)}(\psi_{\text{ML}}) = 0$ where $\psi_{\text{ML}}$ is the maximum likelihood (ML) estimator, if all the following inequalities hold: \begin{align} \frac{g-r+1}{gc}n I_r &\geq (1+\epsilon) \log m, & & \textbf{(Perfect Clustering/Grouping Regime)} \label{eq:suffCond_1}\\ \intraTau m I_r + \frac{\Ig}{gc} \log n &\geq (1+\epsilon) \log n, & & \textbf{(Grouping-Limited Regime)} \label{eq:suffCond_2}\\ \interTau m I_r + \frac{\IcOne}{gc} \log n + \frac{(g-1) \IcTwo }{gc} \log n &\geq (1+\epsilon) \log n, & & \textbf{(Clustering-Limited Regime)} \label{eq:suffCond_3} \end{align} where \begin{align} I_r \coloneqq p \left(\sqrt{1-\theta} - \sqrt{\frac{\theta}{q-1}}\right)^2, \quad \Ig \coloneqq (\sqrt{\alphaConst} - \sqrt{\betaConst})^2, \quad \IcOne \coloneqq (\sqrt{\alphaConst} - \sqrt{\gammaConst})^2, \quad \IcTwo \coloneqq (\sqrt{\betaConst} - \sqrt{\gammaConst})^2. \label{eq:Ir_I_abg_defn} \end{align} Throughout the proof, let $p = \Theta ((\log n) / n)$, and let $q$ and $\theta$ be constants such that $q$ is prime and $\theta \in [0,1]$. We first present the structure of the ground truth rating matrix and the underlying linear MDS code structure in Section~\ref{sec:achv_groundTruth}. Next, we introduce a number of auxiliary lemmas in Section~\ref{sec:achv_auxLemma}. Finally, we present the achievability proof of Theorem~\ref{thm:p_star} in Section~\ref{sec:achv_proof_Thm1}. \subsection{The Structure of Ground Truth Rating Matrix} \label{sec:achv_groundTruth} Let the ground truth rating matrix be denoted by $\gtMat = (\mathcal{V}_0,\mathcal{Z}_0)$ where $\gtMat \in \matSet$, and \begin{align} \mathcal{V}_0 &= \left\{\vecU{i}{x}: x\in [c], i\in [g]\right\}, \qquad \mathcal{Z}_0 = \left\{\left\{Z_0(x,i)\right\}_{x \in [c],\: i \in [g]} \right\}, \end{align} where $\mathcal{Z}_0$ follows the conditions given in \eqref{eq:Z_defn}, but omitted for the sake of brevity. Let $\gtRatingCluster{x} \in \mathbb{F}_{q}^{g \times m}$ be a matrix obtained by stacking all the rating vectors of cluster $x$ given by $\{\vecU{i}{x}: i\in [g]\}$ for $x \in [c]$. Consequently, $\gtMat$ is an $n \times m$ matrix where its $r^{\text{th}}$ row equals to $\vecU{i}{x}$ if and only if $r \in Z_0(x,i)$. Furthermore, let the output of an estimator~$\psi$ (i.e., the completed rating matrix) be denoted by $X = (\mathcal{V}, \mathcal{Z})$ where $X \in \mathbb{F}_{q}^{n \times m}$, and \begin{align} \mathcal{V} &= \left\{\vecV{i}{x}: x\in [c], i\in [g]\right\}, \qquad \mathcal{Z} = \left\{\left\{Z(x,i)\right\}_{x \in [c],\: i \in [g]} \right\}, \end{align} where $\mathcal{Z}$ also follows similar conditions listed in \eqref{eq:Z_defn}. First, we construct a ground truth rating matrix $\gtMat$ that we are supposed to recover using the maximum likelihood estimator $\psi_{\text{ML}}$. Recall from Section~\ref{subsec:probForm} that the considered hierarchical graph consists of $c$ clusters, and each cluster comprises $g$ equal-sized groups. The set of $g$ rating vectors of cluster~$x$ is spanned by any subset of $r$ rating vectors for $x \in [c]$. Without loss of generality, assume that the set of users who belong to cluster~$x$ and group $i$ is given by $\{k + 1, k + 2, \ldots, k + \frac{n}{cg}\}$ for $x \in [c]$, $i \in [g]$ and $k = (x-1)\frac{n}{c} + (i-1)\frac{n}{cg}$. From the literature of error-correcting codes, a $(g,r)$ linear MDS code in $\mathbb{F}_q$ has a minimum distance of $g-r+1$, and hence reaches the Singleton bound \cite{macwilliams1977theory}. Furthermore, according to the MDS conjecture \cite{macwilliams1977theory}, \textcolor[rgb]{0,0,0}{there exists a $(g,r)$ MDS code in $\mathbb{F}_q$ if and only if $g \leq q+1$ for all $q$ and $2 \leq r \leq q-1$, except when $q$ is even and $r \in \{3, q-1\}$, in which case $g \leq q + 2$}. If these conditions are satisfied, then the existence of such an MDS code is guaranteed by the construction of Generalized Reed-Solomon codes \cite{macwilliams1977theory}. Consider a $(g,r)$ linear MDS code in $\mathbb{F}_q$ where $g$ is the length of the code and $r$ is its dimension. Let the set of $g$ ground truth rating vectors of the groups in cluster~$x$ be a $(g,r)$ MDS code. Hence, the set of $g$ rows of $\gtRatingCluster{x}$ spanned by any subset of $r$ rows of $\gtRatingCluster{x}$. Let $\iGenerator{x} \in \mathbb{F}_q^{g \times r}$ be a generator matrix of the $(g,r)$ MDS code, and $\iBasis{x} \in \mathbb{F}_q^{r \times m}$ be the basis matrix (with rank $r$), such that \begin{align} \gtRatingCluster{x} = \iGenerator{x} \iBasis{x},\: \text{ for } x \in [c]. \label{eq:mds_code} \end{align} Without loss of generality, we make the following assumptions: \begin{itemize} \item let the first row of $\gtRatingCluster{1}$ be given by $\gtRatingCluster{1}(1,:)= \mathbf{1}_{1 \times n}$; \item for $x \in [c]$, let $\iGenerator{x} = \Phi$ where $\Phi$ is a systematic generator matrix such that $\Phi = \left[I_{r \times r} \ A^\intercal \right]^\intercal$ and $A \in \mathbb{F}_{q}^{(g-r) \times r}$. This ensures that the first $r$ rows of $\iGenerator{x}$ are linearly independent, and hence the first $r$ rows of $\gtRatingCluster{x}$ are linearly independent by \eqref{eq:mds_code}. \end{itemize} Based on the aforementioned assumptions, the entries of each column of $\gtMat$ can take values from a set of $q^{cr-1}$ possible column vectors. This is due to the fact that the first row of $\gtMat$ is fixed to all-one vector, and the last $g-r$ rows of $\gtRatingCluster{x}$, for $x \in [c]$, can be constructed by linear combinations of its first $r$ rows. Hence, we have a total of $q^{cg-(1+c(g-r))} = q^{cr-1}$ different choices. Let the set of column of $\gtMat$ be partitioned into $q^{cr-1}$ sections, where the columns of each section correspond to one choice of the possible $q^{cr-1}$ vectors. Let the number of columns of each section be $\colBlockSize{\ell} m$, where $0 \leq \colBlockSize{\ell} \leq 1$ for $\ell \in \{0,1,\ldots,q-1\}^{cr-1}$ and $\sum_{\ell \in \{0,1,\ldots,q-1\}^{cr-1}} \colBlockSize{\ell} = 1$. Let $\colBlock{\ell}$ denote the $\ell^{\text{th}}$ column section of $\gtMat$, and hence $\colBlockSize{\ell} = \vert \colBlock{\ell} \vert / m$. Accordingly, let each row $\vecU{i}{x}$ of $\gtMat$ be partitioned into $q^{cr-1}$ sections, denoted\footnote{A similar interpretation goes for $\{\vecV{i}{x}(\ell): \ell\in \{0,1,\ldots,q-1\}^{cr-1}\}$.} by $\{\vecU{i}{x}(\ell): \ell\in \{0,1,\ldots,q-1\}^{cr-1}\}$, for $x \in [c]$ and $i \in [g]$. \textcolor[rgb]{0,0,0}{We assume that the MDS code structure is assumed to be known a priori, and hence the output matrix follows the MDS code structure imposed on the construction of $\gtMat$.} In the following example, we give an illustrative description of the proposed construction of the ground truth rating matrix $\gtMat$. \subsubsection{Illustrative Example} Consider the setting of $(c,g,r,q) = (2,3,2,2)$. Under this setting, the generator matrix and the basis matrix of each cluster are given by \begin{align} \iGenerator{1} &= \iGenerator{2} = \Phi = \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{bmatrix}, \nonumber\\ \iBasis{1} &= \begin{bmatrix} \begin{array}{c|c|c|c|c|c|c|c} \mathbf{1}_{1\times \colBlockSize{000} m} & \mathbf{1}_{1\times \colBlockSize{001} m} & \mathbf{1}_{1\times \colBlockSize{010} m} & \mathbf{1}_{1\times \colBlockSize{011} m} & \mathbf{1}_{1\times \colBlockSize{100} m} & \mathbf{1}_{1\times \colBlockSize{101} m} & \mathbf{1}_{1\times \colBlockSize{110} m} & \mathbf{1}_{1\times \colBlockSize{111} m}\\ \hline \mathbf{0}_{1\times \colBlockSize{000} m} & \mathbf{0}_{1\times \colBlockSize{001} m} & \mathbf{0}_{1\times \colBlockSize{010} m} & \mathbf{0}_{1\times \colBlockSize{011} m} & \mathbf{1}_{1\times \colBlockSize{100} m} & \mathbf{1}_{1\times \colBlockSize{101} m} & \mathbf{1}_{1\times \colBlockSize{110} m} & \mathbf{1}_{1\times \colBlockSize{111} m} \end{array} \end{bmatrix}, \nonumber\\ \iBasis{2} &= \begin{bmatrix} \begin{array}{c|c|c|c|c|c|c|c} \mathbf{0}_{1\times \colBlockSize{000} m} & \mathbf{0}_{1\times \colBlockSize{001} m} & \mathbf{1}_{1\times \colBlockSize{010} m} & \mathbf{1}_{1\times \colBlockSize{011} m} & \mathbf{0}_{1\times \colBlockSize{100} m} & \mathbf{0}_{1\times \colBlockSize{101} m} & \mathbf{1}_{1\times \colBlockSize{110} m} & \mathbf{1}_{1\times \colBlockSize{111} m}\\ \hline \mathbf{0}_{1\times \colBlockSize{000} m} & \mathbf{1}_{1\times \colBlockSize{001} m} & \mathbf{0}_{1\times \colBlockSize{010} m} & \mathbf{1}_{1\times \colBlockSize{011} m} & \mathbf{0}_{1\times \colBlockSize{100} m} & \mathbf{1}_{1\times \colBlockSize{101} m} & \mathbf{0}_{1\times \colBlockSize{110} m} & \mathbf{1}_{1\times \colBlockSize{111} m} \end{array} \end{bmatrix}, \end{align} where $0 \leq \colBlockSize{\ell} \leq 1$ for $\ell \in \{0,1\}^3$, and $\sum_{\ell \in \{0,1\}^3} \colBlockSize{\ell} = 1$. Therefore, from \eqref{eq:mds_code}, we have \begin{align} \gtRatingCluster{1} &= \iGenerator{1} \iBasis{1} = \begin{bmatrix} \begin{array}{c|c|c|c|c|c|c|c} \mathbf{1}_{1\times \colBlockSize{000} m} & \mathbf{1}_{1\times \colBlockSize{001} m} & \mathbf{1}_{1\times \colBlockSize{010} m} & \mathbf{1}_{1\times \colBlockSize{011} m} & \mathbf{1}_{1\times \colBlockSize{100} m} & \mathbf{1}_{1\times \colBlockSize{101} m} & \mathbf{1}_{1\times \colBlockSize{110} m} & \mathbf{1}_{1\times \colBlockSize{111} m}\\ \hline \mathbf{0}_{1\times \colBlockSize{000} m} & \mathbf{0}_{1\times \colBlockSize{001} m} & \mathbf{0}_{1\times \colBlockSize{010} m} & \mathbf{0}_{1\times \colBlockSize{011} m} & \mathbf{1}_{1\times \colBlockSize{100} m} & \mathbf{1}_{1\times \colBlockSize{101} m} & \mathbf{1}_{1\times \colBlockSize{110} m} & \mathbf{1}_{1\times \colBlockSize{111} m}\\ \hline \mathbf{1}_{1\times \colBlockSize{000} m} & \mathbf{1}_{1\times \colBlockSize{001} m} & \mathbf{1}_{1\times \colBlockSize{010} m} & \mathbf{1}_{1\times \colBlockSize{011} m} & \mathbf{0}_{1\times \colBlockSize{100} m} & \mathbf{0}_{1\times \colBlockSize{101} m} & \mathbf{0}_{1\times \colBlockSize{110} m} & \mathbf{0}_{1\times \colBlockSize{111} m}\\ \end{array} \end{bmatrix}, \nonumber\\ \gtRatingCluster{2} &= \iGenerator{2} \iBasis{2} = \begin{bmatrix} \begin{array}{c|c|c|c|c|c|c|c} \mathbf{0}_{1\times \colBlockSize{000} m} & \mathbf{0}_{1\times \colBlockSize{001} m} & \mathbf{1}_{1\times \colBlockSize{010} m} & \mathbf{1}_{1\times \colBlockSize{011} m} & \mathbf{0}_{1\times \colBlockSize{100} m} & \mathbf{0}_{1\times \colBlockSize{101} m} & \mathbf{1}_{1\times \colBlockSize{110} m} & \mathbf{1}_{1\times \colBlockSize{111} m}\\ \hline \mathbf{0}_{1\times \colBlockSize{000} m} & \mathbf{1}_{1\times \colBlockSize{001} m} & \mathbf{0}_{1\times \colBlockSize{010} m} & \mathbf{1}_{1\times \colBlockSize{011} m} & \mathbf{0}_{1\times \colBlockSize{100} m} & \mathbf{1}_{1\times \colBlockSize{101} m} & \mathbf{0}_{1\times \colBlockSize{110} m} & \mathbf{1}_{1\times \colBlockSize{111} m}\\ \hline \mathbf{0}_{1\times \colBlockSize{000} m} & \mathbf{1}_{1\times \colBlockSize{001} m} & \mathbf{1}_{1\times \colBlockSize{010} m} & \mathbf{0}_{1\times \colBlockSize{011} m} & \mathbf{0}_{1\times \colBlockSize{100} m} & \mathbf{1}_{1\times \colBlockSize{101} m} & \mathbf{1}_{1\times \colBlockSize{110} m} & \mathbf{0}_{1\times \colBlockSize{111} m} \end{array} \end{bmatrix}. \end{align} Consequently, $\gtMat$ is given by \begin{align} \label{eq_M0} \gtMat = \begin{bmatrix} \begin{array}{c|c|c|c|c|c|c|c} \mathbf{1}_{\frac{n}{6}\times \colBlockSize{000} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{001} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{010} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{011} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{100} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{101} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{110} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{111} m}\\ \hline \mathbf{0}_{\frac{n}{6}\times \colBlockSize{000} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{001} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{010} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{011} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{100} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{101} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{110} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{111} m}\\ \hline \mathbf{1}_{\frac{n}{6}\times \colBlockSize{000} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{001} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{010} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{011} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{100} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{101} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{110} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{111} m}\\ \hline \mathbf{0}_{\frac{n}{6}\times \colBlockSize{000} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{001} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{010} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{011} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{100} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{101} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{110} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{111} m}\\ \hline \mathbf{0}_{\frac{n}{6}\times \colBlockSize{000} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{001} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{010} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{011} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{100} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{101} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{110} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{111} m}\\ \hline \mathbf{0}_{\frac{n}{6}\times \colBlockSize{000} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{001} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{010} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{011} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{100} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{101} m} & \mathbf{1}_{\frac{n}{6}\times \colBlockSize{110} m} & \mathbf{0}_{\frac{n}{6}\times \colBlockSize{111} m} \end{array} \end{bmatrix}, \end{align} which is the same construction of $\gtMat$ provided in \cite{elmahdy2020matrix} for the special case of $(c,g,r,q) = (2,3,2,2)$. \hfill$\blacklozenge$ \subsection{The Auxiliary Lemmas} \label{sec:achv_auxLemma} We present six auxiliary lemmas that are used to prove the achievability part of Theorem~\ref{thm:p_star}. Before each lemma, we introduce the terminologies and notations needed for the statement of the lemma. Let $\mathsf{L}(X)$ denotes\footnote{With a slight abuse of notation, we omit the dependence on $(Y,G)$ in the likelihood function for notational compactness.} the negative log-likelihood of a candidate rating matrix $X=(\mathcal{V},\mathcal{Z})$ given a fixed input pair $(Y,\mathcal{G})$. More formally, we have \begin{align} \mathsf{L}(X) = \left\{ \begin{array}{cl} - \log \mathbb{P}\left[(Y,\mathcal{G}) \;|\; \mathbf{X} = X \right] & \textrm{if $X \in \matSet$}, \vspace{0.5mm}\\ \infty & \textrm{otherwise}. \end{array} \right. \label{eq:likelihood_defn} \end{align} We show that the likelihood expression hinges on two factors: (i) the difference between the estimated ratings (entries of $X$) and the observed ratings (elements of $Y$); and (ii) the dissimilarity between the graph induced by the partitioning in $\mathcal{Z}$ and the observed graph $\mathcal{G}$. As defined in Section~\ref{subsec:notation}, we denote by $\Lambda(X,Y)$ the number of mismatched entries between $X$ and $Y$. For a user partitioning $\mathcal{Z}$, let $\userPairSet{\alpha}{\mathcal{Z}}$ denote the set of pairs of users within any group; $\userPairSet{\beta}{\mathcal{Z}}$ denote the set of pairs of users in different groups within any cluster; and $\userPairSet{\gamma}{\mathcal{Z}}$ denote the set of pairs of users in different clusters. Formally, we have \begin{align} \begin{split} \userPairSet{\alpha}{\mathcal{Z}} &= \left\{ (a,b) : a \in Z(x,i), \: b \in Z(x,i), \mbox{ for } x \in [c], \: i \in [g] \right\}, \\ \userPairSet{\beta}{\mathcal{Z}} &= \left\{ (a,b) : a \in Z(x,i), \: b \in Z(x,j), \: \mbox{ for } x \in [c],\: i, j \in [g],\: i\neq j \right\}, \\ \userPairSet{\gamma}{\mathcal{Z}} &= \left\{ (a,b) : a \in Z(x,i), \: b \in Z(y,j), \: \mbox{ for } x,y \in [c],\: x \neq y, \: i, j \in [g] \right\}. \end{split} \end{align} Recall from Section~\ref{subsec:probForm} that the user partitioning induced by any rating matrix in $\matSet$ should satisfy the property that all groups have equal size of $n/(cg)$ users. This implies that the sizes of $\userPairSet{\alpha}{\mathcal{Z}}$, $\userPairSet{\beta}{\mathcal{Z}}$ and $\userPairSet{\gamma}{\mathcal{Z}}$ are constants and given by \begin{align} \vert \userPairSet{\alpha}{\mathcal{Z}} \vert = gc \binom{n/(gc)}{2}, \qquad \vert \userPairSet{\beta}{\mathcal{Z}} \vert = c \binom{g}{2} \left(n/(gc)\right)^2, \qquad \vert \userPairSet{\gamma}{\mathcal{Z}} \vert = \binom{c}{2} \left(n/c\right)^2, \end{align} for any user partitioning. Furthermore, for a graph $\mathcal{G}$ and a user partitioning $\mathcal{Z}$, define $\numEdge{\alpha}{\mathcal{G}}{\mathcal{Z}}$ as the number of edges within any group; $\numEdge{\beta}{\mathcal{G}}{\mathcal{Z}}$ as the number of edges across groups within any cluster; and $\numEdge{\gamma}{\mathcal{G}}{\mathcal{Z}}$ as the number of edges across clusters. More formally, we have \begin{align} \numEdge{\mu}{\mathcal{G}}{\mathcal{Z}} &= \sum_{(a,b) \in \userPairSet{\mu}{\mathcal{Z}}} \indicatorFn{(a,b) \in \mathcal{E}}, \label{eq:e_mu} \end{align} for $\mu \in \{\alphaEdge,\betaEdge,\gammaEdge\}$. The following lemma gives a precise expression of $\mathsf{L}(X)$. \begin{lemma} For a given fixed input pair $(Y,\mathcal{G})$ and any $X \in \matSet$, we have \begin{align} \mathsf{L}(X) = \log \left((q-1) \frac{1-\theta}{\theta}\right) \numDiffElmnt{Y}{X} + \sum\limits_{\mu\in\left\{\alphaEdge,\betaEdge,\gammaEdge\right\}} \left( \log \left(\frac{1-\mu}{\mu}\right) \numEdge{\mu}{\mathcal{G}}{\mathcal{Z}} - \log(1-\mu) \left\vert \userPairSet{\mu}{\mathcal{Z}} \right\vert \right), \label{eq:neg_log_likelihood} \end{align} where $\alphaEdge$, $\betaEdge$ and $\gammaEdge$ are the edge probabilities defined in \eqref{eq:edge_prob_defn}. \label{lm:neg_log_likelihood} \end{lemma} \begin{IEEEproof} We refer to Appendix~\ref{app:neg_log_likelihood} for the proof of Lemma~\ref{lm:neg_log_likelihood}. \end{IEEEproof} The following lemma provides an upper bound on the worst-case probability of error $P_e^{(\delta)}(\psi_{\text{ML}})$. \begin{lemma} \label{lm:upp_worst_case_err_prob} For the maximum likelihood estimator $\psi_{\text{ML}}$, we have \begin{align} \label{ineq:upp_worst_case_err_prob} P_e^{(\delta)}(\psi_{\text{ML}}) \leq \sum_{X \neq \gtMat} \mathbb{P}\left[\mathsf{L}(\gtMat) \geq \mathsf{L}(X)\right]. \end{align} \end{lemma} \begin{IEEEproof} We refer to Appendix~\ref{app:upp_worst_case_err_prob} for the proof of Lemma~\ref{lm:upp_worst_case_err_prob}. \end{IEEEproof} For a ground truth rating matrix $\gtMat = (\mathcal{V}_0,\mathcal{Z}_0)$; a candidate rating matrix $X = (\mathcal{V}, \mathcal{Z})$; and a tuple $T \in \tupleSetDelta$, define the following disjoint sets: \begin{itemize \item define $\diffEntriesSet = \diffEntriesSet(\gtMat, X)$ as the set of matrix entries where $X \neq \gtMat$. Formally, we have \begin{align} \diffEntriesSet = \left\{(r,t)\in [n] \times [m]: X(r,t) \neq \gtMat(r,t)\right\}; \label{eq:N1_defn} \end{align} \item define $\misClassfSet{\betaEdge}{\alphaEdge} = \misClassfSet{\betaEdge}{\alphaEdge}(\mathcal{Z}_0, \mathcal{Z})$ as the set of pairs of users where the two users of each pair belong to different groups of the same cluster in $\gtMat$ (and therefore they are connected with probability $\betaEdge$), but they are estimated to be in the same group in $X$ (and hence, given the estimator output, the belief for the existence of an edge between these two users is $\alphaEdge$). Formally, we have \begin{align} \misClassfSet{\betaEdge}{\alphaEdge} = \left\{ (a,b): a \in Z_0(x,i_1) \cap Z(y,j),\: b \in Z_0(x,i_2) \cap Z(y,j), \mbox{ for } x, y \in [c],\: i_1, i_2, j \in [g],\: i_1 \neq i_2 \right\}. \label{eq:N2rev_defn} \end{align} On the other hand, define $\misClassfSet{\alphaEdge}{\betaEdge} = \misClassfSet{\alphaEdge}{\betaEdge} (\mathcal{Z}_0, \mathcal{Z})$ as \begin{align} \misClassfSet{\alphaEdge}{\betaEdge} = \left\{ (a,b): a \in Z_0(x,i) \cap Z(y,j_1),\: b \in Z_0(x,i) \cap Z(y,j_2), \mbox{ for } x, y \in [c],\: i, j_1, j_2 \in [g],\: j_1 \neq j_2 \right\}; \label{eq:N2_defn} \end{align} \item define $\misClassfSet{\gammaEdge}{\alphaEdge} = \misClassfSet{\gammaEdge}{\alphaEdge}(\mathcal{Z}_0, \mathcal{Z})$ as the set of pairs of users where the two users of each pair belong to different clusters in $\gtMat$ (and therefore they are connected with probability $\gammaEdge$), but they are estimated to be in the same group in $X$ (and hence, given the estimator output, the belief for the existence of an edge between these two users is $\alphaEdge$). Formally, we have \begin{align} \misClassfSet{\gammaEdge}{\alphaEdge} = \left\{ (a,b) : a \in Z_0(x_1,i_1) \cap Z(y,j),\: b \in Z_0(x_2,i_2) \cap Z(y,j), \mbox{ for } x_1, x_2, y \in [c],\: x_1 \neq x_2,\: i_1, i_2, j \in [g] \right\}. \label{eq:N3rev_defn} \end{align} On the other hand, define $\misClassfSet{\alphaEdge}{\gammaEdge} = \misClassfSet{\alphaEdge}{\gammaEdge}(\mathcal{Z}_0, \mathcal{Z})$ as \begin{align} \misClassfSet{\alphaEdge}{\gammaEdge} = \left\{ (a,b) : a \in Z_0(x,i) \cap Z(y_1,j_1),\: b \in Z_0(x,i) \cap Z(y_2, j_2), \mbox{ for } x, y_1, y_2 \in [c],\: y_1 \neq y_2,\: i, j_1, j_2 \in [g] \right\}; \label{eq:N3_defn} \end{align} \item define $\misClassfSet{\gammaEdge}{\betaEdge} = \misClassfSet{\gammaEdge}{\betaEdge}(\mathcal{Z}_0, \mathcal{Z})$ as the set of pairs of users where the two users of each pair belong to different clusters in $\gtMat$ (and therefore they are connected with probability $\gammaEdge$), but they are estimated to be in different groups of the same cluster in $X$ (and hence, given the estimator output, the belief for the existence of an edge between these two users is $\betaEdge$). Formally, we have \begin{align} \misClassfSet{\gammaEdge}{\betaEdge} &\!=\! \left\{ (a,b) \!: a \!\in\! Z_0(x_1,i_1) \!\cap\! Z(y,j_1),\: b \!\in\! Z_0(x_2,i_2) \!\cap\! Z(y,j_2), \!\mbox{ for } x_1, x_2, y \!\in\! [c],\: x_1 \!\neq\! x_2, \: i_1, i_2, j_1, j_2 \!\in\! [g],\: j_1 \!\neq\! j_2 \right\}\!. \label{eq:N4rev_defn} \end{align} On the other hand, define $\misClassfSet{\betaEdge}{\gammaEdge} = \misClassfSet{\betaEdge}{\gammaEdge}(\mathcal{Z}_0, \mathcal{Z})$ as \begin{align} \misClassfSet{\betaEdge}{\gammaEdge} &\!=\! \left\{ (a,b) \!: a \!\in\! Z_0(x,i_1) \!\cap\! Z(y_1,j_1),\: b \!\in\! Z_0(x, i_2) \!\cap\! Z(y_2, j_2), \!\mbox{ for } x, y_1, y_2 \!\in\! [c],\: y_1 \!\neq\! y_2, \: i_1, i_2, j_1, j_2 \!\in\! [g],\: i_1 \!\neq\! i_2 \right\}\!. \label{eq:N4_defn} \end{align} \end{itemize} Let $\mathsf{B}_i^{(\sigma)}$ denote the $i^{\text{th}}$~Bernoulli random variable with parameter $\sigma \in \{p, \theta, \frac{1}{q-1}, \alphaEdge, \betaEdge, \gammaEdge\}$. Define the following sets of independent Bernoulli random variables: \begin{align} \left\{\mathsf{B}_i^{(p)}: i\in\diffEntriesSet\right\}, \: \left\{\mathsf{B}_i^{(\theta)}:i \in \diffEntriesSet \right\}, \: \left\{\mathsf{B}_i^{\left(\frac{1}{q-1}\right)}: i\in\diffEntriesSet\right\}, \: \left\{ \mathsf{B}_i^{(\mu)}: i\in \misClassfSet{\mu}{\nu},\: \mu, \nu \in \left\{\alphaEdge,\betaEdge,\gammaEdge \right\}, \: \mu \neq \nu \right\}. \label{eq:bern_sets} \end{align} Now, define $\mathbf{B} = \mathbf{B} \left(\diffEntriesSet, \{\misClassfSet{\mu}{\nu} : \mu, \nu \in \{\alphaEdge,\betaEdge,\gammaEdge \}, \: \mu \neq \nu\}\right)$ as \begin{align} \mathbf{B} &\coloneqq \log\left((q-1)\frac{1-\theta}{\theta}\right) \sum_{i \in \diffEntriesSet} \mathsf{B}_i^{(p)} \left(\left(1+\mathsf{B}_i^{\left(\frac{1}{q-1}\right)}\right)\mathsf{B}_i^{(\theta)} - 1\right) \nonumber\\ &\phantom{=} + \left(\log\frac{(1-\betaEdge)\alphaEdge}{(1-\alphaEdge)\betaEdge}\right) \left( \sum\limits_{i \in \misClassfSet{\betaEdge}{\alphaEdge}} \mathsf{B}_i^{(\betaEdge)} - \sum\limits_{i \in \misClassfSet{\alphaEdge}{\betaEdge}} \mathsf{B}_i^{(\alphaEdge)} \right) + \left(\log\frac{1-\alphaEdge}{1-\betaEdge}\right) \left( \left\vert \misClassfSet{\betaEdge}{\alphaEdge}\right\vert - \left\vert \misClassfSet{\alphaEdge}{\betaEdge}\right\vert \right) \nonumber\\ &\phantom{=} + \left(\log\frac{(1-\gammaEdge)\alphaEdge}{(1-\alphaEdge)\gammaEdge}\right) \left( \sum\limits_{i \in \misClassfSet{\gammaEdge}{\alphaEdge}} \mathsf{B}_i^{(\gammaEdge)} - \sum\limits_{i \in \misClassfSet{\alphaEdge}{\gammaEdge}} \mathsf{B}_i^{(\alphaEdge)} \right) + \left(\log\frac{1-\alphaEdge}{1-\gammaEdge}\right) \left( \left\vert \misClassfSet{\gammaEdge}{\alphaEdge}\right\vert - \left\vert \misClassfSet{\alphaEdge}{\gammaEdge}\right\vert \right) \nonumber\\ &\phantom{=} + \left(\log\frac{(1-\gammaEdge)\betaEdge}{(1-\betaEdge)\gammaEdge}\right) \left( \sum\limits_{i \in \misClassfSet{\gammaEdge}{\betaEdge}} \mathsf{B}_i^{(\gammaEdge)} - \sum\limits_{i \in \misClassfSet{\betaEdge}{\gammaEdge}} \mathsf{B}_i^{(\betaEdge)} \right) + \left(\log\frac{1-\betaEdge}{1-\gammaEdge}\right) \left( \left\vert \misClassfSet{\gammaEdge}{\betaEdge}\right\vert - \left\vert \misClassfSet{\betaEdge}{\gammaEdge}\right\vert \right). \label{eq:B_middle} \end{align} In the following lemma, we write each summand in \eqref{ineq:upp_worst_case_err_prob} in terms of \eqref{eq:B_middle}. \begin{lemma} \label{lemma:neg_lik_M0_XT} For any $X \in \mathcal{X}(T)$ and $T \in \tupleSetDelta$, we have \begin{align} \mathbb{P}\left[\mathsf{L}\left(\gtMat\right) \geq \mathsf{L}(X)\right] = \mathbb{P} \left[\mathbf{B} \geq 0 \right]. \label{eq:lemma3} \end{align} \end{lemma} \begin{IEEEproof} We refer to Appendix~\ref{proof:neg_lik_M0_XT} for the proof of Lemma~\ref{lemma:neg_lik_M0_XT}. \end{IEEEproof} The following lemma provides an upper bound of the RHS of \eqref{eq:lemma3}. \begin{lemma} \label{lemma:upper_bound_B} For any $\{\misClassfSet{\mu}{\nu} : \mu, \nu \in \{\alphaEdge,\betaEdge,\gammaEdge \}, \: \mu \neq \nu\}$, we have \begin{align} &\mathbb{P} \left[ \mathbf{B} \geq 0 \right] \leq \exp\left(-\left(1+o(1)\right) \left(\lvert\diffEntriesSet\rvert I_r + \Pleftrightarrow{\alphaEdge}{\betaEdge} \: \Ig \frac{\log n}{n} + \Pleftrightarrow{\alphaEdge}{\gammaEdge} \:\IcOne \frac{\log n}{n} + \Pleftrightarrow{\betaEdge}{\gammaEdge} \: \IcTwo \frac{\log n}{n} \right)\right), \label{eq:lemma1_2} \end{align} where \begin{align} \Pleftrightarrow{\alphaEdge}{\betaEdge} = \frac{\left\vert \misClassfSet{\betaEdge}{\alphaEdge} \right\vert + \left\vert \misClassfSet{\alphaEdge}{\betaEdge} \right\vert}{2}, \qquad \Pleftrightarrow{\alphaEdge}{\gammaEdge} = \frac{\left\vert \misClassfSet{\gammaEdge}{\alphaEdge} \right\vert + \left\vert \misClassfSet{\alphaEdge}{\gammaEdge} \right\vert}{2}, \qquad \Pleftrightarrow{\betaEdge}{\gammaEdge} = \frac{\left\vert \misClassfSet{\gammaEdge}{\betaEdge} \right\vert + \left\vert \misClassfSet{\betaEdge}{\gammaEdge} \right\vert}{2}. \label{eq:Pleftrightarrow_defn} \end{align} \end{lemma} \begin{IEEEproof} We refer to Appendix~\ref{proof:upper_bound_B} for the proof of Lemma~\ref{lemma:upper_bound_B}. \end{IEEEproof} We show that the interested error event $\{ \mathsf{L}(\gtMat) \geq \mathsf{L}(X) : X \neq \gtMat \}$ in \eqref{ineq:upp_worst_case_err_prob} depends solely on two sets of key parameters which dictate the relationship between $X$ and $\gtMat$: \begin{enumerate \item the first set includes counters to identify the number of users in cluster $x$ and group $i$ whose rating vector $\vecU{i}{x}$ in $\gtMat$ is changed to the rating vector $\vecV{j}{y}$ of users in cluster $y$ and group $j$ in $X$, for $x,y \in [c]$ and $i,j \in [g]$. Formally, we define \begin{align} \kUsrs{i}{j}{x}{y} = \left\vert \left\{ r : r \in Z_0(x,i) \cap Z(y,j) \right\}\right\vert, \:\text{ where }\: 0 \leq \kUsrs{i}{j}{x}{y} \leq \frac{n}{gc}; \label{eq:kUsrs_defn} \end{align} \item the second set provides the Hamming distance between $\vecU{i}{x}$ and $\vecV{i}{x}$, for $x \in [c]$ and $i \in [g]$. Formally, we define \begin{align} \dElmntsGen{i}{j}{x}{y} = \hamDist{\vecU{i}{x}}{\vecV{j}{y}}, \:\text{ where }\: 0 \leq \dElmntsGen{i}{j}{x}{y} \leq m. \label{eq:dElmntsGen_defn} \end{align} \end{enumerate} Based on these two parameters, the set of rating matrices $\matSet$ is partitioned into a number of classes of matrices $\mathcal{X}(T)$. Here, each matrix class $\mathcal{X}(T)$ is defined as the set of rating matrices that is characterized by a tuple~$T$ where \begin{align} T = \left( \left\{\kUsrs{i}{j}{x}{y}\right\}_{x,y \in [c], \: i,j \in [g]}, \left\{\dElmntsGen{i}{j}{x}{y}\right\}_{x,y \in [c], \: i,j \in [g]} \right). \label{eq:tuple_ratMat} \end{align} Define $\tupleSetDelta$ as the set of all non-all-zero tuples $T$. Therefore, we can write $\matSet = \bigcup_{T \in \tupleSetDelta} \mathcal{X}(T)$. \begin{JA_AE} Next, we analyze the performance of the ML decoder by comparing the ground truth user partitioning with that of the decoder. For a non-negative constant $\relabelConst \in (0,\: (\epsilon\log m - (2+\epsilon)\log(2q)) / (2 (1 + \epsilon)\log m))$, where $\epsilon > \max\{(2 \log 2) / \log n, \: (2(g-r+1) \log 2) / \log (2qm), \: (2\log(2q))/\log(m/2q)\}$, define $\sigma(x,i)$ as the set of pairs of cluster and group in $\mathcal{Z}$ whose number of overlapped users with $\mathcal{Z}_0(x,i)$ exceeds a $(1-\tau)$ fraction of the group size. Formally, we have \begin{align} \sigma(x,i) = \left\{(y,j)\in[c]\times[g]: \left| Z_0(x,i) \cap Z(y,j)\right| \geq (1-\relabelConst) \frac{n}{gc} \right\}. \label{eq:sigma(x,i)} \end{align} Note that $\relabelConst < 0.5$, which implies that $|\sigma(x,i)| \leq 1$ since the size of any group is $n/(gc)$ users. For $|\sigma(x,i)| = 1$, let $\sigma(x,i) = \{(\sigma(x), \sigma(i|x))\}$. Accordingly, partition the set $\tupleSetDelta$ into two subsets $\TsmallErr$ and $\TlargeErr$ that are defined as follows: \begin{align} \TsmallErr &= \left\{ T \in \mathcal{T}^{(\delta)} : \forall (x,i) \in [c]\times [g] \text{ such that } \left\vert \sigma(x,i) \right\vert = 1, \: \dElmntsGen{i}{\:\sigma(i|x)}{x}{\:\sigma(x)} \leq \tau m \min\{\interTau, \intraTau\} \right\}, \label{eq:TsmallErr}\\ \TlargeErr &= \left\{ T \in \mathcal{T}^{(\delta)} : \exists (x,i) \in [c]\times [g] \text{ such that } \left(\left\vert \sigma(x,i) \right\vert = 0\right) \right\} \nonumber\\ &\phantom{=}\cup \left\{ T \in \mathcal{T}^{(\delta)} : \forall (x,i) \in [c] \times [g] \text{ such that } \left\vert \sigma(x,i) \right\vert = 1,\: \exists (x,i) \in [c] \times [g] \text{ such that } \dElmntsGen{i}{\:\sigma(i|x)}{x}{\:\sigma(x)} > \tau m \min\{\interTau, \intraTau\} \right\}. \label{eq:TlargeErr} \end{align} Intuitively, when $T \in \TsmallErr$, the class of matrices $\mathcal{X}(T)$ corresponds to the typical (i.e., small) error set. On the other hand, when $T \in \TlargeErr$, the class of matrices $\mathcal{X}(T)$ corresponds to the atypical (i.e., large) error set that has negligible probability mass. The following two lemmas provide an upper bound on the RHS of \eqref{eq:lemma1_2} under different classes of candidate rating matrices, and evaluating the limits as $n$ and $m$ tend to infinity. \begin{lemma} \label{lemma:T1_related} For any $\{\misClassfSet{\mu}{\nu} : \mu, \nu \in \{\alphaEdge,\betaEdge,\gammaEdge \}, \: \mu \neq \nu\}$, we have\footnote{As $n$ tends to infinity, $m$ also tends to infinity since $m = \omega(\log n)$.} \begin{align} & \lim_{n,m\rightarrow \infty} \sum\limits_{T \in \TsmallErr} \sum\limits_{X \in \mathcal{X}(T)} \exp\left(-\left(1+o(1)\right) \left(\lvert\diffEntriesSet\rvert I_r + \Pleftrightarrow{\alphaEdge}{\betaEdge} \: \Ig \frac{\log n}{n} + \Pleftrightarrow{\alphaEdge}{\gammaEdge} \: \IcOne \frac{\log n}{n} + \Pleftrightarrow{\betaEdge}{\gammaEdge} \: \IcTwo \frac{\log n}{n} \right)\right) = 0. \label{eq:lemma_T1_1} \end{align} \end{lemma} \begin{IEEEproof} We refer to Appendix~\ref{proof:T1_related} for the proof of Lemma~\ref{lemma:T1_related}. \end{IEEEproof} \begin{lemma} \label{lemma:eta_omega(nm)} For any $\{\misClassfSet{\mu}{\nu} : \mu, \nu \in \{\alphaEdge,\betaEdge,\gammaEdge \}, \: \mu \neq \nu\}$, we have \begin{align} & \lim_{n,m\rightarrow \infty } \sum\limits_{T \in \TlargeErr} \sum\limits_{X \in \mathcal{X}(T)} \exp\left(-\left(1+o(1)\right) \left(\lvert\diffEntriesSet\rvert I_r + \Pleftrightarrow{\alphaEdge}{\betaEdge} \: \Ig \frac{\log n}{n} + \Pleftrightarrow{\alphaEdge}{\gammaEdge} \: \IcOne \frac{\log n}{n} + \Pleftrightarrow{\betaEdge}{\gammaEdge} \: \IcTwo \frac{\log n}{n} \right)\right) = 0. \label{ineq:eta_omega(nm)} \end{align} \end{lemma} \begin{IEEEproof} We refer to Appendix~\ref{proof:eta_omega(nm)} for the proof of Lemma~\ref{lemma:eta_omega(nm)}. \end{IEEEproof} \end{JA_AE} \subsection{The Achievability Proof of Theorem~\ref{thm:p_star}} \label{sec:achv_proof_Thm1} The worst-case probability of error $P_e^{(\delta)}(\psi_{\text{ML}})$ is upper bounded by \begin{align} &P_e^{(\delta)}(\psi_{\text{ML}}) \nonumber\\ &\!\leq\! \sum_{X \neq \gtMat} \mathbb{P}\left[\mathsf{L}(\gtMat) \geq \mathsf{L}(X)\right] \label{eq:matrix_enumerate_neg1}\\ &\!=\! \sum_{\substack{X \neq \gtMat, \\ X \in \matSet}} \mathbb{P}\left[\mathsf{L}(\gtMat) \geq \mathsf{L}(X)\right] \label{eq:matrix_enumerate_0}\\ &\!=\! \sum\limits_{T \in \tupleSetDelta} \sum\limits_{X \in \mathcal{X}(T)} \mathbb{P}\left[\mathsf{L}(\gtMat) \geq \mathsf{L}(X)\right] \label{eq:matrix_enumerate}\\ &\!\leq\! \sum\limits_{T \in \tupleSetDelta} \sum\limits_{X \in \mathcal{X}(T)} \exp\left(-\left(1\!+\!o(1)\right) \left(\lvert\diffEntriesSet\rvert I_r + \Pleftrightarrow{\alphaEdge}{\betaEdge} \: \Ig \frac{\log n}{n} + \Pleftrightarrow{\alphaEdge}{\gammaEdge} \: \IcOne \frac{\log n}{n} + \Pleftrightarrow{\betaEdge}{\gammaEdge} \: \IcTwo \frac{\log n}{n} \right)\right) \label{ineq:upper_bound_M0_XT}\\ &\!=\! \sum\limits_{T \in \TsmallErr} \sum\limits_{X \in \mathcal{X}(T)} \exp\left(-\left(1\!+\!o(1)\right) \left(\lvert\diffEntriesSet\rvert I_r + \Pleftrightarrow{\alphaEdge}{\betaEdge} \: \Ig \frac{\log n}{n} + \Pleftrightarrow{\alphaEdge}{\gammaEdge} \: \IcOne \frac{\log n}{n} + \Pleftrightarrow{\betaEdge}{\gammaEdge} \: \IcTwo \frac{\log n}{n} \right)\right) \label{partial_sum}\\ &\phantom{\leq} + \sum\limits_{T \in \TlargeErr} \sum\limits_{X \in \mathcal{X}(T)} \exp\left(-\left(1+o(1)\right) \left(\lvert\diffEntriesSet\rvert I_r + \Pleftrightarrow{\alphaEdge}{\betaEdge} \: \Ig \frac{\log n}{n} + \Pleftrightarrow{\alphaEdge}{\gammaEdge} \: \IcOne \frac{\log n}{n} + \Pleftrightarrow{\betaEdge}{\gammaEdge} \: \IcTwo \frac{\log n}{n} \right)\right),\nonumber \end{align} where \eqref{eq:matrix_enumerate_neg1} follows from Lemma~\ref{lm:upp_worst_case_err_prob}; \eqref{eq:matrix_enumerate_0} follows from the definition of negative log-likelihood in \eqref{eq:likelihood_defn}; \eqref{eq:matrix_enumerate} follows from the definition of the tuples characterizing matrix classes in \eqref{eq:tuple_ratMat}; \eqref{ineq:upper_bound_M0_XT} follows from Lemma~\ref{lemma:neg_lik_M0_XT} and Lemma~\ref{lemma:upper_bound_B}; and finally \eqref{partial_sum} follows from the definitions of $\TsmallErr$ and $\TlargeErr$ in \eqref{eq:TsmallErr} and \eqref{eq:TlargeErr}, respectively. Finally, the limit of the worst-case probability of error $P_e^{(\delta)}(\psi_{\text{ML}})$ in \eqref{partial_sum} as $n$ and $m$ tend to infinity is evaluated as \begin{align} &\lim_{n,m\rightarrow \infty } P_e^{(\delta)}(\psi_{\text{ML}}) \nonumber\\ &\leq \lim_{n,m\rightarrow \infty } \left( \sum\limits_{T \in \TsmallErr} \sum\limits_{X \in \mathcal{X}(T)} \exp\left(-\left(1\!+\!o(1)\right) \left(\lvert\diffEntriesSet\rvert I_r + \Pleftrightarrow{\alphaEdge}{\betaEdge} \: \Ig \frac{\log n}{n} + \Pleftrightarrow{\alphaEdge}{\gammaEdge} \: \IcOne \frac{\log n}{n} + \Pleftrightarrow{\betaEdge}{\gammaEdge} \: \IcTwo \frac{\log n}{n} \right)\right) \right. \nonumber\\ &\phantom{=\lim_{n\rightarrow \infty } \left(\right.} \left. +\!\sum\limits_{T \in \TlargeErr} \sum\limits_{X \in \mathcal{X}(T)} \!\exp\left(-\left(1+o(1)\right) \left(\lvert\diffEntriesSet\rvert I_r + \Pleftrightarrow{\alphaEdge}{\betaEdge} \: \Ig \frac{\log n}{n} + \Pleftrightarrow{\alphaEdge}{\gammaEdge} \: \IcOne \frac{\log n}{n} + \Pleftrightarrow{\betaEdge}{\gammaEdge} \: \IcTwo \frac{\log n}{n} \right)\right) \right) \nonumber\\ &= 0, \label{eq:lim_err_achv} \end{align} where \eqref{eq:lim_err_achv} follows from Lemma \ref{lemma:T1_related} and Lemma \ref{lemma:eta_omega(nm)}. This concludes the achievability proof of Theorem~\ref{thm:p_star}. \hfill $\blacksquare$ \section{The Converse Proof} \label{sec:conv} In this section, we prove the converse part of Theorem~\ref{thm:p_star}, that is if the condition on $p$ in \eqref{eq:pstar-general_conv} holds, then $ \lim_{n \rightarrow \infty} P_e^{(\delta)}(\psi) \neq 0$ for any estimator $\psi$. To this end, we prove that $\lim_{n\rightarrow \infty} P_e^{(\delta)} (\psi) \neq 0$ for any estimator $\psi$ and any ground truth rating matrix $\gtMat \in \matSet$, if either of the following conditions holds: \begin{align} \frac{g-r+1}{gc}nI_r &\leq (1-\epsilon) \log m, & & \textbf{(Perfect Clustering/Grouping Regime)} \label{eq:necCond_1}\\ \intraTau m I_r + \frac{\Ig}{gc} \log n &\leq (1-\epsilon) \log n, & & \textbf{(Grouping-Limited Regime)} \label{eq:necCond_2}\\ \interTau m I_r + \frac{\IcOne}{gc} \log n + \frac{(g-1) \IcTwo}{gc} \log n &\leq (1-\epsilon) \log n, & & \textbf{(Clustering-Limited Regime)} \label{eq:necCond_3} \end{align} where $I_r$, $\Ig$, $\IcOne$ and $\IcTwo$ are defined in \eqref{eq:Ir_I_abg_defn}. Throughout the proof, let $p = \Theta ((\log n) / n)$, and let $q$ and $\theta$ be constants such that $q$ is prime and $\theta \in [0,1]$. We first present a number of auxiliary lemmas in Section~\ref{sec:conv_auxLemma}. Then, we present the converse proof of Theorem~\ref{thm:p_star} in Section~\ref{sec:conv_proof_thm1}. \subsection{The Auxiliary Lemmas} \label{sec:conv_auxLemma} We present three auxiliary lemmas that are used to prove the converse part of Theorem~\ref{thm:p_star}. Before each lemma, we introduce the terminologies and notations needed for the statement of the lemma. First, let $S$ denote the success event that a rating matrix is correctly estimated (i.e., exactly recovered). It is defined as \begin{align} S \coloneqq \bigcap_{X \neq \gtMat} \left[\mathsf{L}(X) > \mathsf{L}(\gtMat)\right], \label{eq:defS} \end{align} where $\mathsf{L}(X)$ is the negative log-likelihood of a candidate rating matrix $X$, defined in \eqref{eq:likelihood_defn}. The following lemma introduces a lower bound on the infimum of the worst-case probability of error. \begin{lemma} \label{lm:inf_worstProbError} For any estimator $\psi$, we have \begin{align} \inf_{\psi} P_e^{(\delta)} (\psi) \geq \mathbb{P}\left[S^c\right]. \end{align} \end{lemma} \begin{IEEEproof} We refer to Appendix~\ref{app:inf_worstProbError} for the proof of Lemma~\ref{lm:inf_worstProbError}. \end{IEEEproof} Next, the following lemma provides, together with Lemma~\ref{lemma:neg_lik_M0_XT}, a lower bound on the probability that $\mathsf{L}(\gtMat)$ is greater than or equal to $\mathsf{L}(X)$. \begin{lemma} \label{lm:lowerB_prob} For any $\{\misClassfSet{\mu}{\nu} : \left\vert \misClassfSet{\mu}{\nu} \right\vert = \left\vert \misClassfSet{\nu}{\mu} \right\vert, \: \mu, \nu \in \{\alphaEdge,\betaEdge,\gammaEdge \}, \: \mu \neq \nu\}$, we have \begin{align} &\mathbb{P} \left[ \mathbf{B} \geq 0 \right] \geq \frac{1}{4} \exp\left(-\left(1+o(1)\right) \left(\lvert\diffEntriesSet\rvert I_r + \left\vert \misClassfSet{\betaEdge}{\alphaEdge} \right\vert \Ig \frac{\log n}{n} + \left\vert \misClassfSet{\gammaEdge}{\alphaEdge} \right\vert \IcOne \frac{\log n}{n} + \left\vert \misClassfSet{\gammaEdge}{\betaEdge} \right\vert \IcTwo \frac{\log n}{n} \right)\right). \label{eq:lowerB_prob} \end{align} where the random variable $\mathbf{B}$ is defined in \eqref{eq:B_middle}. \end{lemma} \begin{IEEEproof} We refer to Appendix~\ref{app:lowerB_prob_proof} for the proof of Lemma~\ref{lm:lowerB_prob}. \end{IEEEproof} We finally present a lemma that guarantees the existence of two subsets of users with specific properties. \begin{lemma} Consider the sets $\grpG{i}{x}$ and $\grpG{j}{y}$ for $x,y \in [c]$, $i,j \in [g]$ and $(x,i) \neq (y,j)$. As $n\rightarrow \infty$, with probability approaching $1$, there exists two subsets $\tG{i}{x} \subset \grpG{i}{x}$ and $\tG{j}{y}\subset \grpG{j}{y}$ with cardinalities $\vert \tG{i}{x} \vert \geq \frac{n}{\log^3 n}$ and $\vert\tG{j}{y}\vert \geq \frac{n}{\log^3 n}$ such that there are no edges between the vertices in $\tG{i}{x} \cup \tG{j}{y}$. That is, \begin{align} \mathcal{E} \cap \left( \left(\tG{i}{x} \cup \tG{j}{y}\right) \times \left(\tG{i}{x} \cup \tG{j}{y}\right)\right) = \varnothing. \label{eq:noEdgeLemma} \end{align} \label{lm:randGraph} \end{lemma} \begin{IEEEproof} We refer to Appendix~\ref{app:randGraph} for the proof of Lemma~\ref{lm:randGraph}. \end{IEEEproof} \subsection{The Converse Proof of Theorem~\ref{thm:p_star}} \label{sec:conv_proof_thm1} In order to prove the converse part of Theorem~\ref{thm:p_star}, we demonstrate that $\lim_{n,m \rightarrow \infty} \mathbb{P} \left[S\right] = 0$ if any of the conditions given by \eqref{eq:necCond_1}, \eqref{eq:necCond_2} or \eqref{eq:necCond_3} holds. In the following, we show the claim for each condition in \eqref{eq:necCond_1}, \eqref{eq:necCond_2} or \eqref{eq:necCond_3} separately. \subsubsection{Failure Proof for the Perfect Clustering/Grouping Regime} \label{subsec:failureProof1} In this proof, we introduce a class of rating matrices, where each matrix in this class is obtained by replacing one column of $\gtMat$ with a carefully chosen sequence. Then, we prove that if \eqref{eq:necCond_1} holds, then with high probability the ML estimator will fail by selecting one of the rating matrices from this class, instead of $\gtMat$. Recall the sections of the columns of $\gtMat$ defined in Section~\ref{sec:achv}, and note that there exists (at least) one section $\colBlock{\ell}$ such that $\colBlockSize{\ell} = |\colBlock{\ell}|/m $ is bounded away from zero (i.e., not vanishing with $m$ and $n$). For each $k \in \colBlock{\ell}$, define $\M{k} \in \mathbb{F}_{q}^{n \times m}$ as a rating matrix that is identical to $\gtMat$ except for its $k^{\text{th}}$, which will be determined below. Recall from Section~\ref{sec:achv} that $\gtRatingCluster{1} \in \mathbb{F}_{q}^{g \times m}$, the submatrix of $\gtMat$ associated with the first cluster, is obtained by stacking some codeword vectors from a $(g,r)$ MDS code with generator matrix $\iGenerator{1}$. Let $w\in \mathbb{F}_q^{g\times 1}$ be another codeword from this MDS code such that \begin{align} \hamDist{w}{\:\gtRatingCluster{1}\left(:,k\right)} = g-r+1. \label{eq:hamDist_Mc} \end{align} The existence of such a column vector $w$ is guaranteed due to the fact that the $(g,r)$ MDS code in $\mathbb{F}_q$ has a minimum distance of $g-r+1$. Consequently, the entries of $\M{k}$ are given by \begin{align} \M{k}(r,t) = \left\{ \begin{array}{cl} w(1) & \textrm{if $r \in Z(1,1)$ and $t=k$}, \vspace{0.5mm}\\ w(2) & \textrm{if $r \in Z(1,2)$ and $t=k$}, \vspace{0.5mm}\\ \vdots & \qquad\vdots \vspace{0.5mm}\\ w(g) & \textrm{if $r \in Z(1,g) $ and $t=k$}, \vspace{0.5mm}\\ \gtMat(r,t) & \textrm{otherwise}. \end{array} \right. \label{eq:Xk_entries} \end{align} Furthermore, given $\gtMat$ and $\M{k}$, we have \begin{align} \begin{split} &\diffEntriesSet = \left\{(r,k): r \in Z(1,i) \text{ for } i \in [g], \: \M{k}(r,k) \neq \gtMat(r,k)\right\}, \\ &\misClassfSet{\betaEdge}{\alphaEdge} = \misClassfSet{\alphaEdge}{\betaEdge} = \varnothing, \qquad \misClassfSet{\gammaEdge}{\alphaEdge} = \misClassfSet{\alphaEdge}{\gammaEdge} = \varnothing, \qquad \misClassfSet{\gammaEdge}{\betaEdge} = \misClassfSet{\betaEdge}{\gammaEdge} = \varnothing, \end{split} \label{eq:failure1_pairs} \end{align} according to their definitions in \eqref{eq:N1_defn}--\eqref{eq:N4rev_defn}. Thus, the cardinalities of the sets in \eqref{eq:failure1_pairs} are given by \begin{align} \left\vert\diffEntriesSet\right\vert = \frac{n}{gc} (g-r+1), \qquad \left\vert \misClassfSet{\betaEdge}{\alphaEdge} \right\vert = \left\vert \misClassfSet{\alphaEdge}{\gammaEdge} \right\vert = 0, \qquad \left\vert \misClassfSet{\gammaEdge}{\alphaEdge} \right\vert = \left\vert \misClassfSet{\alphaEdge}{\gammaEdge} \right\vert = 0, \qquad \left\vert \misClassfSet{\gammaEdge}{\betaEdge} \right\vert = \left\vert \misClassfSet{\betaEdge}{\gammaEdge} \right\vert = 0. \label{eq:failure1_sizePair} \end{align} For each $\M{k}$ where $k \in \colBlock{\ell}$, the probability that the negative log-likelihood of $\M{k}$ is greater that that of $\gtMat$ is upper bounded~by \begin{align} \mathbb{P} \left[ \mathsf{L}(\M{k}) > \mathsf{L}(\gtMat) \right] &= 1 - \mathbb{P} \left[ \mathsf{L}(\M{k}) \leq \mathsf{L}(\gtMat)\right] \nonumber\\ &= 1 - \mathbb{P} \left[ \log \left((q-1)\frac{1-\theta}{\theta}\right) \sum_{i \in \diffEntriesSet} \mathsf{B}_i^{(p)} \left(\left(1+\mathsf{B}_i^{\left(\frac{1}{q-1}\right)}\right)\mathsf{B}_i^{(\theta)}-1\right) \:\geq\: 0 \right] \label{eq:1stTermX_prob_cond1_0}\\ &= 1 - \mathbb{P} \left[ \log \left((q-1)\frac{1-\theta}{\theta}\right) \sum_{i=1}^{\frac{n}{gc} (g-r+1)} \mathsf{B}_i^{(p)} \left(\left(1+\mathsf{B}_i^{\left(\frac{1}{q-1}\right)}\right)\mathsf{B}_i^{(\theta)}-1\right) \:\geq\: 0\right] \label{eq:1stTermX_prob_cond1_eta} \\ &\leq 1- \frac{1}{4} \exp \left(- (1+o(1))\frac{g-r+1}{gc} n I_r\right) \label{eq:1stTermX_prob_cond1_lm} \\ &\leq \exp \left(- \frac{1}{4} \exp \left(- (1+o(1))\frac{g-r+1}{gc} n I_r\right)\right), \label{eq:1stTermX_prob_cond1} \end{align} where \eqref{eq:1stTermX_prob_cond1_0} follows from Lemma~\ref{lemma:neg_lik_M0_XT} and \eqref{eq:failure1_pairs}; \eqref{eq:1stTermX_prob_cond1_eta} follows from \eqref{eq:failure1_sizePair}; and \eqref{eq:1stTermX_prob_cond1_lm}~is an immediate consequence of Lemma~\ref{lm:lowerB_prob}. Finally, since $\colBlockSize{\ell}$ is bounded away from zero, the probability of exact rating matrix recovery is upper bounded by \begin{align} \mathbb{P}[S] &\leq \mathbb{P} \left[\bigcap_{k\in \colBlock{\ell}} \left(\mathsf{L}(\M{k}) > \mathsf{L}(\gtMat)\right)\right] \label{eq:1stTerm_cond1_0}\\ & = \prod_{k\in \colBlock{\ell}} \mathbb{P} \left[ \mathsf{L}(\M{k}) > \mathsf{L}(\gtMat) \right] \label{eq:1stTerm_cond1_indp} \\ & \leq \left(\exp \left(- \frac{1}{4} \exp \left(- (1+o(1)) \frac{g-r+1}{gc} n I_r\right)\right)\right)^{\colBlockSize{\ell} m} \label{eq:1stTerm_cond1_ident} \\ & = \exp \left(- \frac{1}{4} \colBlockSize{\ell} \exp \left(- (1+o(1)) \frac{g-r+1}{gc} n I_r + \log m\right)\right) \nonumber\\ & \leq \exp \left(- \frac{1}{4} \colBlockSize{\ell} \exp \Bigl( -\bigl( (1+o(1)) (1-\epsilon) - 1 \bigr) \log m \Bigr) \right) \label{eq:1stTerm_cond1_cond}\\ & \leq \exp \left(- \frac{1}{4} \colBlockSize{\ell} \exp \Bigl( \bigl( \epsilon - o(1) (1-\epsilon) \bigr) \log m \Bigr) \right), \end{align} where \eqref{eq:1stTerm_cond1_0} follows from the definition in \eqref{eq:defS}; \eqref{eq:1stTerm_cond1_indp} holds since the events $\{\mathsf{L}(\M{k}) > \mathsf{L}(\gtMat) : k \in \colBlock{\ell}\}$ are mutually independent due to the fact that each event corresponds to a different column $k$ within $\colBlock{\ell}$; \eqref{eq:1stTerm_cond1_ident}~follows from \eqref{eq:1stTermX_prob_cond1}; and \eqref{eq:1stTerm_cond1_cond} follows from the condition in \eqref{eq:necCond_1}. Therefore, we obtain \begin{align} \lim_{n,m \rightarrow \infty} \mathbb{P} \left[S\right] &\leq \lim_{n,m \rightarrow \infty} \exp \left(- \frac{1}{4} \colBlockSize{\ell} \exp \Bigl( \bigl( \epsilon - o(1) (1-\epsilon) \bigr) \log m \Bigr) \right) = 0, \label{eq:lim_Ps_cond1} \end{align} which shows that if the condition in \eqref{eq:necCond_1} holds, then the ML estimator will fail in finding $\gtMat$ with high probability. \subsubsection{Failure Proof for the Grouping-Limited Regime} \label{subsec:failureProof2} Without loss of generality, assume $\intraTau m = \hamDist{\vecU{1}{1}}{\vecU{2}{1}}$, i.e., the rating vectors of groups $1$ and $2$ in cluster~$1$ have the minimum Hamming distance among distinct pairs of rating vectors of groups within the same cluster. In this proof, we introduce a class of rating matrices, which are obtained by switching two users between groups $1$ and $2$ in cluster~$1$. Then, we prove that if \eqref{eq:necCond_2} holds, then with high probability the ML estimator will fail by selecting one of the rating matrices from this class, instead of $\gtMat$. Set $(x,i)=(1,1)$ and $(y,j)=(1,2)$ in Lemma~\ref{lm:randGraph}. Thus, there exist subsets $\tG{1}{1} \subset \grpG{1}{1}$ and $\tG{2}{1}\subset \grpG{2}{1}$ with $|\tG{1}{1}| =|\tG{2}{1}|=\frac{n}{\log^3 n}$, such that the subgraph induced by the vertices in $\tG{1}{1} \cup \tG{2}{1}$ is edge-free. Define $\M{a,b} \in \mathbb{F}_{q}^{n \times m}$, for $a\in \tG{1}{1}$ and $b\in \tG{2}{1}$, as a rating matrix that is identical to $\gtMat$ except for its $a^{\text{th}}$ and $b^{\text{th}}$ rows, which are swapped. More formally, the entries of $\M{a,b}$ are given by \begin{align} \M{a,b}(r,:) = \left\{ \begin{array}{cc} \gtMat(b,:)=\vecU{2}{1} & \textrm{if $r=a$},\\ \gtMat(a,:)=\vecU{1}{1} & \textrm{if $r=b$},\\ \gtMat(r,:) & \textrm{otherwise}. \end{array} \right. \label{eq:Xab_defn} \end{align} The user partitioning $\mathcal{Z}_{\langle a,b\rangle}$ induced by $\M{a,b}$ is given by \begin{align} \Z{a,b}(x,i) = \left\{ \begin{array}{cl} \grpG{1}{1} \cup \{b\} \setminus\{a\} & \textrm{if $(x,i) = (1,1)$}, \vspace{1mm}\\ \grpG{2}{1} \cup \{a\} \setminus\{b\} & \textrm{if $(x,i) = (1,2)$}, \vspace{0.7mm}\\ \grpG{i}{x} & \textrm{otherwise}. \end{array} \right. \label{eq:Zab_defn} \end{align} Furthermore, given $\gtMat$ and $\M{a,b}$, we have \begin{align} \begin{split} \diffEntriesSet &= \left\{(r,t): r \in \{a,b\}, t \in \left[m\right], \: \M{a,b}(r,t) \neq \gtMat(r,t)\right\}, \\ \misClassfSet{\betaEdge}{\alphaEdge} &= \left\{(a,h): h\in \grpG{1}{2}\setminus\{b\} \right\} \:\cup\: \left\{(b,h): h\in \grpG{1}{1}\setminus\{a\} \right\}, \\ \misClassfSet{\alphaEdge}{\betaEdge} &= \left\{(a,h): h\in \grpG{1}{1}\setminus\{a\} \right\} \:\cup\: \left\{(b,h): h\in \grpG{2}{1}\setminus\{b\} \right\}, \\ \misClassfSet{\gammaEdge}{\alphaEdge} &= \misClassfSet{\alphaEdge}{\gammaEdge} = \varnothing, \qquad \misClassfSet{\gammaEdge}{\betaEdge} = \misClassfSet{\betaEdge}{\gammaEdge} = \varnothing, \end{split} \label{eq:failure2_pairs} \end{align} according to their definitions in \eqref{eq:N1_defn}--\eqref{eq:N4rev_defn}. Thus, the cardinalities of the sets in \eqref{eq:failure2_pairs} are given by \begin{align} \begin{split} \left\vert\diffEntriesSet\right\vert &= \hamDist{\M{a,b}(a,:)}{\gtMat(a,:)} + \hamDist{\M{a,b}(b,:)}{\gtMat(b,:)} \\ &= \hamDist{\gtMat(b,:)}{\gtMat(a,:)} + \hamDist{\gtMat(a,:)}{\gtMat(b,:)} \\ &= 2\intraTau m, \\ \left\vert \misClassfSet{\betaEdge}{\alphaEdge} \right\vert &= \left\vert \misClassfSet{\alphaEdge}{\gammaEdge} \right\vert = 2\left(\frac{n}{cg}-1\right), \\ \left\vert \misClassfSet{\gammaEdge}{\alphaEdge} \right\vert &= \left\vert \misClassfSet{\alphaEdge}{\gammaEdge} \right\vert = 0, \qquad \left\vert \misClassfSet{\gammaEdge}{\betaEdge} \right\vert = \left\vert \misClassfSet{\betaEdge}{\gammaEdge} \right\vert = 0. \label{eq:failure2_sizePair} \end{split} \end{align} For each $\M{a,b}$ where $a\in \tG{1}{1}$ and $b\in \tG{2}{1}$, we have \begin{align} \mathsf{L}(\gtMat) - \mathsf{L}\left(\M{a,b}\right) &= \log \left((q-1)\frac{1-\theta}{\theta}\right) \sum_{i \in \diffEntriesSet} \mathsf{B}_i^{(p)} \left(\left(1+\mathsf{B}_i^{\left(\frac{1}{q-1}\right)}\right)\mathsf{B}_i^{(\theta)}-1\right) + \log\left(\frac{(1-\betaEdge)\alphaEdge}{(1-\alphaEdge)\betaEdge}\right) \sum_{j \in \misClassfSet{\betaEdge}{\alphaEdge}} \left( \mathsf{B}_{j}^{(\betaEdge)} - \mathsf{B}_{j}^{(\alphaEdge)}\right) \label{eq:c2_diff_1}\\ &= \log \left((q-1)\frac{1-\theta}{\theta}\right) \sum_{i=1}^{2\intraTau m} \mathsf{B}_i^{(p)} \left(\left(1+\mathsf{B}_i^{\left(\frac{1}{q-1}\right)}\right)\mathsf{B}_i^{(\theta)}-1\right) + \log\left(\frac{(1-\betaEdge)\alphaEdge}{(1-\alphaEdge)\betaEdge}\right) \sum_{j=1}^{2(\frac{n}{cg}-1)} \left( \mathsf{B}_{j}^{(\betaEdge)} - \mathsf{B}_{j}^{(\alphaEdge)}\right), \label{eq:c2_diff_2} \end{align} where \eqref{eq:c2_diff_1} follows from Lemma~\ref{lemma:neg_lik_M0_XT} and \eqref{eq:failure2_pairs}; and \eqref{eq:c2_diff_2} follows from \eqref{eq:failure2_sizePair}. Therefore, the probability that the negative log-likelihood of $\M{a,b}$ is greater that that of $\gtMat$ is upper bounded by \begin{align} \mathbb{P} \left[ \mathsf{L}\left(\M{a,b}\right) > \mathsf{L}(\gtMat)\right] &= 1 - \mathbb{P}\left[ \mathsf{L}(\gtMat) - \mathsf{L}\left(\M{a,b}\right) \geq 0\right] \nonumber \\ &\leq 1 - \frac{1}{4} \exp \left( - (1 + o(1)) \left(2 \intraTau m I_r + 2\left(\frac{n}{cg}-1\right) \Ig \frac{\log n}{n} \right) \right) \label{eq:2nd-L-diff_0}\\ &\leq \exp \left( - \frac{1}{4} \exp \left( - (1+o(1)) \left(2\intraTau m I_r + 2\left(\frac{n}{cg}-1\right) \Ig \frac{\log n}{n} \right) \right) \right), \label{eq:2nd-L-diff} \end{align} where \eqref{eq:2nd-L-diff_0} follows from \eqref{eq:c2_diff_2} and Lemma~\ref{lm:lowerB_prob}. Finally, the probability of exact rating matrix recovery is upper bounded by \begin{align} \mathbb{P}[S] &\leq \mathbb{P} \left[\bigcap_{\substack{a\in \tG{1}{1} \\ b\in \tG{2}{1}}} \left(\mathsf{L}\left(\M{a,b}\right) > \mathsf{L}(\gtMat)\right)\right] \label{eq:2nd-success-0}\\ &= \prod_{\substack{a\in \tG{1}{1} \\ b\in \tG{2}{1}}} \mathbb{P} \left[ \mathsf{L}\left(\M{a,b}\right) > \mathsf{L}(\gtMat) \right] \label{eq:2nd-indep} \\ & \leq \left(\exp \left( - \frac{1}{4} \exp \left( - (1+o(1)) \left(2\intraTau m I_r + 2\left(\frac{n}{cg}-1\right) \Ig \frac{\log n}{n} \right) \right) \right) \right)^{\left|\tG{1}{1}\right|\cdot \left|\tG{2}{1}\right|} \label{eq:2nd-eval} \\ & = \exp \left( -\frac{n^2}{4\log^6 n} \exp \left( - (1+o(1)) \left(2\intraTau m I_r + 2\left(\frac{n}{cg}-1\right) \Ig \frac{\log n}{n} \right) \right) \right) \label{eq:2nd-SetSize}\\ & \leq \exp \left( -\frac{n^2}{4 \log^6 n} \exp \left( - 2(1+o(1)) (1-\epsilon) \log n \right) \right) \label{eq:2d-BadCond}\\ & \leq \exp \left(-\frac{n^{2(\epsilon - o(1)(1-\epsilon))}}{4 \log^6 n } \right), \end{align} where \eqref{eq:2nd-success-0} follows from the definition in \eqref{eq:defS}; \eqref{eq:2nd-indep} holds since the events $\{\mathsf{L}\left(\M{a,b}\right) > \mathsf{L}(\gtMat) : a\in \tG{1}{1}, b\in \tG{2}{1}\}$ are mutually independent due to the fact that there are no edges among the vertices in $\tG{1}{1} \cup \tG{2}{1}$, as per Lemma~\ref{lm:randGraph}; \eqref{eq:2nd-eval} follows from \eqref{eq:2nd-L-diff}; \eqref{eq:2nd-SetSize} holds since $|\tG{1}{1}| =|\tG{2}{1}|=\frac{n}{\log^3 n}$; and \eqref{eq:2d-BadCond} follows from the condition in \eqref{eq:necCond_2}. Therefore, we obtain \begin{align*} \lim_{n,m \rightarrow \infty } \mathbb{P}[S] \leq \lim_{n,m \rightarrow \infty } \exp \left( -\frac{n^{2(\epsilon - o(1)(1-\epsilon))}}{4 \log^6 n} \right) =0, \end{align*} which shows that if the condition in \eqref{eq:necCond_2} holds, then the ML estimator will fail in finding $\gtMat$ with high probability. \subsubsection{Failure Proof for the Clustering-Limited Regime} \label{subsec:failureProof3} The proof follows the same structure as that presented in Section~\ref{subsec:failureProof2} where the condition in \eqref{eq:necCond_2} holds. Without loss of generality, assume that the rating vectors of group $1$ in cluster $1$ and group $2$ in cluster $2$ have the minimum Hamming distance among distinct pairs of rating vectors across different clusters, i.e., $ \hamDist{\vecU{1}{1}}{ \vecU{2}{2}} = \interTau m$. Note that the corresponding groups defined by such rating vectors belong to different clusters, as opposed to the same cluster in Section~\ref{subsec:failureProof2}. In this proof, we introduce a class of rating matrices, which are obtained by switching two users between group $1$ in cluster $1$ and group $2$ in cluster $2$. Then, we prove that if \eqref{eq:necCond_3} holds, then with high probability the ML estimator will fail by selecting one of the rating matrices from this class, instead of~$\gtMat$. Set $(x,i)=(1,1)$ and $(y,j)=(2,2)$ in Lemma~\ref{lm:randGraph}. Hence, there exist subsets $\tG{1}{1} \subset \grpG{1}{1}$ and $\tG{2}{2}\subset \grpG{2}{2}$ with $|\tG{1}{1}| =|\tG{2}{2}|=\frac{n}{\log^3 n}$, such that the subgraph induced by the vertices in $\tG{1}{1} \cup \tG{2}{2}$ is edge-free. Similar to \eqref{eq:Xab_defn} and \eqref{eq:Zab_defn} in Section~\ref{subsec:failureProof2}, define $\M{a,b} \in \mathbb{F}_{q}^{n \times m}$, for $a\in \tG{1}{1}$ and $b\in \tG{2}{2}$, as \begin{align} \M{a,b}(r,:) = \left\{ \begin{array}{cc} \gtMat(b,:)=\vecU{2}{2} & \textrm{if $r=a$},\\ \gtMat(a,:)=\vecU{1}{1} & \textrm{if $r=b$},\\ \gtMat(r,:) & \textrm{otherwise}. \end{array} \right. \label{eq:Xab_defn_2} \end{align} The corresponding user partitioning $\mathcal{Z}_{\langle a,b\rangle}$ is given by \begin{align} \Z{a,b}(x,i) = \left\{ \begin{array}{cl} \grpG{1}{1} \cup \{b\} \setminus\{a\} & \textrm{if $(x,i) = (1,1)$}, \vspace{1mm}\\ \grpG{2}{2} \cup \{a\} \setminus\{b\} & \textrm{if $(x,i) = (2,2)$}, \vspace{0.7mm}\\ \grpG{i}{x} & \textrm{otherwise}. \end{array} \right. \label{eq:Zab_defn_2} \end{align} Furthermore, given $\gtMat$ and $\M{a,b}$, we have \begin{align} \begin{split} \diffEntriesSet &= \left\{(r,t): r \in \{a,b\}, t \in \left[m\right], \: \M{a,b}(r,t) \neq \gtMat(r,t)\right\}, \\ \misClassfSet{\betaEdge}{\alphaEdge} &= \misClassfSet{\alphaEdge}{\betaEdge} = \varnothing, \\ \misClassfSet{\gammaEdge}{\alphaEdge} &= \left\{(a,h): h\in \grpG{2}{2}\setminus\{b\} \right\} \:\cup\: \left\{(b,h): h\in \grpG{1}{1}\setminus\{a\} \right\}, \\ \misClassfSet{\alphaEdge}{\gammaEdge} &= \left\{(a,h): h\in \grpG{1}{1}\setminus\{a\} \right\} \:\cup\: \left\{(b,h): h\in \grpG{2}{2}\setminus\{b\} \right\}, \\ \misClassfSet{\gammaEdge}{\betaEdge} &= \left\{(a,h): h \in \bigcup_{i \in [g] \setminus \{2\}} \grpG{i}{2} \right\} \:\cup\: \left\{(b,h): h \in \bigcup_{i \in [g] \setminus \{1\}} \grpG{i}{1} \right\}, \\ \misClassfSet{\betaEdge}{\gammaEdge} &= \left\{(a,h): h \in \bigcup_{i \in [g] \setminus \{1\}} \grpG{i}{1} \right\} \:\cup\: \left\{(b,h): h \in \bigcup_{i \in [g] \setminus \{2\}} \grpG{i}{2} \right\}, \end{split} \label{eq:failure3_pairs} \end{align} according to their definitions in \eqref{eq:N1_defn}--\eqref{eq:N4rev_defn}. Thus, the cardinalities of the sets in \eqref{eq:failure3_pairs} are given by \begin{align} \begin{split} \left\vert\diffEntriesSet\right\vert &= \hamDist{\M{a,b}(a,:)}{\gtMat(a,:)} + \hamDist{\M{a,b}(b,:)}{\gtMat(b,:)} \\ &= \hamDist{\gtMat(b,:)}{\gtMat(a,:)} + \hamDist{\gtMat(a,:)}{\gtMat(b,:)} \\ &= 2\interTau m, \\ \left\vert \misClassfSet{\betaEdge}{\alphaEdge} \right\vert &= \left\vert \misClassfSet{\alphaEdge}{\gammaEdge} \right\vert = 0, \\ \left\vert \misClassfSet{\gammaEdge}{\alphaEdge} \right\vert &= \left\vert \misClassfSet{\alphaEdge}{\gammaEdge} \right\vert = 2 \left(\frac{n}{cg}-1\right), \\ \left\vert \misClassfSet{\gammaEdge}{\betaEdge} \right\vert &= \left\vert \misClassfSet{\betaEdge}{\gammaEdge} \right\vert = 2 \left(\frac{g-1}{gc}\right) n. \end{split} \label{eq:failure3_sizePair} \end{align} For each $\M{a,b}$ where $a\in \tG{1}{1}$ and $b\in \tG{2}{2}$, we have \begin{align} \mathsf{L}(\gtMat) - \mathsf{L}\left(\M{a,b}\right) &= \log \left((q-1)\frac{1-\theta}{\theta}\right) \sum_{i \in \diffEntriesSet} \mathsf{B}_i^{(p)} \left(\left(1+\mathsf{B}_i^{\left(\frac{1}{q-1}\right)}\right)\mathsf{B}_i^{(\theta)}-1\right) \nonumber\\ &\phantom{=} + \left(\log\frac{(1-\gammaEdge)\alphaEdge}{(1-\alphaEdge)\gammaEdge}\right) \sum_{i \in \misClassfSet{\gammaEdge}{\alphaEdge}} \left(\mathsf{B}_{i}^{(\gammaEdge)} - \mathsf{B}_{i}^{(\alphaEdge)}\right) + \left(\log\frac{(1-\gammaEdge)\betaEdge}{(1-\betaEdge)\gammaEdge}\right) \sum_{i \in \misClassfSet{\gammaEdge}{\betaEdge}} \left(\mathsf{B}_{i}^{(\gammaEdge)} - \mathsf{B}_{i}^{(\betaEdge)}\right) \label{eq:c1_diff_0}\\ &= \log \left((q-1)\frac{1-\theta}{\theta}\right) \sum_{i = 1}^{2\interTau m} \mathsf{B}_i^{(p)} \left(\left(1+\mathsf{B}_i^{\left(\frac{1}{q-1}\right)}\right)\mathsf{B}_i^{(\theta)}-1\right) \nonumber\\ &\phantom{=} + \left(\log\frac{(1-\gammaEdge)\alphaEdge}{(1-\alphaEdge)\gammaEdge}\right) \sum_{i = 1}^{2 \left(\frac{n}{cg}-1\right)} \left(\mathsf{B}_{i}^{(\gammaEdge)} - \mathsf{B}_{i}^{(\alphaEdge)}\right) + \left(\log\frac{(1-\gammaEdge)\betaEdge}{(1-\betaEdge)\gammaEdge}\right) \sum_{i = 1}^{2 \left(\frac{g-1}{gc}\right) n} \left(\mathsf{B}_{i}^{(\gammaEdge)} - \mathsf{B}_{i}^{(\betaEdge)}\right), \label{eq:c1_diff_1} \end{align} where \eqref{eq:c1_diff_0} follows from Lemma~\ref{lemma:neg_lik_M0_XT} and \eqref{eq:failure3_pairs}; and \eqref{eq:c1_diff_1} follows from \eqref{eq:failure3_sizePair}. Therefore, the probability that the negative log-likelihood of $\M{a,b}$ is greater that that of $\gtMat$ is upper bounded by \begin{align} \mathbb{P} \left[ \mathsf{L}\left(\M{a,b}\right) > \mathsf{L}(\gtMat)\right] &= 1 - \mathbb{P}\left[ B\left(2\interTau m,\: 0,\: 2 \left(\frac{n}{cg}-1\right),\: 2 \left(\frac{g-1}{gc}\right) n \right) \geq 0 \right] \nonumber \\ &\leq 1 - \frac{1}{4} \exp \left( - (1+o(1)) \left(2\interTau m I_r + 2\left(\frac{n}{cg}-1\right) \IcOne \frac{\log n}{n} + 2 \left(\frac{g-1}{gc}\right) n \IcTwo \frac{\log n}{n} \right) \right) \label{eq:3rd-L-diff}\\ &\leq \exp \left( - \frac{1}{4} \exp \left( - (1+o(1)) \left(2\interTau m I_r + 2\left(\frac{n}{cg}-1\right) \IcOne \frac{\log n}{n} + 2 \left(\frac{g-1}{gc}\right) n \IcTwo \frac{\log n}{n} \right) \right) \right), \end{align} where \eqref{eq:3rd-L-diff} follows from \eqref{eq:c1_diff_1} and Lemma~\ref{lm:lowerB_prob}. Finally, the probability of exact rating matrix recovery is upper bounded by \begin{align} \mathbb{P}[S] &\leq \mathbb{P} \left[\bigcap_{\substack{a\in \tG{1}{1} \\ b\in \tG{2}{2}}} \left(\mathsf{L}\left(\M{a,b}\right) > \mathsf{L}(\gtMat)\right)\right] \label{eq:3rd-success-0}\\ &= \prod_{\substack{a\in \tG{1}{1} \\ b\in \tG{2}{2}}} \mathbb{P} \left[ \mathsf{L}\left(\M{a,b}\right) > \mathsf{L}(\gtMat)\right]\label{eq:3rd-indep}\\ &\leq \left(\exp \left( - \frac{1}{4} \exp \left( - (1+o(1)) \left(2\interTau m I_r + 2\left(\frac{n}{cg}-1\right) \IcOne \frac{\log n}{n} + 2\left(\frac{g-1}{gc}\right) n \IcTwo \frac{\log n}{n} \right) \right) \right)\right)^{\left|\tG{1}{1}\right|\cdot \left|\tG{2}{2}\right|} \label{eq:3rd-eval} \\ & \leq \exp \left( -\frac{n^2}{4 \log^6 n} \exp \left( - 2(1+o(1)) (1-\epsilon) \log n \right) \right) \label{eq:3rd-BadCond}\\ & \leq \exp \left(-\frac{n^{2(\epsilon - o(1)(1-\epsilon))}}{4 \log^6 n} \right), \end{align} where \eqref{eq:3rd-success-0} follows from the definition in \eqref{eq:defS}; \eqref{eq:3rd-indep} holds since the events $\{\mathsf{L}\left(\M{a,b}\right) > \mathsf{L}(\gtMat) : a\in \tG{1}{1}, b\in \tG{2}{2}\}$ are mutually independent due to the fact that there are no edges among the vertices in $\tG{1}{1} \cup \tG{2}{2}$, as per Lemma~\ref{lm:randGraph}; \eqref{eq:3rd-eval} follows from \eqref{eq:3rd-L-diff}; and \eqref{eq:3rd-BadCond} follows from the condition in \eqref{eq:necCond_3}, and $|\tG{1}{1}| =|\tG{2}{1}|=\frac{n}{\log^3 n}$. Thus, we obtain \begin{align*} \lim_{n,m\rightarrow \infty } \mathbb{P}[S] = \lim_{n,m\rightarrow \infty } \exp \left(-\frac{n^{2(\epsilon - o(1)(1-\epsilon))}}{4 \log^6 n} \right) =0, \end{align*} which shows that if the condition in \eqref{eq:necCond_3} holds, then the ML estimator will fail in finding $\gtMat$ with high probability. Since $\lim_{n,m \rightarrow \infty} \mathbb{P} \left[S\right] = 0$ is proved under each of the three conditions stated in \eqref{eq:necCond_1}, \eqref{eq:necCond_2} and \eqref{eq:necCond_3}, the converse proof of Theorem~\ref{thm:p_star} is concluded. \hfill $\blacksquare$ \section{Simulation Results} \label{sec:expResults} We conduct Monte Carlo experiments\footnote{The proposed achievable scheme is based on maximum likelihood estimation whose computational complexity increases dramatically with the problem size (i.e., as $n$ and $m$ increase). Therefore, we use the computationally efficient matrix completion algorithm, proposed in \cite{elmahdy2020matrix}.} to corroborate Theorem~\ref{thm:p_star}. We consider a problem setting in which we have $c=2$ clusters, $g=3$ groups per cluster, finite field of order $q=2$, and $r=2$ basis vectors per group. The MDS code structure is given $\vecU{3}{x} = \vecU{1}{x} + \vecU{2}{x}$ for $x\in[2]$. Furthermore, the parameters of observation noise, graph and rating vectors are set to $\theta=0.1$, $(\beta,\gamma)=(10,0.5)$ and $(\intraTau,\interTau)=(0.5,0.5)$, respectively. Finally, the synthetic data is generated as per the model in Section~\ref{subsec:probForm}. In Figs. \ref{fig:synth_alph40} and \ref{fig:synth_alph17}, we evaluate the performance of the proposed algorithm, and quantify the empirical success rate as a function of the normalized sample complexity over $10^3$~randomly drawn realizations of rating vectors and hierarchical graphs. We vary $n$ and $m$, preserving the ratio $n/m=3$. Fig.~\ref{fig:synth_alph40} depicts the case of $\alpha = 40$ which corresponds to perfect clustering/grouping regime, while Fig.~\ref{fig:synth_alph17} illustrates the case of $\alpha = 17$ which corresponds to grouping-limited regime. In both figures, we observe a phase transition\footnote{The transition is ideally a step function at $p = p^\star$ as $n$ and $m$ tend to infinity.} in the success rate at $p = p^\star$, and the phase transition gets sharper as $n$ and $m$ increase. Figs. \ref{fig:synth_alph40} and \ref{fig:synth_alph17} corroborate Theorem~\ref{thm:p_star} in different regimes when the graph side information is not scarce. \begin{figure* \centering \subfloat[]{\includegraphics[width=0.45\textwidth]{fig_synth_alph40.pdf} \label{fig:synth_alph40}} \hfill \subfloat[]{\includegraphics[width=0.45\textwidth]{fig_synth_alph17.pdf} \label{fig:synth_alph17}} \hfill \caption{ The success rate of the proposed algorithm as a function of $p/p^\star$ for under different values of $n$, $m$ and $\alpha$. The considered problem setting is characterized by $(c,g,q,r)=(2,3,2,2)$, $\vecU{3}{x} = \vecU{1}{x} + \vecU{2}{x}$ for $x\in[2]$, $\theta=0.1$, $(\beta,\gamma)=(10,0.5)$, and $(\intraTau,\interTau)=(0.5,0.5)$. We study two cases: (a) perfect clustering/grouping regime where $\alpha = 40$; and (b) grouping-limited regime where $\alpha = 17$. } \end{figure*} \section{Conclusion} \label{sec:conclusion} In this paper, we consider a rating matrix that consists of $n$ users and $m$ items, and a hierarchical similarity graph that consists of $c$ disjoint clusters, and each cluster comprises $g$ disjoint groups. The rating vectors of the groups of a given cluster are different, but related to each other through a linear subspace of $r$ basis vectors. We characterize the optimal sample complexity to jointly recover the hierarchical structure of the similarity graph as well as the rating matrix entries. We propose a matrix completion algorithm that is based on the maximum likelihood estimation, and achieve the characterized sample complexity. The optimality of the proposed achievable scheme was demonstrated through a matching converse proof. We demonstrate that the optimal sample complexity hinge on the quality of side information of the hierarchical similarity graph. We also highlighted the fact that leveraging the graph side information enables us to achieve significant gain in sample complexity, compared to existing schemes that identifies different groups without taking into consideration the hierarchical structure across them. One potential research direction is to develop a computationally efficient algorithm to achieve the sharp threshold on the optimal sample complexity characterized in this paper. Another research direction is to characterize the optimal sample complexity for a more general case of $c$ clusters, each of which comprise arbitrary number of groups of possibly different number of users. \bibliographystyle{IEEEtran}
{'timestamp': '2021-09-14T02:18:36', 'yymm': '2109', 'arxiv_id': '2109.05408', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05408'}
arxiv
\section{Introduction} \label{Introduction} The variational reformulation of Griffith’s theory~\cite{griffith_phenomena_1921} proposed by Francfort and Marigo~\cite{francfort_revisiting_1998} and followed by Bourdin et al.'s phase-field regularization~\cite{bourdin_numerical_2000} offered a robust mathematical and computational framework for the modeling of quasi-static brittle fracture. Based on a smooth representation of the discontinuities through a damage field, variational phase-field models compute the nucleation and propagation of complex crack paths through the minimization of an energy functional. As opposed to discrete approaches dealing explicitly with cracks like Linear Elastic Fracture Mechanics (LEFM) or Cohesive Zone Models (CZMs), the phase-field method for fracture can model crack propagation without the need for remeshing, a priori knowledge of the crack path or ad hoc criteria~\cite{wu_phase-field_2019}. Owing to its elegant simplicity and its compatibility with classical finite element methods, the phase-field method has been applied and extended to hydraulic fracture~\cite{mikelic_phase-field_2015,wilson_phase-field_2016}, ductile fracture~\cite{miehe_phase_2016,borden_phase-field_2016}, stress corrosion cracking~\cite{nguyen_phase_2017,martinez-paneda_phase_2018} and brittle fracture in heterogeneous structures~\cite{hansen-dorr_phase-field_2019,nguyen_phase_2019}. A well-known downside of phase-field models is their high computational cost. The first explanation for this situation is the necessity of a very fine mesh for the finite element method to accurately capture the strong damage gradient in the fracture zone, yielding large linear systems to be solved. Adaptive mesh techniques~\cite{heister_primal-dual_2015,ferro_anisotropic_2018,mang_mesh_2020} and multiscale methods~\cite{patil_adaptive_2018, nguyen_multiscale_2019} have been developed and appear to successfully reduce the number of degrees of freedom to a minimum. The second explanation for the high computational cost is the non-linear and non-convex nature of the underlying energy functional of phase-field models~\cite{bourdin_numerical_2000}. For non-convex problems, the conventional Newton's method is inadequate since the Hessian can become indefinite and hinder the convergence to a critical point. The first method proposed in the literature to solve phase-field models was the alternating minimization algorithm~\cite{bourdin_numerical_2000}. Stemming from the observation that the functional is convex in each variable when the other field is fixed, the alternating minimization scheme alternatively solves the kinematic and damage sub-problems until convergence. Widely adopted by the community~\hl{\mbox{\cite{martinez-paneda_phase_2018,hansen-dorr_phase-field_2019,miehe_phase_2010,amor_regularized_2009,borden_phase-field_2012,ambati_phase-field_2015,nguyen_phase-field_2016,marigo_overview_2016,pham_experimental_2017,tanne_crack_2018,gerasimov_penalization_2019}}}, the algorithm is robust, but exhibits a slow convergence rate due to the decoupling of the sub-problems~\cite{gerasimov_line_2016,farrell_linear_2017,wu_bfgs_2020}. Significant gains in efficiency were obtained using a combination of preconditioned alternating minimization scheme and classical Newton's method~\cite{farrell_linear_2017}\hl{, a staggered scheme relying on a truncated modified Newton method~\mbox{\cite{kirkesaether_brun_iterative_2020}}}, or a semi-implicit form of the staggered scheme~\cite{lu_efficient_2020}. \hl{An accelerated staggered scheme combining Anderson acceleration and over-relaxation was also shown to yield significant decrease in computation time in~\mbox{\cite{storvik_accelerated_2021}}.} Nevertheless, such methods require either the tuning of \hl{numerical parameters} or a time step convergence study, implying additional computation, while still suffering from the decoupling between the displacement and damage fields. \hl{The quasi-monolithic approach~\mbox{\cite{heister_primal-dual_2015}} is a non-partitioned and robust alternative to the staggered scheme relying on the linearization of the kinematic sub-problem through a time extrapolation of the phase-field~\mbox{\cite{wick_multiphysics_2020}}. This partial linearization allowing to solve simultaneously both sub-problems was used in~\mbox{\cite{lee_phase-field_2018,jodlbauer_matrix-free_2019,mang_phase-field_2020}}}. The quasi-monolithic scheme was also reported efficient and robust in~\cite{wick_error-oriented_2017}, but the relaxation of the applied forces and a delayed crack growth was observed. Furthermore, the delayed and relaxed evolution seems to be amplified under unstable crack growth, where the damage field evolves rapidly. This suggests that the quasi-monolithic scheme generates a numerical viscosity, requiring smaller time steps and, therefore, an increased computational cost to accurately capture rapidly growing cracks. To the best of our knowledge, the efficiency of the alternating minimization algorithm and the quasi-monolithic scheme has never been compared. \hl{A fully monolithic scheme would have the potential to be more efficient than the alternating and quasi-monolithic methods since it would preserve the strong coupling between the two fields.} As reported by Wick~\cite{wick_modified_2017}, obtaining a monolithic scheme for phase-field models for fracture is a difficult task. Numerous monolithic algorithms have been proposed, such as a Newton method using a modified line-search algorithm~\cite{gerasimov_line_2016}, an error-oriented Newton’s method~\cite{wick_error-oriented_2017}, a modified Newton method with Jacobian modification~\cite{wick_modified_2017}, \hl{and a multilevel trust region method~\mbox{\cite{kopanicakova_recursive_2020}}}. Probably due to their complexity, variable robustness, or problem-dependent efficiency, these monolithic methods have yet to impose themselves, with the alternating minimization algorithm and quasi-monolithic scheme still being vastly more represented in the literature. More recently, Wambacq et al.~\cite{wambacq_interior-point_2021} proposed a monolithic solver relying on a modified Newton method with inertia correction inspired by~\cite{wachter_implementation_2006}. Although the modified Newton method showed interesting performance, their work focused on the efficiency of the interior-point method to enforce the irreversibility condition present in phase-field models for fracture. Consequently, the efficiency of the monolithic solver was only compared to the alternating algorithm when coupled with the interior-point method. The performances of the two solvers were concluded to be problem-dependent in this case. We also point out that few popular formulations, such as the history variable approach of Miehe and co-workers~\cite{miehe_phase_2010}, or the hybrid model from~\cite{ambati_review_2015}, although computationally efficient, have the downfall of being variationally inconsistent. Gerasimov and De Lorenzis came to the conclusion that the approach based on the history variable proposed by Miehe~\cite{miehe_phase_2010} leads to the solution of a problem that is not equivalent to the variational one~\cite{gerasimov_penalization_2019}. \hl{Therefore, we focus in this work on the efficiency of solvers for phase-field models that do not rely on the history variable.} In this work, we formulate a fully monolithic and implicit solver relying on a modified Newton method with inertia correction of the Jacobian and a backtracking energy line-search, similar to~\cite{wambacq_interior-point_2021,wachter_implementation_2006}. We then compare the performance of the alternating minimization algorithm, the quasi-monolithic scheme and the modified Newton solver on four benchmark tests selected from the phase-field literature. To eliminate the time step dependency of the quasi-monolithic scheme and facilitate its benchmarking, we couple the latter with an extrapolation correction loop controlled by a damage evolution \hl{criterion}. The benchmarking demonstrates that not only is the modified Newton method a robust monolithic solver for variational phase-field models, but it is also significantly more efficient than the quasi-monolithic and alternating minimization algorithms. The paper is organized as follows. In Section~\ref{Background}, we recall the formulation of variational phase-field models, describe the adopted treatment of the irreversibility constraint, and write the Euler-Lagrange equations of the minimization problem along with their discretization. We also present the alternating minimization algorithm and the quasi-monolithic scheme. In Section~\ref{New solution algorithms}, we present a monolithic solver for variational phase-field models based on a modified Newton method and describe the quasi-monolithic scheme augmented with an extrapolation correction loop. Section~\ref{Numerical results} compares the performance of the three studied algorithms on four different benchmark tests and discusses the results. Finally, our conclusions are presented in Section~\ref{Conclusions}. \section{Background} \label{Background} \subsection{Variational modeling of brittle fracture} Here we define the phase-field model for brittle fracture, including the strain energy decomposition and treatment of the irreversibility condition adopted, on which is performed the benchmarking of the three solvers. Then, the Euler-Lagrange equations of the unconstrained variational problem and their spatial discretization are defined. \subsubsection{Variational formulation} Let $\Omega \subset {\rm I\!R}^\delta$ ($\delta = 2,3$) be the domain representing a crack-free brittle elastic body. The boundary $\partial \Omega$ is subject to time-dependent Dirichlet and Neumann conditions, $\Gamma_D \subset \partial \Omega$, $\Gamma_N \subset \partial \Omega$, with $\Gamma_D \cup \Gamma_N = \partial \Omega$ and $\Gamma_D \cap \Gamma_N = \emptyset$. We also introduce an evolving crack surface $\Gamma_c \subset \Omega$. We define the displacement function $\boldsymbol{u}:\Omega \setminus \Gamma_c \subset {\rm I\!R}^\delta \rightarrow {\rm I\!R}^\delta$ and the linearized elastic strain $\boldsymbol{e}(\boldsymbol{u})\coloneqq \frac{1}{2}(\nabla \boldsymbol{u}^T + \nabla \boldsymbol{u})$. We can therefore define the elastic potential energy $\Psi(\boldsymbol{u}) = \frac{1}{2} \boldsymbol{\sigma}(\boldsymbol{u}):\boldsymbol{e}(\boldsymbol{u})$, where $\boldsymbol{\sigma}(\boldsymbol{u})$ is the stress tensor. Finally, we denote the critical energy release rate of the brittle material with $G_c$. Neglecting the external forces, Francfort and Marigo's \hl{reformulation} of quasi-static brittle fracture~\cite{francfort_revisiting_1998} leads to the following variational problem \begin{equation} \boldsymbol{u},\Gamma_c = \textrm{arg}\,\textrm{min } \mathcal{E}(\boldsymbol{u},\Gamma_c ) \quad \textrm{s.t.} \quad \dot{\Gamma}_c \geq 0, \end{equation} with the energy functional \begin{equation} \mathcal{E}(\boldsymbol{u}, \Gamma_c) = \int_{\Omega \setminus \Gamma_c} \Psi(\boldsymbol{u}) \, \text{d}\boldsymbol{x} + \int_{\Gamma_c} G_c \, \text{d}s. \end{equation} Phase-field damage models use the Ambrosio and Tortorelli elliptical regularization~\cite{ambrosio_approximation_1990} to overcome problems associated with the numerical treatment of the discontinuous crack $\Gamma_c$, as proposed initially in~\cite{bourdin_numerical_2000}. The regularization replaces the sharp crack by a diffuse damage band through the phase-field variable, denoted by $d:\Omega \rightarrow [0,1]$, where $d=0$ describes the undamaged material and $d=1$ describes the fully damaged material. The displacement function becomes $\boldsymbol{u}:\Omega \subset {\rm I\!R}^\delta \rightarrow {\rm I\!R}^\delta$. The different phase-field models for brittle fracture are characterized mainly by the type of crack function $\alpha(d)$ and degradation function $g(d)$ adopted. They can generally be expressed as \begin{equation} \mathcal{E}_l(\boldsymbol{u},d) = \int_{\Omega} g(d)\Psi(\boldsymbol{u}) \, \text{d}\boldsymbol{x} + \frac{G_c}{c_\alpha}\int_{\Omega}\Big(\frac{\alpha(d)}{l}+l|\nabla d|^2 \Big)\text{d}\boldsymbol{x}, \end{equation} with the normalization parameter $c_\alpha \coloneqq 4\int_0^1 \sqrt{\alpha(z)} \, \text{d}z$ \cite{tanne_crack_2018,gerasimov_penalization_2019}. The regularization $\alpha(d)$ and the characteristic length $l$ define the shape and width of the smeared crack while the degradation function $g(d)$ describes the dependency of the apparent stiffness on the damage field. In this paper, we focus on the so-called $AT_1$ model with its linear crack function $\alpha(d) = d$ and quadratic degradation function $g(d)=(1-d)^2$ introduced by Pham et al.~\cite{pham_gradient_2011}, yielding the functional \begin{equation} \label{AT1} \mathcal{E}_l(\boldsymbol{u},d) = \int_{\Omega} (1-d)^2\Psi(\boldsymbol{u}) \, \text{d}\boldsymbol{x} + \frac{3G_c}{8}\int_{\Omega}\Big(\frac{d}{l}+l|\nabla d|^2 \Big)\text{d}\boldsymbol{x}. \end{equation} With the regularized energy functional relying on the phase-field variable, the variational problem now reads \begin{equation} \label{VP} \boldsymbol{u},d = \textrm{arg}\,\textrm{min } \mathcal{E}_l(\boldsymbol{u},d ) \quad \textrm{s.t.} \quad 0 \leq d \leq 1 \quad \textrm{and} \quad \dot{d} \geq 0. \end{equation} As opposed to the widely used $AT_2$ model, the $AT_1$ model prevents damage initiation at low strain-energy density, therefore exhibiting an elastic phase. Furthermore, the linear crack function of the $AT_1$ model leads to a finite localization band, implying the convergence to the Griffith energy without the necessity of the characteristic length $l$ to approach zero~\cite{tanne_crack_2018}. However, the constraint $d \geq 0$ from the minimization problem \eqref{VP} is no longer naturally respected. A well-known issue with formulation \eqref{AT1} is its inability to distinguish between energy generated from tensile or compressive loading. Consequently, interpenetration of crack surfaces and non-physical cracks were observed early in the developments of the variational approach to fracture~\cite{bourdin_numerical_2000}. Multiple methods using energy splits have been proposed to elude this difficulty~\cite{lancioni_variational_2009, wu_novel_2018, bilgen_crack-driving_2019,dijk_strain_2020}, such as the volumetric-deviatoric split~\cite{amor_regularized_2009} adopted in~\cite{schluter_phase_2014,wu_phase-field_2017} and the spectral split~\cite{miehe_phase_2010} adopted in~\cite{pham_experimental_2017,wick_modified_2017}. In this work, we adopt the spectral decomposition of the strain tensor in its positive and negative components, as proposed by Miehe~\cite{miehe_phase_2010}, with \begin{equation} \boldsymbol{e}(\boldsymbol{u}) = \boldsymbol{e}^+(\boldsymbol{u}) + \boldsymbol{e}^-(\boldsymbol{u}), \end{equation} and \begin{equation} \boldsymbol{e}^+(\boldsymbol{u}) = \boldsymbol{S}(\boldsymbol{u}) \boldsymbol{\Lambda}^+(\boldsymbol{u}) \boldsymbol{S}^T(\boldsymbol{u}), \end{equation} where $\boldsymbol{\Lambda}^+$ is the diagonal matrix containing the positive eigenvalues $\lambda_i^+$, and $\boldsymbol{S}$ is the matrix containing the corresponding eigenvectors $\boldsymbol{s}_i$~\cite{wick_error-oriented_2017}. Dropping the dependencies in $\boldsymbol{u}$, the positive and negative stress of an isotropic material now read \begin{equation} \boldsymbol{\sigma}^+ = \lambda \langle \text{tr}(\boldsymbol{e}) \rangle_{+} \boldsymbol{I} + 2\mu \boldsymbol{e}^+, \end{equation} \begin{equation} \boldsymbol{\sigma}^- = \lambda \langle \text{tr}(\boldsymbol{e}) \rangle_{-} \boldsymbol{I} + 2\mu \boldsymbol{e}^-, \end{equation} where $\boldsymbol{I}$ is the second order identity tensor and ($\lambda$, $\mu$) are the Lamé coefficients. $\langle z \rangle_{\pm}$ designates the positive or negative ramp function of $z$, where $\langle z \rangle_{+} = \text{max}(0,z)$ and $\langle z \rangle_{-} = \text{min}(0,z)$. The energy functional using the energy split becomes \begin{equation} \begin{split} \label{AT1+split} \mathcal{E}_l(\boldsymbol{u},d) = & \int_{\Omega} \frac{1}{2}\Big((1-d)^2\boldsymbol{\sigma}^+(\boldsymbol{u}) + \boldsymbol{\sigma}^-(\boldsymbol{u})\Big):\boldsymbol{e}(\boldsymbol{u}) \, \text{d}\boldsymbol{x} \\ & + \frac{3G_c}{8}\int_{\Omega}\Big(\frac{d}{l}+l|\nabla d|^2 \Big) \text{d}\boldsymbol{x}. \end{split} \end{equation} \subsubsection{Irreversibility constraint} \label{irreversibility} Formulation \eqref{AT1+split} is set in a quasi-static regime, with dependency on time appearing only through the boundary conditions. However, the irreversibility condition found in \eqref{VP} implies an history dependency in the minimization problem. Introducing a discretization of the loading process through the pseudo-time steps $\Delta t^n = t^n - t^{n-1}$, and knowing the solution from the previous step, we look for a solution to the minimization problem at every time increment. Using the time discretization, $\dot{d}\geq 0$ can be approximated through a backward differentiation with \begin{equation} d^n \geq d^{n-1}. \end{equation} To avoid a cumbersome notation, we denote the solution of the actual increment $(\boldsymbol{u}^n,d^n)$ with $(\boldsymbol{u},d)$. The variational problem \eqref{VP} now contains 3 constraints, namely $d \geq 0$, $d \leq 1$ and $d \geq d^{n-1}$. With the degradation function chosen as quadratic, $d \leq 1$ is naturally respected~\hl{\mbox{\cite{miehe_phase_2010,kuhn_degradation_2015}}}. However, $d \geq 0$ and $d \geq d^{n-1}$ need to be imposed. Multiple options for enforcing the $d \geq d^{n-1}$ condition are available in the literature, such as \hl{the primal-dual active set method~\mbox{\cite{heister_primal-dual_2015}}}, the penalty method~\hl{\mbox{\cite{gerasimov_penalization_2019,miehe_thermodynamically_2010}}}, \hl{the Lagrange multiplier method~\mbox{\cite{mang_phase-field_2020}}}, the augmented Lagrangian method~\cite{wheeler_augmented-lagrangian_2014}, or the interior-point method~\cite{wambacq_interior-point_2021}. Here we adopt the simple quadratic penalty, as proposed by~\cite{gerasimov_penalization_2019} \begin{equation} \label{penalty} P = \frac{\gamma}{2} \int_{\Omega} \langle d - d^{n-1} \rangle_{-}^{2}\: \text{d}\boldsymbol{x}, \end{equation} where $\gamma$ is a penalty parameter and $d^{n-1}$ is the solution of the phase-field from the previous time increment. By taking $d^0 \geq 0$, the constraint $d \geq 0$ is simultaneously enforced. Adding the penalty term \eqref{penalty} to the energy functional \eqref{AT1+split} yields an unconstrained minimization problem which reads \begin{equation} \label{VPu} \boldsymbol{u},d = \textrm{arg}\,\textrm{min } \mathcal{E}_l(\boldsymbol{u},d) \end{equation} with the energy functional \begin{equation} \begin{split} \label{AT1+split+P} \mathcal{E}_l(\boldsymbol{u},d) = & \int_{\Omega} \frac{1}{2}\Big((1-d)^2\boldsymbol{\sigma}^+(\boldsymbol{u}) + \boldsymbol{\sigma}^-(\boldsymbol{u})\Big):\boldsymbol{e}(\boldsymbol{u}) \, \text{d}\boldsymbol{x} \\ & + \frac{3G_c}{8}\int_{\Omega}\Big(\frac{d}{l}+l|\nabla d|^2 \Big) \text{d}\boldsymbol{x} + \frac{\gamma}{2} \int_{\Omega} \langle d - d^{n-1} \rangle_{-}^{2}\: \text{d}\boldsymbol{x}. \end{split} \end{equation} This new problem is an approximation of \eqref{VP}, where the minimizers of \eqref{AT1+split+P} converge to the minimizers of \eqref{AT1+split} with $\gamma \rightarrow \infty$. Instead of increasing $\gamma$ until the Karush-Kuhn-Tucker (KKT) conditions are met, as one would typically do with a penalty method, we use the fixed optimal penalty parameter presented in~\cite{gerasimov_penalization_2019} \begin{equation} \gamma = \frac{G_c}{l}\frac{27}{64 \mathtt{TOL^2_{Ir}}}, \end{equation} where $\mathtt{TOL_{Ir}}$ is a chosen irreversibility tolerance. \hl{In this work, we use $\mathtt{TOL_{Ir}} = 0.01$ as proposed in~\mbox{\cite{gerasimov_penalization_2019}}}. Derived from the notion of optimal phase-field profile, this constant penalty coefficient was shown to lead to a good approximation of the original constrained problem~\cite{gerasimov_penalization_2019}. \subsubsection{Euler-Lagrange equations and finite element discretization} \label{section:ELd} We define the function spaces \hl{$\boldsymbol{\mathcal{V}} \coloneqq \{\boldsymbol{v} \in (H^1(\Omega))^\delta : \boldsymbol{v} = \boldsymbol{0} \text{ on } \Gamma_D \}$} and $\mathcal{W} \coloneqq \hll{\{ w \in H^1(\Omega) \}}$, with $H^1(\Omega)$ the Sobolev space. Applying directional derivatives towards $(\boldsymbol{u},d)$ to \eqref{AT1+split+P}, the Euler-Lagrange equations of problem \eqref{VPu} can be written in their weak form as~\cite{heister_primal-dual_2015,gerasimov_penalization_2019}: \begin{subequations} \label{EL} \begin{align} & \int_{\Omega} \Big( (1-d)^2\boldsymbol{\sigma}^+(\boldsymbol{u}) + \boldsymbol{\sigma}^-(\boldsymbol{u}) \Big):\boldsymbol{e}(\boldsymbol{v}) \, \text{d}\boldsymbol{x} = 0, \quad \forall \boldsymbol{v} \in \boldsymbol{\mathcal{V}}, \label{EL1}\\ & \int_{\Omega} -w(1-d) \boldsymbol{\sigma}^+(\boldsymbol{u}):\boldsymbol{e}(\boldsymbol{u}) \, \text{d}\boldsymbol{x} + \frac{3G_c}{8}\int_{\Omega} \Big( \frac{w}{l}+2l\nabla d \cdot \nabla w \Big) \text{d}\boldsymbol{x} \nonumber \\ & \quad + \gamma \int_{\Omega} w\langle d - d^{n-1} \rangle_{-}\: \text{d}\boldsymbol{x} = 0, \quad \forall w \in \mathcal{W}. \label{EL2} \end{align} \end{subequations} The equation system \eqref{EL} is usually discretized using a Galerkin finite element method \cite{heister_primal-dual_2015,borden_phase-field_2012,mang_phase-field_2020}. To this end, assuming a 2D polygonal domain, we partition $\Omega$ in a non-degenerate family of quadrilateral elements $\mathcal{Q}^h$, where $h$ is the average element edge size. Using the notation from~\cite{brenner_mathematical_2008}, we introduce the linear finite element space \begin{equation*} \mathcal{V}_h \coloneqq \{ v \in H^1(\Omega): \text{ $v|_Q$ is linear $\forall Q \in \mathcal{Q}^h$}\}. \end{equation*} The nodal basis functions of the vector space $\mathcal{V}_h$ are noted \begin{equation*} \{ \varphi_i : 1 \leq i \leq m \}, \end{equation*} where $m$ is the dimension of the finite element space. To approximate the vector field $\boldsymbol{u}$, and borrowing the deal.II convention~\cite{bangerth_assembling_2002}, we define the $2m$ vector shape functions \begin{align*} \boldsymbol{\phi}_0(\boldsymbol{x}) & = \begin{pmatrix} \varphi_0(\boldsymbol{x}) \\ 0 \end{pmatrix}, \\ \boldsymbol{\phi}_1(\boldsymbol{x}) & = \begin{pmatrix} 0 \\ \varphi_0(\boldsymbol{x}) \end{pmatrix}, \\ \boldsymbol{\phi}_2(\boldsymbol{x}) & = \begin{pmatrix} \varphi_1(\boldsymbol{x}) \\ 0 \end{pmatrix}\hll{,} \ldots \\ \boldsymbol{\phi}_{2m}(\boldsymbol{x}) & = \begin{pmatrix} 0 \\ \varphi_m(\boldsymbol{x}) \end{pmatrix}. \end{align*} Collecting the displacement and damage nodal coefficients in respectively $\boldsymbol{U} \in \mathbb{R}^{2m}$ and $\boldsymbol{D} \in \mathbb{R}^m$, the functions $(\boldsymbol{u},d)$ are now approximated with \begin{equation} \boldsymbol{u}_h(\boldsymbol{x}) = \sum_{j = 1}^{2m}\boldsymbol{\phi}_j(\boldsymbol{x})U_j, \quad d_h(\boldsymbol{x}) = \sum_{j = 1}^{m}\varphi_j(\boldsymbol{x}) D_j. \end{equation} Using the finite element approximations $\boldsymbol{u}_h \in \mathcal{V}_h \times \mathcal{V}_h$ and $d_h \in \mathcal{V}_h$, the discretized Euler-Lagrange equations can be written as the following residuals \begin{subequations} \label{ELd} \begin{align} R_i^u \coloneqq & \int_{\Omega} \Big( (1-d_h)^2\boldsymbol{\sigma}^+(\boldsymbol{u}_h) + \boldsymbol{\sigma}^-(\boldsymbol{u}_h) \Big):\boldsymbol{e}(\boldsymbol{\phi}_i) \, \text{d}\boldsymbol{x} = 0 \label{ELd1}\\ R_i^d \coloneqq & \int_{\Omega} -(1-d_h)\varphi_i\boldsymbol{\sigma}^+(\boldsymbol{u}_h):\boldsymbol{e}(\boldsymbol{u}_h) \, \text{d}\boldsymbol{x} + \frac{3G_c}{8}\int_{\Omega} \Big( \frac{\varphi_i}{l}+2l\nabla d_h \cdot \nabla \varphi_i \Big) \text{d}\boldsymbol{x} \nonumber \\ & \: + \gamma \int_{\Omega} \varphi_i\langle d_h - d_h^{n-1} \rangle_{-}\: \text{d}\boldsymbol{x} = 0. \label{ELd2} \end{align} \end{subequations} For all Newton-based solvers, the assembly of the Jacobian, or at least part of it, is necessary. The Jacobian associated to \eqref{ELd} can be written in its block structure as \begin{subequations} \label{Jacobian} \begin{align} J^{uu}_{ij} = \frac{\partial R_i^u}{\partial U_j} = & \int_{\Omega} \Big( (1-d_h)^2\boldsymbol{\sigma}^+(\boldsymbol{\phi}_j) + \boldsymbol{\sigma}^-(\boldsymbol{\phi}_j) \Big) :\boldsymbol{e}(\boldsymbol{\phi}_i) \, \text{d}\boldsymbol{x} \label{J1}\\ J^{ud}_{ij} = \frac{\partial R_i^u}{\partial D_j} = & \int_{\Omega} -2(1-d_h)\varphi_j\boldsymbol{\sigma}^+(\boldsymbol{u}_h):\boldsymbol{e}(\boldsymbol{\phi}_i) \, \text{d}\boldsymbol{x} \label{J2}\\ J^{du}_{ij} = \frac{\partial R_i^d}{\partial U_j} = & \int_{\Omega} -2(1-d_h)\varphi_i\boldsymbol{\sigma}^+(\boldsymbol{u}_h):\boldsymbol{e}(\boldsymbol{\phi}_j) \, \text{d}\boldsymbol{x} \label{J3}\\ J^{dd}_{ij} = \frac{\partial R_i^d}{\partial D_j} = & \int_{\Omega} \varphi_i\varphi_j\boldsymbol{\sigma}^+(\boldsymbol{u}_h):\boldsymbol{e}(\boldsymbol{u}_h) \text{d}\boldsymbol{x} + \frac{3G_c}{8}\int_{\Omega}2l\nabla \varphi_i \cdot \nabla \varphi_j \text{d}\boldsymbol{x} \nonumber \\ &\; + \gamma \int_{\Omega} \varphi_i\varphi_jH^-(d_h - d_h^{n-1}) \: \text{d}\boldsymbol{x}, \label{J4} \end{align} \end{subequations} with the general structure \begin{equation} \boldsymbol{J} = \begin{pmatrix} \boldsymbol{J}^{uu} & \boldsymbol{J}^{ud} \\ \boldsymbol{J}^{du} & \boldsymbol{J}^{dd} \end{pmatrix}. \end{equation} By $\boldsymbol{\sigma}^+(\boldsymbol{\phi}_j)$, we imply the directional derivative of $\boldsymbol{\sigma}^+(\boldsymbol{u}_h)$ towards $U_j$ as thoroughly detailed by~\cite{heister_primal-dual_2015}. Stemming from the derivative of the ramp function $\langle z \rangle_{-}$, $H^-(z)$ is the Heaviside function worth 1 if $z \leq 0$ and worth 0 otherwise. Finally, we denote the discretized Dirichlet conditions $\boldsymbol{\bar{U}}$. \subsection{Solution algorithms} \label{Solution algorithms} We present two algorithms commonly used to obtain a solution in phase-field fracture problems: the alternating minimization algorithm and the quasi-monolithic scheme. With these two methods, the Euler-Lagrange equations \eqref{EL} are treated as a set of non-linear equations and only a stationary point of \eqref{AT1+split+P} is obtained. The nature of the stationary point as either a local minimum, saddle point, or local maximum is unknown. \subsubsection{Alternating minimization algorithm} As observed in~\cite{bourdin_numerical_2000}, the functional \eqref{AT1} becomes convex in one field when the other is fixed. A stationary point can therefore be easily obtained with Newton's method if we solve towards one field at a time. Based on this fact, the alternating minimization algorithm, also often referred to as the staggered solver, consists in splitting the problem in a kinematic and a damage sub-problem and, as its name implies, alternatively solving them until convergence in both $\boldsymbol{u}$ and $d$. Since the solution is independent from the previous time steps, except of course for the penalty term, the alternating minimization algorithm is an implicit solver. Applied to the energy functional \eqref{AT1+split+P}, the staggered solver sequentially solves \eqref{ELd1} and \eqref{ELd2} using their respective Jacobian $J^{uu}$ \eqref{J1} and $J^{dd}$ \eqref{J4} through Newton's method. In this work, we adopt the alternating minimization algorithm as presented in~\cite{marigo_overview_2016,gerasimov_penalization_2019}, and described in Algorithm \ref{Stagg}. \begin{algorithm} \caption{Alternating minimization scheme} \label{Stagg} \hspace*{\algorithmicindent} \textbf{Input:} $\boldsymbol{U}^{n-1}$, $\boldsymbol{D}^{n-1}$, $\boldsymbol{\bar{U}}^n$ on $\Gamma_D$. \\ \hspace*{\algorithmicindent} \textbf{Output:} $\boldsymbol{U}^{n}$, $\boldsymbol{D}^{n}$. \begin{algorithmic}[1] \State Initialize $\boldsymbol{U}_0 \coloneqq \boldsymbol{U}^{n-1}$, $\boldsymbol{D}_0 \coloneqq \boldsymbol{D}^{n-1}$, $k = 0$. \While{$||\boldsymbol{R}^d(\boldsymbol{U}_k,\boldsymbol{D}_k)||_{L^\infty} > \mathtt{TOL}$} \State Find solution $\boldsymbol{D}_{k+1}$: $\hll{||\boldsymbol{R}^d(\boldsymbol{U}_k,\boldsymbol{D}_{k+1})||_{L^\infty}} \leq \mathtt{TOL}_{IN}$. \State Find solution $\boldsymbol{U}_{k+1}$: $\hll{||\boldsymbol{R}^u(\boldsymbol{U}_{k+1},\boldsymbol{D}_{k+1})||_{L^\infty}} \leq \mathtt{TOL}_{IN}$. \State $k \gets k+1$. \EndWhile \State $\boldsymbol{U}^{n} \gets \boldsymbol{U}_{k}$, $\boldsymbol{D}^{n} \gets \boldsymbol{D}_{k}$. \end{algorithmic} \end{algorithm} Different stopping criteria are used in the literature, see~\cite{wu_bfgs_2020} for a short review. Here, we use a residual-based convergence \hl{criterion, as shown in Algorithm \mbox{\ref{Stagg}}}. Since the two sub-problems are solved sequentially, it is necessary for the inner Newton methods to be solved to a smaller tolerance to reach the global convergence \hl{criterion}, implying the necessity of selecting $\texttt{TOL}_{IN} < \texttt{TOL}$~\cite{gerasimov_penalization_2019}. \subsubsection{Quasi-monolithic scheme} \label{Quasi-monolithic scheme} Based on the identification of the term $(1-d)^2\boldsymbol{\sigma}^+(\boldsymbol{u}):\boldsymbol{e}(\boldsymbol{u})$ as the one rendering the functional \eqref{AT1+split+P} non-convex, \hl{the idea of the quasi-monolithic scheme is to linearize the kinematic sub-problem using a fixed} $\tilde{d}$ instead of the unknown field $d$~\cite{heister_primal-dual_2015}. $\tilde{d}$ is taken as an extrapolation constructed from the solution of previous time steps, with $\tilde{d} \coloneqq \tilde{d}(d^{n-1},d^{n-2})$. \hl{To retain the coupling between the two fields, $\tilde{d}$ is inserted in lieu of $d$ only in equation \mbox{\eqref{EL1}}, rendering the kinematic sub-problem dependent of $\boldsymbol{u}$ only. The damage sub-problem is kept identical to \mbox{\eqref{EL2}}}. However, due to the extrapolation $\tilde{d}$, the quasi-monolithic scheme can be interpreted as a semi-implicit method, therefore explaining the numerical viscosity observed in~\cite{wick_error-oriented_2017}. Different types of extrapolations are used for $\tilde{d}$, such as the linear extrapolation appearing in the implementation available with~\cite{heister_primal-dual_2015} or the constant extrapolation described in~\cite{mang_phase-field_2020}. In fact, many extrapolation schemes could be developed and tested. However, formulation \eqref{AT1+split+P} has no dependency in time, implying that no guarantee can be made on the quality of a time-based extrapolation of $d$. By replacing the unknown phase-field with a heuristic prediction as done here, one could reasonably expect the performance of this method to be problem-dependent. To perform a fair but straightforward comparison between the different methods, we adopt the linear extrapolation, as used in~\cite{heister_primal-dual_2015,lee_phase-field_2018,wick_error-oriented_2017} and described in~\hl{\mbox{\cite{wick_multiphysics_2020}}} as \begin{equation} \tilde{d} = d^{n-1}\frac{t^n - t^{n-2}}{t^{n-1} - t^{n-2}} - d^{n-2}\frac{t^n - t^{n-1}}{t^{n-1} - t^{n-2}}. \end{equation} With the extrapolated scheme, the residual reads \begin{equation} \label{ResQM} \begin{split} R_i^u \coloneqq & \int_{\Omega} \Big( (1-\tilde{d}_h)^2\boldsymbol{\sigma}^+(\boldsymbol{u}_h) + \boldsymbol{\sigma}^-(\boldsymbol{u}_h) \Big) :\boldsymbol{e}(\boldsymbol{\phi}_i) \, \text{d}\boldsymbol{x} = 0 \\ R_i^d \coloneqq & \int_{\Omega} -(1-d_h)\varphi_i\boldsymbol{\sigma}^+(\boldsymbol{u}_h):\boldsymbol{e}(\boldsymbol{u}_h) \, \text{d}\boldsymbol{x} \\ & \: + \frac{3G_c}{8}\int_{\Omega} \Big( \frac{\varphi_i}{l}+2l\nabla d_h \cdot \nabla \varphi_i \Big) \text{d}\boldsymbol{x} + \gamma \int_{\Omega} \varphi_i\langle d_h - d_h^{n-1} \rangle_{-}\: \text{d}\boldsymbol{x} = 0 \end{split} \end{equation} with the Jacobian \begin{equation} \label{JacQM} \begin{split} J^{uu}_{ij} = \frac{\partial R_i^u}{\partial U_j} = & \int_{\Omega} \Big( (1-\tilde{d}_h)^2\boldsymbol{\sigma}^+(\boldsymbol{\phi}_j) + \boldsymbol{\sigma}^-(\boldsymbol{\phi}_j) \Big) :\boldsymbol{e}(\boldsymbol{\phi}_i) \, \text{d}\boldsymbol{x} \\ J^{ud}_{ij} = \frac{\partial R_i^u}{\partial D_j} = & \;0 \\ J^{du}_{ij} = \frac{\partial R_i^d}{\partial U_j} = & \int_{\Omega} -2(1-d_h)\varphi_i\boldsymbol{\sigma}^+(\boldsymbol{u}_h):\boldsymbol{e}(\boldsymbol{\phi}_j) \, \text{d}\boldsymbol{x} \\ J^{dd}_{ij} = \frac{\partial R_i^d}{\partial D_j} = & \int_{\Omega} \varphi_i\varphi_j\boldsymbol{\sigma}^+(\boldsymbol{u}_h):\boldsymbol{e}(\boldsymbol{u}_h) \text{d}\boldsymbol{x} + \frac{3G_c}{8}\int_{\Omega} 2l\nabla \varphi_i \cdot \nabla \varphi_j \text{d}\boldsymbol{x} \\ & + \gamma \int_{\Omega} \varphi_i\varphi_jH^-(d_h - d_h^{n-1}) \: \text{d}\boldsymbol{x} \end{split}. \end{equation} For every time step $t^n$, the solution $\boldsymbol{U} \coloneqq \{\boldsymbol{u}^n,d^n\}$ is obtained with the Newton method using the modified residual $\boldsymbol{R}$ \eqref{ResQM} and Jacobian $\boldsymbol{J}$ \eqref{JacQM}. In this case, the Newton method would consist in solving the linear system \begin{equation} \boldsymbol{J}_k \boldsymbol{\delta U}_k = -\boldsymbol{R}_k \end{equation} and updating the solution $\boldsymbol{U}_k$ through \begin{equation} \boldsymbol{U}_{k+1} = \boldsymbol{U}_k + \boldsymbol{\delta U}_k \end{equation} until the convergence \hl{criterion} is reached. Here, we use the residual-based convergence \hl{criterion} $||\boldsymbol{R}(\boldsymbol{U}_k)||_{L^\infty} \leq \mathtt{TOL}$. \section{New solution algorithms} \label{New solution algorithms} \subsection{A modified Newton method with inertia correction and energy line-search} When minimizing a function $\mathcal{E}(\boldsymbol{u})$, a positive definite Hessian, or Jacobian, guarantees the identified Newton direction $\boldsymbol{\delta u}_{k}$ to be one of descent. A descent direction implies the existence of a solution $\boldsymbol{u}_{k+1} \coloneqq \boldsymbol{u}_{k} + \alpha_k \boldsymbol{\delta u}_{k}$, with the step-size parameter $\alpha_k > 0$, such that $\mathcal{E}(\boldsymbol{u}_{k+1}) < \mathcal{E}(\boldsymbol{u}_{k})$. Therefore, if the Jacobian is positive definite and a line-search procedure is used to identify a satisfying $\alpha_k$, the convergence to a local minimum is theoretically guaranteed~\cite{nocedal_numerical_2006}. To preserve this convergence property when solving phase-field models, we propose to use a modified Newton method that ensures the positive definiteness of the Jacobian through inertia corrections, inspired by~\cite{wachter_implementation_2006}. The inertia of an $m \times m$ matrix is expressed with the triplet $(\chi^+,\chi^-,\chi^0)$, where $\chi^+$, $\chi^-$ and $\chi^0$ are respectively the number of positive, negative and null eigenvalues, counting the multiplicities. Consequently, the inertia of a positive definite Jacobian of size $m \times m$ should be $(m,0,0)$. Since the inertia is available as an output with symmetric indefinite linear solvers such as the ones found in the Intel® Math Kernel Library (MKL) and Harwell Subroutine Library (HSL), it suffices to verify that $\chi^+ = m$ before taking a step in the search direction. If the Jacobian is not positive definite, we correct it by adding multiples of the identity matrix, yielding the modified Newton step~\cite{nocedal_numerical_2006} \begin{equation} \label{modifiedNewton} (\boldsymbol{J}_k + \tau_k \boldsymbol{I}) \boldsymbol{\delta U}_k = -\boldsymbol{R}_k, \end{equation} where $\tau_k > 0$ is a scalar parameter and $\boldsymbol{I}$ is the identity matrix. To choose $\tau_k$, we adopt the inertia correction algorithm used in the optimization software IPOPT~\cite{wachter_implementation_2006}. The modified Newton method with inertia correction is presented in Algorithm~\ref{MN}. As described in Algorithm~\ref{MN}, we first attempt to obtain a search direction without correction. \hl{If an incorrect inertia is detected, a first small correction $\bar{\tau}>0$ is tested. If the correction is still insufficient, the correction is multiplied by $\kappa^+ > 1$ until all eigenvalues are positive. If a correction is needed in a subsequent iteration, the last used value of $\tau$ is reused as a starting point, with a slight decrease by $\kappa^- \in [0,1]$. $\bar{\tau}^{min} > 0$ and $\bar{\kappa}^+ > 1$ denote the smallest correction accepted and the increase used for the first iteration with a non-zero correction. For example, the default parameters used in IPOPT are $\kappa^+ = 8$, $\kappa^- = \frac{1}{3}$, $\bar{\kappa}^+ = 100$, $\bar{\tau} = 10^{-4}$, and $\bar{\tau}^{min} = 10^{-20}$~\mbox{\cite{wachter_implementation_2006}}.} \hl{As seen in \mbox{Algorithm~\ref{MN}}, the $\kappa^+$, $\kappa^-$, $\bar{\kappa}^+$, $\bar{\tau}$ and $\bar{\tau}^{min}$ parameters control the amplitude of the Jacobian regularization and the rapidity with which the amplitude is increased. Hence, they should be chosen to allow \mbox{Algorithm~\ref{MN}} to identify the $\tau_k$ rendering the modified Hessian positive definite through a minimum number of factorization, while still trying to minimize the amplitude of the modification made to the original Hessian. Since the inertia correction is a heuristic method, the $\kappa^+$, $\kappa^-$, $\bar{\kappa}^+$, $\bar{\tau}$ and $\bar{\tau}^{min}$ are indeed numerical parameters that could be tuned. However, as shown in \mbox{Section~\ref{Numerical results}}, significant and consistent gains in performance are obtained with this method without any tuning and by simply taking the default parameters of IPOPT.} Therefore, for every time step $t^n$, the solution $\boldsymbol{U} \coloneqq \{\boldsymbol{u}^n, d^n\}$ is obtained by identifying a search direction $\boldsymbol{\delta U}_k$ using Algorithm \ref{MN}, with residual $\boldsymbol{R}_k$ \eqref{ELd} and the full Jacobian \eqref{Jacobian}, and updating the solution $\boldsymbol{U}_k$ with \begin{equation} \boldsymbol{U}_{k+1} = \boldsymbol{U}_k + \alpha_k \boldsymbol{\delta U}_k \end{equation} until the convergence \hl{criterion} is reached. Once again, we use the residual-based convergence \hl{criterion} $||\boldsymbol{R}(\boldsymbol{U}_k)||_{L^\infty} \leq \mathtt{TOL}$. $\alpha_k \in [0,1]$ is identified through a standard Armijo backtracking line-search~\hl{\mbox{\cite{nocedal_numerical_2006}} applied to the energy functional~\mbox{\eqref{AT1+split+P}}, as described in Algorithm~\mbox{\ref{Armijo}} where $\rho \in [0,1]$ is the contraction factor}. The described modified Newton method presents many theoretical and numerical advantages over the solvers found in the phase-field literature. First, since the Jacobian is modified only when necessary, as opposed to the staggered and quasi-monolithic solvers, the modified Newton method preserves the theoretical quadratic convergence rate of the Newton method in as many time steps as possible. Once the Jacobian is modified, the convergence rate remains linear~\cite{nocedal_numerical_2006}. Note also that the corrections appear naturally within the method and, \hl{contrarily to the solvers proposed in~\mbox{\cite{farrell_linear_2017,storvik_accelerated_2021}}, no switch between algorithms is required}. Second, as opposed to methods relying only on the residual and Jacobian, the use of a line-search on the energy functional ensures that the solution is at least a local minimum. Altogether, these multiple advantages make the proposed modified Newton method a potentially highly efficient and robust fully monolithic solver for phase-field models. \begin{algorithm}[] \caption{Modified Newton method with inertia correction} \label{MN} \hspace*{\algorithmicindent} \textbf{Input:} $\boldsymbol{J}_k$, $\boldsymbol{R}_k$, $\tau_{k-1}$, $\kappa^+$, $\kappa^-$, $\bar{\kappa}^+$, $\bar{\tau}$, $\bar{\tau}^{min}$. \\ \hspace*{\algorithmicindent} \textbf{Output:} $\boldsymbol{\delta U}_k$, $\tau_{k}$. \begin{algorithmic}[1] \State Initialize $\tau^0 = 0$, $i = 0$. \State Factorize $(\boldsymbol{J}_k + \tau^0 \boldsymbol{I})$ and obtain the inertia $(\chi^+,\chi^-,\chi^0)$. \If{the modified Jacobian is not positive definite, i.e. $\chi^+ \neq m$} \If{$\tau_{k-1}$ = 0} \State Set $\tau^1 = \bar{\tau}$ \Else \State Set $\tau^1 = \text{max}(\bar{\tau}^{min},\kappa^- \tau_{k-1})$ \EndIf \State Factorize $(\boldsymbol{J}_k + \tau^1 \boldsymbol{I})$ and obtain the inertia $(\chi^+,\chi^-,\chi^0)$. \State $i \gets i+1$ \While{the modified Jacobian is not positive definite, i.e. $\chi^+ \neq m$} \If{$\tau_{k-1}$ = 0} \State Set $\tau^{i+1} = \bar{\kappa}^+ \tau^i$ \Else \State Set $\tau^{i+1} = \kappa^+ \tau^i$ \EndIf \State Factorize $(\boldsymbol{J}_k + \tau^{i+1} \boldsymbol{I})$ and obtain the inertia $(\chi^+,\chi^-,\chi^0)$. \State $i \gets i+1$ \EndWhile \EndIf \State Solve $(\boldsymbol{J}_k + \tau^i \boldsymbol{I}) \boldsymbol{\delta U} = -\boldsymbol{R}_k$ for $\boldsymbol{\delta U}$. \State $\boldsymbol{\delta U}_k \gets \boldsymbol{\delta U}$, $\tau_{k} \gets \tau^i$. \end{algorithmic} \end{algorithm} \begin{algorithm} \caption{\hl{Armijo backtracking line-search}} \label{Armijo} \hspace*{\algorithmicindent} \textbf{Input:} $\boldsymbol{U}_k$, $\boldsymbol{\delta U}_k$, $\rho$. \\ \hspace*{\algorithmicindent} \textbf{Output:} $\alpha_k$. \begin{algorithmic}[1] \State Initialize $\alpha^0 = 1$, $i = 0$. \While{$\mathcal{E}_l(\boldsymbol{U}_k + \alpha^i \boldsymbol{\delta U}_k) > \mathcal{E}_l(\boldsymbol{U}_k)$} \State Set $\alpha^{i+1} = \rho \alpha^i$. \State $i \gets i+1$. \EndWhile \State $\alpha_k \gets \alpha^i$. \end{algorithmic} \end{algorithm} \subsection{An improved quasi-monolithic scheme using an extrapolation correction loop} The quasi-monolithic scheme as described in Section~\ref{Quasi-monolithic scheme} is a semi-implicit method, implying that, depending on the step size, the solution can be delayed or completely inaccurate (see~\cite{wick_error-oriented_2017} for an example). The lag in the solution can be explained by the extrapolation $\tilde{d}$ underestimating the rapidly evolving damage field when too large time steps are used. Due to the absence of time continuity of the damage field, large time steps can cause the extrapolation to quickly diverge from the actual solution. The simplest strategy to lessen the lag induced by the extrapolation is to use uniformly refined time steps. On one hand, this method usually yields a more accurate solution, since, with the step size converging to zero, the time-based extrapolation can reasonably be expected to converge to the implicit solution. On the other hand, the uniformly refined time steps imply additional and unnecessary calculations when no crack is propagating. One could consider the use of a time adaptive scheme, but once again, the lack of continuity in time of the damage field hinders the potential robustness of such methods. To the best of our knowledge, no such time adaptive scheme is available for the quasi-monolithic scheme in the literature. Another strategy to reduce the lag in the evolution of the damage field, as proposed in~\cite{wick_multiphysics_2020}, is to use an additional loop in which the extrapolation is updated. The idea is that, by updating the extrapolation inside a single time step, $\tilde{d}$ should get closer and eventually converge to the actual damage solution $d$. Rather than using a constant and maybe insufficient number of updates, we propose to continue the iterating process until the damage field reaches a convergence \hl{criterion}. The solution is defined as converged when the updating of the extrapolation no longer influences the phase-field solution, within a certain tolerance, as \begin{equation} \label{time_conv} ||d_{k} - d_{k-1}||_{L^2} \leq \mathtt{TOL_{QM}}. \end{equation} \hl{The final quasi-monolithic method is detailed in Algorithm~\mbox{\ref{Quasi-mono}}. As described, for every time steps, a first extrapolation $\widetilde{\boldsymbol{D}}_{1}$ is constructed from the phase-field solution of the two previous time steps, $\boldsymbol{D}^{n-1}$ and $\boldsymbol{D}^{n-2}$. Using $\widetilde{\boldsymbol{D}}_{1}$, a first solution $\{\boldsymbol{U}_1, \boldsymbol{D}_1\}$ is computed solving the modified residual~\mbox{\eqref{ResQM}}. The extrapolation $\widetilde{\boldsymbol{D}}_{k+1}$ is then updated using the two most recent phase-field iterates, $\boldsymbol{D}_{k}$ and $\boldsymbol{D}_{k-1}$, and the solution $\{\boldsymbol{U}_k, \boldsymbol{D}_k\}$ re-calculated until the stopping criterion~\mbox{\eqref{time_conv}} is respected. Note that no additional precaution was taken to enforce $\boldsymbol{D}^n \leq 1$.} \hl{The proposed extrapolation correction loop is heuristic since $d$ has no regularity in time, but applying Algorithm~\mbox{\ref{Quasi-mono}} every time steps allows the semi-implicit quasi-monolithic scheme to converge to the implicit solution without a uniform time step refinement or pre-defined number of extrapolation correction, as shown in~\mbox{\ref{Appendix}}.} \begin{algorithm} \caption{Quasi-monolithic scheme with extrapolation correction loop} \label{Quasi-mono} \hspace*{\algorithmicindent} \textbf{Input:} $\boldsymbol{U}^{n-1}$, $\boldsymbol{D}^{n-1}$, $\boldsymbol{D}^{n-2}$, $\boldsymbol{\bar{U}}^n$ on $\Gamma_D$. \\ \hspace*{\algorithmicindent} \textbf{Output:} $\boldsymbol{U}^{n}$, $\boldsymbol{D}^{n}$. \begin{algorithmic}[1] \State Initialize $\boldsymbol{U}_0 \coloneqq \boldsymbol{U}^{n-1}$, $\boldsymbol{D}_{0} \coloneqq \boldsymbol{D}^{n-1}$, $\boldsymbol{D}_{-1} \coloneqq \boldsymbol{D}^{n-2}$, $k = 1$. \State Compute extrapolation $\widetilde{\boldsymbol{D}}_{1} \coloneqq f(\boldsymbol{D}_{0}, \boldsymbol{D}_{-1})$. \State Find solution $\{\boldsymbol{U}_{1},\boldsymbol{D}_{1}\}$: $\boldsymbol{R}(\boldsymbol{U}_1,\boldsymbol{D}_{1}, \widetilde{\boldsymbol{D}}_{1}) \leq \mathtt{TOL}$. \While{$||\boldsymbol{D}_{k} - \boldsymbol{D}_{k-1}||_{L^2} > \mathtt{TOL_{QM}}$} \State Compute extrapolation $\widetilde{\boldsymbol{D}}_{k+1} \coloneqq f(\boldsymbol{D}_{k}, \boldsymbol{D}_{k-1})$. \State Find solution $\{\boldsymbol{U}_{k+1},\boldsymbol{D}_{k+1}\}$: $\hll{||\boldsymbol{R}(\boldsymbol{U}_{k+1},\boldsymbol{D}_{k+1},\boldsymbol{\widetilde{D}}_{k+1})||_{L^\infty}} \leq \mathtt{TOL}$. \State $k \gets k+1$. \EndWhile \State $\boldsymbol{U}^{n} \gets \boldsymbol{U}_{k}$, $\boldsymbol{D}^{n} \gets \boldsymbol{D}_{k}$. \end{algorithmic} \end{algorithm} \section{Numerical results} \label{Numerical results} In this section, we present benchmarks representative of numerical experiments found in the phase-field literature. For all tests and for each algorithm, we compare the resultant crack paths, the force-displacement responses of the structure, the number of iterations required, and the computation time. We define an iteration as every time a correction is made to the solution $(\boldsymbol{u}^n,d^n)$. This definition implies that iterations do not have the same associated computational cost depending on the algorithm. Nevertheless, we consider the total number of iterations to inform on the performance of the algorithms when combined with the computation time. Only 2D geometries are considered and \hl{plane} strain is assumed. For every geometry, a local mesh refinement with a maximum size of $h = \frac{l}{5}$ is used in the expected fracture zone to avoid a numerical overestimation of the toughness~\cite{tanne_crack_2018,bourdin_variational_2008,mesgarnejad_validation_2015}. Pre-existing cracks are modeled as notches in the geometry and mesh. All meshes were generated using the commercial finite element software ABAQUS. The boundary conditions are strongly enforced by isolating the degrees of freedom subject to the Dirichlet condition and reducing the linear system. \hl{All computations are displacement-driven with constant displacement increments.} The integrals are approximated using the Gauss quadrature with four integration points. For all three methods, the convergence tolerance on the residual is set to $\mathtt{TOL} = 10^{-4}$, \hl{as in~\mbox{\cite{gerasimov_penalization_2019,gerasimov_line_2016,gerasimov_stochastic_2020}}}. The tolerance of the inner Newton methods of the alternating algorithm is set to $\mathtt{TOL}_{IN} = 10^{-5}$. In order to propose the fairest comparison with the quasi-monolithic scheme, the tolerance $\mathtt{TOL}_{QM}$ is adjusted for each experiment to ensure convergence to the implicit solution while minimizing the computation time. For the inertia correction scheme of the modified Newton solver, we take the default IPOPT parameters with $\kappa^+ = 8$, $\kappa^- = \frac{1}{3}$, $\bar{\kappa}^+ = 100$, $\bar{\tau} = 10^{-4}$ and $\bar{\tau}^{min} = 10^{-20}$ \cite{wachter_implementation_2006}. \hl{For the Armijo backtracking line-search used with the modified Newton solver, we take the contraction factor $\rho = \frac{1}{2}$. We recall that, as suggested in~\mbox{\cite{gerasimov_penalization_2019}}, an irreversibility tolerance of $\mathtt{TOL_{Ir}} = 0.01$ is taken for the penalty coefficient.} The finite element method and the numerical algorithms presented are implemented using the Julia language~\cite{bezanson_julia_2017}. For all three methods, linear systems are solved with the Intel® MKL Pardiso direct sparse solver. All computations are performed on a workstation with an Intel® Core(TM) i7-6700K CPU @ 4.00GHz and 32 GB RAM. \subsection{Single-edge notched plate under tensile loading} \label{SENP-tensile} \begin{figure}[] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=\textwidth]{TensileBenchmark_converted.pdf} \caption{} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=\textwidth]{MeshTensile.pdf} \caption{} \end{subfigure} \caption{Single edge notched plate under tension (SENP-tension) test. (a) Schematic of the geometry and boundary conditions. The lower edge of the plate is fixed (i.e. $\bar{u}_x = \bar{u}_y = 0$) while only a vertical displacement of $\bar{u}_y = 0.01$ mm is prescribed on the upper edge. The plate has unit thickness. All units are in mm. (b) Finite element discretization of the geometry.} \label{fig:Tensile} \end{figure} As a first test case, we consider the simple notched square plate under uniaxial tension (SENP-tensile). Widely used as a reference test in the literature~\cite{martinez-paneda_phase_2018,heister_primal-dual_2015,miehe_phase_2010,ambati_review_2015}, the geometry and loading generate unstable crack propagation. With an implicit scheme, the crack is expected to fully extend across the plate within a single time increment. Therefore, this test allows to assess the capacity of the algorithms to capture fast propagating cracks. The geometry, the boundary conditions and the mesh used for this test are presented in Figure~\ref{fig:Tensile}. The material properties selected are $E = 210$ GPa, $\nu = 0.3$, $G_c = 2.7$ N/mm and $l = 0.024$ mm. A total vertical displacement of 0.01 mm is applied in 50 time steps, implying uniform increments of $\Delta \bar{u} = 2\times 10^{-4}$ mm. The finite element mesh contains 6524 nodes and 6431 quadrilateral elements. A tolerance of $\mathtt{TOL}_{QM} = 0.01$ was found sufficient for the extrapolated scheme to converge to the implicit solution. Figure~\ref{fig:CrackTensile} shows the crack paths obtained with \hl{the alternating minimization, quasi-monolithic, and modified Newton algorithms} for the SENP-tensile tests. As depicted, all three algorithms converge to the expected solution, which in this case is a straight crack from the pre-crack to the right edge. Figure~\ref{fig:TensileFD} presents the corresponding force-displacement responses obtained with the solvers. The three methods yielded identical force-displacement curves, with a linear response until the peak load, followed by a sudden drop to zero at $\bar{u}_y = 6.2\times 10^{-3}$ mm. The results obtained with the three solvers confirm that they are able to capture the instantaneous propagation and that the quasi-monolithic scheme coupled with the extrapolation correction loop, as presented in Algorithm \ref{Quasi-mono}, converges to the implicit solution. Figure~\ref{fig:TensileIT} shows the total number of iterations required for each algorithm to converge with the evolution of the boundary conditions. At time step 31 ($\bar{u}_y = 6.2\times 10^{-3}$ mm), where the crack is propagating, the modified Newton solver requires only 257 iterations, as opposed to the 406 and 963 needed by the quasi-monolithic scheme and the alternating minimization algorithm, respectively. Table \ref{table:Tensile} summarizes the number of iterations and the computation time required by the three algorithms for the SENP-tensile test. \hl{As can be seen, the modified Newton method needed to correct the Hessian in only 30 iterations out of the 597 total iterations. Therefore, only 5 seconds was spent computing the inertia corrections. Furthermore, the decrease in the number of iterations obtained with the modified Newton solver yielded a reduction of the computation time by factors of 1.53 and 1.19, when compared to the staggered and extrapolated solvers. However, damage propagation is present in only one increment. Consequently, this benchmark does not fully expose the efficiency of the proposed method.} \begin{figure}[!tb] \centering \includegraphics[width=\textwidth]{CrackTensile.pdf} \caption{Comparison of the final crack patterns ($\bar{u}_y = 0.01$ mm) for the three studied algorithms on the undeformed geometry of the SENP-tension test. Crack paths obtained with the three methods are in agreement. The crack produced by the quasi-monolithic (b) scheme has initiated from below the notch, as opposed to the two other methods where the crack initiated above the notch. The difference remains however negligible.} \label{fig:CrackTensile} \end{figure} \begin{figure}[p!] \centering \includegraphics[width=0.65\textwidth]{TensileFD.pdf} \caption{Load-displacement curves obtained with the different solvers on the SENP-tension test. The three algorithms produce identical solutions.} \label{fig:TensileFD} \end{figure} \begin{figure}[p!] \centering \includegraphics[width=0.65\textwidth]{TensileIT.pdf} \caption{Total number of iterations required for the different algorithms to converge on the SENP-tension test. The modified Newton solver appears as the most efficient, while the extrapolated scheme also shows a reduction of the number of iterations when compared to the alternating minimization algorithm.} \label{fig:TensileIT} \end{figure} \begin{table}[p!] \centering \caption{Comparison of the iterations and computation time required for the studied algorithms to solve the SENP-tension benchmark. \hl{For the modified Newton method, the number of iterations requiring inertia correction (IC) and the total time spent computing the inertia corrections are indicated.}} \label{table:Tensile} \addtolength{\leftskip} {-2cm} \addtolength{\rightskip}{-2cm} \setlength{\tabcolsep}{6pt} \renewcommand{\arraystretch}{1.2} \begin{tabular}{cccccc} \hline & Max it. / inc. & Total it. & IC it. & Total time [s] & IC time [s] \\ \hline Alternating minimization & 963 & 1972 & - & 514 & - \\ Quasi-monolithic & 406 & 787 & - & 400 & - \\ Modified Newton & 257 & 597 & \hl{30} & 336 & \hl{5} \\ \hline \end{tabular} \end{table} \subsection{Single-edge notched plate under shear loading} \label{SENP-shear} \begin{figure}[!tb] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=\textwidth]{ShearBenchmark_converted.pdf} \caption{} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=\textwidth]{MeshShear.pdf} \caption{} \end{subfigure} \caption{Single edge notched plate under shear (SENP-shear) test. (a) Illustration of the geometry and boundary conditions. The lower edge of the plate is fixed (i.e. $\bar{u}_x = \bar{u}_y = 0$). \hl{A horizontal} displacement of $\bar{u}_x = 0.015$ mm is prescribed on the upper edge while maintaining $\bar{u}_y = 0$. The plate has a unit thickness. The units are in mm. (b) Finite element discretization.} \label{fig:Shear} \end{figure} The notched square plate under shear loading (SENP-shear) is another widely adopted test in the phase-field community since it allows the verification of the energy splitting method~\cite{heister_primal-dual_2015,miehe_phase_2010,gerasimov_penalization_2019,ambati_review_2015,bilgen_crack-driving_2019,dijk_strain_2020}. \hl{This test is also interesting when studying the efficiency of solvers since, once initiated, the crack propagation is stable.} From the latter numerical experiments found in the literature, it appears that only~\cite{gerasimov_penalization_2019} reported results for the $AT_1$ model. We used the same parameters to allow a comparison with the results from~\cite{gerasimov_penalization_2019}, with $E = 210$ GPa, $\nu = 0.3$, $G_c = 2.7$ N/mm and $l = 0.01$ mm. The geometry, the boundary conditions and the mesh are presented in Figure~\ref{fig:Shear}. A total horizontal displacement of 0.015 mm is applied in 50 equal increments. The mesh is made of 23341 nodes assembled in 23205 elements. In this case, a smaller tolerance of $\mathtt{TOL}_{QM} = 5\times 10^{-3}$ was required because a delay of the initiation and an oscillation of the reaction force were observed for a greater tolerance (results not shown). Figure~\ref{fig:CrackShear} shows the crack paths obtained for the SENP-shear test. As expected and consistently with the results found in the literature (see for example~\cite{ambati_review_2015}), the cracks initiate from the pre-crack and converge in a curved trajectory towards the lower right corner. The cracks yielded by the three solvers are virtually identical. Figure~\ref{fig:ShearFD} presents the load-displacement curves obtained with the three solvers for the SENP-shear test. The responses of the three solvers coincide and match with that of~\cite{gerasimov_penalization_2019}. The difference in peak force observed between the results of Figure~\ref{fig:ShearFD} and the results of~\cite{gerasimov_penalization_2019} could be explained by their use of $P_1$ triangular elements and a mesh size of $h = \frac{l}{4}$. The cumulative number of iterations required by the three solvers is presented in Figure~\ref{fig:ShearIT}. The efficiency of the modified Newton method is clearly illustrated, with a total number of iterations an order of magnitude lower than the quasi-monolithic and alternating schemes. We also note that the iteration totals required by the alternating and modified Newton methods are of the same order of magnitude than that of~\cite{wambacq_interior-point_2021}. Table~\ref{table:Shear} summarizes the computational performances of the three methods for the SENP-shear test. As presented, the total number of iterations required by the modified Newton solver is respectively 15 and 7 times lower when compared to the staggered and the extrapolated scheme. On our workstation, the iteration reduction meant a decrease in computation time by factors of respectively 9.25 and 6.40. \hl{Additionally, with the modified Newton scheme, the Hessian needed to be modified in only 13 iterations, implying that only 9 seconds, out of the total 1557, was spent computing the corrections.} Finally, one can observe from Figure~\ref{fig:ShearIT} that the quasi-monolithic scheme is as efficient as the monolithic modified Newton method prior to the damage propagation. However, the efficiency significantly decreases once the crack starts propagating. \begin{figure}[b!] \centering \includegraphics[width=\textwidth]{CrackShear.pdf} \caption{Comparison of the final crack paths at $\bar{u}_x = 0.015$ mm for all three studied methods on the undeformed geometry of the SENP-shear test. All three crack patterns are virtually identical.} \label{fig:CrackShear} \end{figure} \begin{figure}[p!] \centering \includegraphics[width=0.65\textwidth]{ShearFD.pdf} \caption{Load versus displacement obtained with the three solvers for the SENP-shear test. The three solutions coincide.} \label{fig:ShearFD} \end{figure} \begin{figure}[p!] \centering \includegraphics[width=0.65\textwidth]{ShearIT.pdf} \caption{Cumulative number of iterations required by the algorithms depending on the applied displacement in the SENP-shear test. The modified Newton solver clearly necessitates fewer iterations when the damage starts propagating.} \label{fig:ShearIT} \end{figure} \begin{table}[p!] \centering \caption{Comparison of the computational performances of the three algorithms on the SENP-shear test. \hl{For the modified Newton method, the number of iterations requiring inertia correction (IC) and the total time spent computing the inertia corrections are indicated.}} \label{table:Shear} \addtolength{\leftskip} {-2cm} \addtolength{\rightskip}{-2cm} \setlength{\tabcolsep}{6pt} \renewcommand{\arraystretch}{1.2} \begin{tabular}{cccccc} \hline Method & Max it. / inc. & Total it. & IC it. & Total time [s] & IC time [s] \\ \hline Alternating minimization & 3454 & 13654 & - & 14403 & - \\ Quasi-monolithic & 838 & 6349 & - & 9961 & - \\ Modified Newton & 324 & 897 & \hl{13} & 1557 & \hl{9} \\ \hline \end{tabular} \end{table} \hl{A mesh refinement study was performed to evaluate the robustness of the modified Newton solver with respect to the spatial discretization. Figure~\mbox{\ref{fig:ShearFD_refined}} compares the force-displacement solutions obtained with the modified Newton algorithm on the SENP-shear test for local mesh refinements in the expected fracture zone of $h = \{ \frac{l}{10}, \frac{l}{5}, \frac{2l}{5} \}$, implying respectively $h = \{ 0.001, 0.002, 0.004 \}$ mm. As seen in Figure~\mbox{\ref{fig:ShearFD_refined}}, the solution is slightly different with $h = 0.004$ mm. This behavior is expected since, as already mentioned, it is well-known that a mesh with $h \leq \frac{l}{5}$ should be used in the fracture zone. Figure~\mbox{\ref{fig:ShearIT_refined}} presents the total number of iterations required for the modified Newton algorithm to converge depending on the mesh refinement. It appears that the number of iterations slightly increases when refining the mesh. The increase in iterations can be partly explained by the initial crack propagation becoming more brutal with finer meshes, thus making the solution more difficult to obtain. Nevertheless, the increase in iterations required by the solver for finer meshes is negligible when compared to the gain in efficiency obtained over the staggered and extrapolated schemes.} \begin{figure}[p!] \centering \includegraphics[width=0.65\textwidth]{ShearFD_refined.pdf} \caption{\hl{Load versus displacement obtained with the modified Newton solver on the SENP-shear test for three levels of mesh refinement.}} \label{fig:ShearFD_refined} \end{figure} \begin{figure}[p!] \centering \includegraphics[width=0.65\textwidth]{ShearIT_refined.pdf} \caption{\hl{Cumulative number of iterations required by the modified Newton solver depending on the applied displacement in the SENP-shear test for three levels of mesh refinement.}} \label{fig:ShearIT_refined} \end{figure} \subsection{Three-point bending test} \begin{figure}[] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=\textwidth]{3PointBenchmark_converted.pdf} \caption{} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=\textwidth]{Mesh3Point.pdf} \caption{} \end{subfigure} \caption{Three-point bending of a notched beam test. (a) Schematic of the geometry and boundary conditions. The lower left node is fixed (i.e. $\bar{u}_x = \bar{u}_y = 0$), while the lower right node is only supported vertically and free in $x$ (i.e. $\bar{u}_y = 0$). A vertical displacement of $\bar{u}_y = 0.1$ mm is prescribed on the center node of the upper edge. The beam has a unit thickness. All units are in mm. (b) Finite element discretization of the geometry.} \label{fig:3Point} \end{figure} Let us now consider the classic three-point bending of a notched beam as presented in~\cite{ambati_review_2015}, \hl{where a mode-I crack first propagates brutally before growing in a stable manner}. The geometry, the loading and the discretization used are depicted in Figure~\ref{fig:3Point}. We adopt the same material properties as in~\cite{ambati_review_2015}, with $E = 20.8$ GPa, $\nu = 0.3$ and $G_c = 0.54$ N/mm. It should be noted, however, that the simulations performed in~\cite{ambati_review_2015} were made using the $AT_2$ model. In order to have equivalent mechanical properties for the $AT_1$ model, the characteristic length is converted using the solution for a homogeneous bar under uniaxial tension~\cite{tanne_crack_2018}. The conversion yields a characteristic length of $l = 0.101$ mm. A total displacement of 0.1 mm discretized in 50 equal increments is applied as illustrated in Figure~\ref{fig:3Point}. 11181 nodes and 11031 elements are used. As in the SENP-tension test, a tolerance of $\mathtt{TOL}_{QM} = 0.01$ was found to be sufficient for the quasi-monolithic scheme to converge to the implicit solution. The resulting crack patterns for the three-point bending test are shown in Figure~\ref{fig:Crack3Point}. As expected for a mode-I fracture, the cracks for all three solvers propagate from the notch to the upper edge in a straight line. Once again, they are virtually identical with only a negligible offset for the solution obtained through the modified Newton solver. Figure~\ref{fig:3PointFD} presents the load-deflection curves obtained for the three-point bending test with the three methods. The solutions are identical and in good agreement with that reported in~\cite{ambati_review_2015}. Figure~\ref{fig:3PointIT} presents the cumulative iterations required by the three solvers to obtain a solution to the phase-field problem. As illustrated, the quasi-monolithic and the modified-Newton methods have a similar efficiency before the propagation of damage. However, once the crack starts propagating, the modified Newton algorithm clearly outperforms the alternating and quasi-monolithic schemes. Table \ref{table:3Point} shows the total number of iterations, the maximum number of iterations in an increment and the calculation time required by the three algorithms. The modified Newton solver requires a maximum of only 193 iterations, while the extrapolated and alternating schemes require 565 and 989 iterations, respectively. This is a reduction in the number of iterations by factors of $\approx 3$ and $\approx 5$, which translates to an acceleration of the computation by factors of 3.33 and 4.18, respectively. \hl{Once again, we note that inertia corrections were used in only 70 iterations. The calculations associated to the identification of the correction represented $\approx 4\%$ of the computation time.} \begin{figure}[!tb] \centering \includegraphics[width=\textwidth]{Crack3Point.pdf} \caption{Final crack paths for the three methods on the notched beam under three-point bending for a total deflection of $\bar{u}_y = 0.1$ mm. The three cracks are closely similar, however, the crack produced by the modified Newton solver (c) initiated from the right-hand side of the notch, as opposed to the alternating minimization (a) and quasi-monolithic (b) schemes where the crack initiated to the left-hand side.} \label{fig:Crack3Point} \end{figure} \begin{figure}[p!] \centering \centering \includegraphics[width=0.65\textwidth]{3PointFD.pdf} \caption{Load-deflection curve of the three-point bending experiment for the different algorithms. Again, all three solutions coincide.} \label{fig:3PointFD} \end{figure} \begin{figure}[p!] \centering \includegraphics[width=0.65\textwidth]{3PointIT.pdf} \caption{Total number of iterations required by the methods depending on the deflection of the notched beam. Before the crack propagation, the quasi-monolithic scheme is as efficient as the modified Newton method. Once the crack starts propagating, the modified Newton method is clearly the most efficient solver.} \label{fig:3PointIT} \end{figure} \begin{table}[p!] \centering \caption{Computational performances of the different studied methods on the three-point bending test. \hl{For the modified Newton method, the number of iterations requiring inertia correction (IC) and the total time spent computing the inertia corrections are indicated.}} \label{table:3Point} \addtolength{\leftskip} {-2cm} \addtolength{\rightskip}{-2cm} \setlength{\tabcolsep}{6pt} \renewcommand{\arraystretch}{1.2} \begin{tabular}{cccccc} \hline Method & Max it. / inc. & Total it. & IC it. & Total time [s] & IC time [s] \\ \hline Alternating minimization & 989 & 3804 & - & 1969 & - \\ Quasi-monolithic & 565 & 1953 & - & 1567 & - \\ Modified Newton & 193 & 493 & \hl{70} & 471 & \hl{19} \\ \hline \end{tabular} \end{table} \subsection{L-shaped panel test} \begin{figure}[] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=\textwidth]{LShapedBenchmark_converted.pdf} \caption{} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=\textwidth]{MeshLShaped.pdf} \caption{} \end{subfigure} \caption{L-shaped panel test. (a) Representation of the geometry and boundary conditions. The lower edge is fixed (i.e. $\bar{u}_x = \bar{u}_y = 0$) and a vertical displacement of $\bar{u}_y = 1.0$ mm is prescribed as indicated on the figure. The panel has a thickness of 100 mm. The units are in mm. (b) Finite element discretization of the geometry.} \label{fig:LShaped} \end{figure} The concrete L-shaped panel with mixed mode crack propagation from~\cite{winkler_traglastuntersuchungen_2001} is another popular experiment used to evaluate and validate phase-field models~\cite{wu_bfgs_2020,mang_phase-field_2020,wick_error-oriented_2017,ambati_review_2015,mesgarnejad_validation_2015}. We adopt the geometry, loading and material properties from~\cite{mesgarnejad_validation_2015} for comparison purposes. The geometry, boundary conditions and mesh are presented in Figure~\ref{fig:LShaped}. The material parameters are $E = 21.85$ GPa, $\nu = 0.18$, $G_c = 0.095$ N/mm and $l = 3.125$ mm. A total vertical displacement of 1.0 mm is applied as described in Figure~\ref{fig:LShaped}. 50 equal increments are used to discretize the loading process. The finite element mesh is made of 48984 nodes and 48850 quadrilateral elements. A tolerance of $\mathtt{TOL}_{QM} = 5\times 10^{-3}$ is used for the results presented for the quasi-monolithic scheme, but as will be shown in the following, no convergence to the implicit solution was obtained. The crack paths obtained with the three solvers for the L-shaped panel tests are shown in Figure~\ref{fig:CrackLShaped}. The crack patterns resulting from the alternating minimization and the modified Newton solvers are identical and in agreement with results found in the literature, e.g.~\cite{wick_error-oriented_2017,ambati_review_2015,mesgarnejad_validation_2015}, where the crack first propagate with an angle and stabilizes in the horizontal direction. A small deviation is observed at the end of the crack path but the results still concur with experimentally observed fractures~\cite{winkler_traglastuntersuchungen_2001}. Figure~\ref{fig:LShapedFD} shows the load-displacement curves obtained for the L-shaped panel with the three algorithms. Again here, the alternating minimization and modified Newton solvers are in agreement. The response also concurs with the results obtained without the research for a global minimum in~\cite{mesgarnejad_validation_2015}. The difference in peak load can be explained by the absence of a tension/compression split and the crack initiation performed in~\cite{mesgarnejad_validation_2015}. The crack and the load-displacement curve obtained with the quasi-monolithic scheme are in agreement with neither the numerical results obtained from the two other methods nor the experimental results reported in~\cite{winkler_traglastuntersuchungen_2001}. Furthermore, the obtained crack path is physically questionable since the initiation angle does not agree with the maximum hoop stress criterion, stating that the crack should propagate in the direction maximizing the opening stress~\cite{erdogan_crack_1963}. This error can be attributed to the extrapolation correction loop, which in the present case appears to have significantly influenced the solution. However, either no convergence to the implicit solution or no convergence to a stationary point was obtained with different tolerances $\mathtt{TOL}_{QM}$ or different uniform time refinements. Figure~\ref{fig:LShapedIT} presents the performance of the three algorithms for the L-shaped panel test, although the results for the extrapolated scheme should be interpreted carefully since the method did not converge to the same solution. As can be seen, the final total iterations required by the modified Newton solver is lower than the alternating minimization algorithm by more than 10 times. Table~\ref{table:LShaped} summarizes the performances of the three methods for the L-shaped panel test. As noted in Table~\ref{table:LShaped}, a staggering number of iterations was required by the alternating minimization algorithm to solve increment 14 ($\bar{u}_y = 0.28$ mm). In comparison, the modified Newton solver required 26 times less iterations for the same increment. \hl{Nevertheless, the 2618 iterations of the modified Newton solver for this time step remain large. Additionally, 2113 iterations required inertia corrections, representing approximately $19\%$ of the total computation time. The high computational cost for the three solvers can be explained by the sudden propagation of a large crack in increment 14 and possibly ill-conditioned systems. However, the conditioning of the systems was not further investigated. Regardless, an important acceleration of the computation time by a factor of $\approx 11.9$ was still observed with the modified Newton solver.} \begin{figure}[!tb] \centering \includegraphics[width=\textwidth]{CrackLShaped.pdf} \caption{Crack paths obtained for the three algorithms after applying a total vertical displacement of $\bar{u}_y = 1.0$ mm. The cracks obtained with the alternating algorithm (a) and the modified Newton method (c) are identical. The solution produced by the extrapolated scheme (b) appears to be incorrect. The undeformed geometry is shown.} \label{fig:CrackLShaped} \end{figure} \begin{figure}[p!] \centering \centering \includegraphics[width=0.63\textwidth]{LShapedFD.pdf} \caption{Load-displacement curves resulting from all three methods on the L-shaped panel test. The reaction obtained with the staggered and modified Newton solvers are identical. The response obtained with the quasi-monolithic scheme does not agree with the solutions from the two other methods.} \label{fig:LShapedFD} \end{figure} \begin{figure}[p!] \centering \includegraphics[width=0.63\textwidth]{LShapedIT.pdf} \caption{Cumulative number of iterations required by the different methods to solve the L-shaped panel test. The modified Newton solver requires more than 10 times less iterations than the alternating method. The iterations reported for the quasi-monolithic scheme should be interpreted carefully since its solution did not converge to the solution of the other two methods.} \label{fig:LShapedIT} \end{figure} \begin{table}[p!] \centering \caption{Computational performances of the methods investigated on the L-shaped panel benchmark. \hl{For the modified Newton method, the number of iterations requiring inertia correction (IC) and the total time spent computing the inertia corrections are indicated.}} \label{table:LShaped} \addtolength{\leftskip} {-2cm} \addtolength{\rightskip}{-2cm} \setlength{\tabcolsep}{6pt} \renewcommand{\arraystretch}{1.2} \begin{tabular}{cccccc} \hline Method & Max it. / inc. & Total it. & IC it. & Total time [s] & IC time [s] \\ \hline Alternating minimization & 68442 & 87706 & - & 198377 & - \\ Quasi-monolithic & 7093 & 17117 & - & 62697 & - \\ Modified Newton & 2618 & 3743 & \hl{2113} & 16668 & \hl{3090} \\ \hline \end{tabular} \end{table} \subsection{Discussion of the results} We recall that the alternating minimization algorithm, the quasi-monolithic scheme and the modified Newton method all used the same numerical implementation and treatment of the irreversibility condition. The difference remained in the algorithm used to obtain a stationary point or local minimum. The benchmarking on the four tests, selected from the phase-field literature, showed that both the extrapolated scheme and the modified Newton method offered an increase in computational efficiency, when compared to the staggered algorithm. However, once damage started propagating, the semi-implicit extrapolated scheme required additional correction to converge to the implicit solution. Consequently, the modified Newton method was found to be, by far, the most efficient solver. For example, on the SENP-shear test, the modified Newton solver required up to 11 and 3 times less iterations by increment than the alternating minimization and quasi-monolithic algorithms, respectively. For the L-shaped panel test, the increase in efficiency obtained with the modified Newton solver implied a decrease in computation time by a factor of 12 over the staggered solver. The alternating minimization algorithm remains a powerful and versatile method since it can be applied to non-variational models and implemented using a variational inequality solver, like reported in~\cite{marigo_overview_2016,tanne_crack_2018}. The performance of the extrapolated scheme can probably be enhanced with locally refined time steps and a well-tuned extrapolation. It can also be applied to non-variational formulation. \hl{Nevertheless}, convergence problems were encountered with the quasi-monolithic scheme, as noted for the L-shaped panel test. It is possible that the preconditioned GMRES solver reported in~\cite{wick_modified_2017} would improve the method. The numerical parameters appearing in the inertia correction algorithm of the modified Newton method could also be tuned. \hl{However, it was shown for the first three benchmarks that only very few iterations required inertia correction and that the calculation of the correction represented at most 4\% of the total computational cost. Furthermore, the results of the four tests clearly exhibit that, when using a variational formulation and enforcing the irreversibility condition with a quadratic penalty, the modified Newton solver significantly outperforms the alternating minimization and quasi-monolithic algorithms for quasi-static brittle fracture without requiring any tuning.} Finally, as already mentioned, convergence issues were sporadically observed with the quasi-monolithic scheme and a surprisingly high number of iterations were necessary for the three solvers on the L-shaped panel test. The latter issues are symptomatic of ill-conditioned non-linear systems and could be attributed to the quadratic penalty term used to enforce the irreversibility condition, even if the optimal penalty parameter from \cite{gerasimov_penalization_2019} was used. As presented in Section \ref{irreversibility}, other methods of enforcing the irreversibility condition are available in the literature. Now that an implicit monolithic solver has been identified, the benchmarking of the schemes used to enforce the $\dot{d} \geq 0$ constraint could allow the identification of a method reducing the issues associated to bad conditioning and minimizing the computational cost associated to the solution of phase-field models. \section{Conclusion} \label{Conclusions} A robust, efficient and straightforward solver is still lacking the variational phase-field fracture literature. In an attempt to fill this gap, we proposed a fully monolithic solver based on a modified Newton method with inertia correction and an energy line-search. Additionally, we augmented the quasi-monolithic algorithm with an extrapolation correction loop controlled by a damage-based criterion. Although not perfect, the modified quasi-monolithic scheme allowed us to compare its performance with the alternating algorithm and the modified Newton solver. Through the four test cases presented involving different modes of propagation and initiation, we showed the modified Newton solver to be robust and more efficient than the alternating minimization algorithm and the quasi-monolithic scheme. More precisely, the proposed monolithic solver was shown to be up to $\approx 12$ and $\approx 6$ times faster than the staggered and extrapolated schemes. Furthermore, the performance of the monolithic method did not appear to be problem-dependent, requiring no parameter adjustment, and showing consistent efficiency gains across the test cases. Additional work can still be done to enhance the performance of phase-field solvers. A study concerning the identification of numerical parameters maximizing the efficiency of the modified Newton solver could be performed. As suggested in the discussion, the benchmarking of the methods used to enforce the irreversibility condition could also help further reduce the computational cost of the phase-field method. However, the combination of the modified Newton solver with an adaptive mesh technique could already facilitate the application of phase-field models to more complex structure and with sophisticated constitutive laws. \section*{Acknowledgements} We acknowledge the support of the Natural Sciences and Engineering Research Council of Canada (NSERC) and the Fonds de recherche du Québec - Nature et technologies (FRQNT).
{'timestamp': '2021-09-15T02:30:28', 'yymm': '2109', 'arxiv_id': '2109.05373', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05373'}
arxiv
\section{Introduction}\label{sec:introduction} Music source separation (MSS) is a task to separate audio mixtures into individual sources such as vocals, drums, accompaniment, etc. MSS is an important topic for music information retrieval (MIR) since it can be used for several downstream MIR tasks including melody extraction \cite{salamon2014melody}, pitch estimation \cite{durrieu2011musically}, music transcription \cite{benetos2018automatic}, music remixing \cite{pons2016remixing}, and so on. MSS also has several direct applications such as Karaoke and music remixing. MSS methods can be categorized into signal processing based methods and neural network based methods. Several methods have been proposed for source separation such as non-negative matrix factorizations (NMFs)~\cite{lee1999learning}. NMF decomposes a spectrogram into dictionaries and activations, and separated sources can be obtained by multiplying activations with different dictionaries. Sparse coding was used in \cite{plumbley2009sparse}, where audio signals are transformed into sparse representations for source separation. Independent component analysis (ICA) was used in \cite{davies2007source} by assuming that source signals are statistically independent. Other unsupervised source separation methods include modeling average harmonic structures in \cite{duan2008unsupervised}. Recently, neural network based methods became popular and have achieved state-of-the-art results in the MSS task. Those models include fully connected neural networks \cite{xu2014regression}, recurrent neural networks \cite{naithani2017low, uhlich2017improving}, convolutional neural networks \cite{jansson2017singing, chandna2017monoaural, stoter2019open, takahashi2018mmdenselstm, hennequin2020spleeter, liu2020channel, hu2020dccrn}, and time-domain separation models \cite{luo2019conv, lluis2018end, defossez2019music, stoller2018wave}. First, several previously introduced MSS systems perform in the time-frequency domain and have achieved the state-of-the-art performance. However, many conventional spectrogram-based systems do not estimate the phases of separated sources \cite{jansson2017singing, chandna2017monoaural, stoter2019open, takahashi2018mmdenselstm, hennequin2020spleeter} and it upper bounds performance of MSS systems as we will show in this paper. Recently, several works were proposed to estimate the phases of clean sources. For example, PhaseNet \cite{takahashi2018phasenet} treats the phase estimation as a phase classification problem, and PHASEN \cite{yin2020phasen} estimates the phase of clean sources using a separate neural network. Complex ideal ratio masks (cIRM) \cite{choi2018phase, wang2018supervised, tan2019complex} were also used for MSS. However, directly predicting the real and imaginary parts of cIRMs can be difficult, because the real and imaginary parts are sensitive to signal shifts in the time domain. In this paper, we propose to decouple the magnitude and phase for estimating cIRMs, which increases the performance of the source separation systems. We also elaborately design the magnitude estimation submodule to increase the upper bound of MSS systems. Second, several magnitude or complex mask-based methods \cite{hu2020dccrn} usually limit the magnitude of masks to 1. Based on our analysis, this limits the upper bound of the performance of MSS systems. In this work, we observe that 22\% time-frequency bins in the cIRM have magnitudes larger than 1. To predict magnitudes with cIRMs larger than 1, we propose to combine the predictions of mask and spectrogram where the spectrogram term is a residual component to complement the mask prediction term. Therefore, we combine the advantage of mask and linear spectrogram based methods. All of mask magnitudes, and spectrograms and phases are learnt by a neural network. Third, we show that the previous UNets \cite{jansson2017singing, hennequin2020spleeter, hennequin2020spleeter, hu2020dccrn} with up to tens of layers have limited separation results in MSS. We show that the depth of neural networks are important for the MSS task. In this work, we propose a deep residual UNet with 143 layers. We propose using residual encoder blocks, residual intermediate layers, and residual decoder blocks to build the 143-layer residual UNet. We show that deep architectures significantly increase the MSS performance. This paper is organized as follows. Section 2 introduces previous neural network based source separation systems and their limitations. Section 3 introduces our proposed system including the estimation of cIRMs and deep residual UNet. Section 4 shows experimental results and Section 5 concludes this work. \section{Backgrounds}\label{sec:background} In this paper, we denote the time-domain signal of a mixture and a clean source as $ x \in \mathbb{R}^{L} $ and $ s \in \mathbb{R}^{L} $, respectively, where $ L $ is the number of samples of the signal. Their short-time Fourier transforms (STFTs) are denoted as $ X \in \mathbb{R}^{T \times F} $ and $ S \in \mathbb{R}^{T \times F} $, respectively. $ T $ and $ F $ correspond to the number of frames and frequency bins. Next, we describe several source separation methods. \subsection{Approach 1: Direct Magnitude Prediction} \label{subsec:direct_pred} In direct prediction approaches, a MSS system directly learns a mapping from $ |X| $ to $ |S| $, i.e., $\hat{|S|} = f(|X|)$. Here, $ f $ can be any function approximator, such as a neural network of the fully connected, convolutional or recurrent types. Typically, a direct prediction method does not estimate the phases of separated sources. Instead, the phases of mixture is used to recover the STFT of separated sources: \begin{equation} \label{mask} \hat{S} = |\hat{S}| e^{j \angle X}, \end{equation} \noindent where $ \angle X \in [-\pi, \pi]^{T \times F} $ is the phase of $ X $. Finally, we apply an inverse STFT $ \mathcal{F}^{-1} $ on $ \hat{S} $ to obtain the separated waveform $ \hat{s} = \mathcal{F}^{-1}(\hat{S}) $. \subsection{Approach 2: Magnitude Mask} \label{subsec:mag_mask} In magnitude mask-based approaches, in order to perform source separation, a system predicts a mask, $ |\hat{M}| \in \mathbb{R}_{\geq 0}^{T \times F} $, that is applied to the input spectrogram element-wisely. \begin{equation} \label{eq:mask} \hat{|S|} = |\hat{M}| \odot |X|, \end{equation} The values of $\hat{M}$ can be continuous in the case of using ideal ratio masks (IRMs). The range of IRMs is often bounded between $[0, 1]$, assuming that the magnitudes of individual sources are smaller than the magnitudes of mixture. Furthermore, the magnitude is assumed to be either 0 or 1 in the case of ideal binary mask (IBM). Similar to direct magnitude prediction, in magnitude mask-based methods, the phase of original mixture is used as an approximation of the phase of the separated sources. \begin{figure}[t] \centering \centerline{\includegraphics[width=\columnwidth]{figs/mask_demo.pdf}} \caption{Illustrations of a source signal $ s $, a noise $ n $, and mixture $ x $ on a complex plain. (a) is an example when $ |M(t, f)| $ smaller than 1 and (b) is an example when $ |M(t, f)| $ larger than 1.} \label{fig:cIRM} \end{figure} \begin{table*}[t] \centering \caption{The empirical upper bounds of MSS systems on MUSDB18. `acc.' indicates accompaniment. On the top row, numbers indicate the limit of the magnitude masks.} \label{table:upper_bound} \begin{tabular}{*{12}{c}} \toprule & Mixture & IBM & IRM (1) & IRM (inf) & cIRM (1) & cIRM (2) & cIRM (5) & cIRM (10) & cIRM (inf) \\ \midrule vocals & -5.69 & 10.59 & 10.04 & 10.42 & 19.84 & 31.02 & 41.04 & 47.62 & 54.50 \\ acc. & -5.68 & 16.10 & 15.31 & 15.97 & 26.54 & 37.62 & 47.33 & 53.51 & 60.63 \\ bass & -6.36 & 7.17 & 6.05 & 6.07 & 17.99 & 27.88 & 37.86 & 44.30 & 54.12 \\ drums & -4.30 & 8.75 & 8.03 & 8.61 & 19.10 & 30.38 & 39.91 & 46.45 & 56.08 \\ other & -4.92 & 8.20 & 7.28 & 7.37 & 18.97 & 28.91 & 39.08 & 45.64 & 56.00 \\ \bottomrule \end{tabular} \end{table*} \begin{figure*} \centerline{ \includegraphics[width=\textwidth]{figs/cIRMs.pdf}} \caption{cIRMs of vocals, accompaniment, bass, drums, other, and all sources, on the complex 2D plain. Unit circles are drawn in red.} \label{fig:cIRMs} \end{figure*} \subsection{Approach 3: Complex Mask}\label{subsec:comp_mask} Accurate phase estimation becomes critical as the performance of the systems in Section~\ref{subsec:direct_pred} and \ref{subsec:mag_mask} has improved. Because of that, several works were proposed recently to take the phase estimation into consideration in the model. One ambitious approach is to directly predicting the complex STFT, as an extension of the direct magnitude prediction towards phase \cite{tan2019complex}. However, accurate prediction of a complex STFT is challenging because the estimation of real and imaginary parts of a complex STFT is more difficult than the estimation of the magnitude. As an alternative, many methods have been introduced to predict complex masks of mixture STFT~\cite{wang2018supervised, tan2019complex, choi2018phase}. In PhaseNet \cite{takahashi2018phasenet} and PHASEN \cite{yin2020phasen}, the authors proposed to predict the phases of signals independently from the magnitudes. \subsection{Out-of-Phase and Masks } In this work, we adopt cIRM-based methods for source separation due to their superior performance in phase estimation. A complex mask $ M \in \mathbb{C}^{T \times F} $ is calculated by: \begin{equation} \label{eq:cIRM} \begin{split} M & = S / X \\ & = \frac{S_{r} + i S_{i}}{X_{r} + i X_{i}} \\ & = \frac{S_{r}X_{r} + S_{i}X_{i} + i(S_{i}X_{r} - S_{r}X_{i})}{X_{r}^{2} + X_{i}^{2}}, \end{split} \end{equation} \noindent where $ X_{r} $, $ S_{r} $ are real parts of $ X $ and $ S $ respectively, and $ X_{i} $, $ S_{i} $ are imaginary parts of $ X $ and $ S $ respectively. The perfect separation of $ S $ from $ X $ can be obtained by: \begin{equation} \label{eq:mask_mul} \begin{split} S & = MX \\ & = |M||X|e^{j (\angle M + \angle X)}. \end{split} \end{equation} \noindent Equation (\ref{eq:mask_mul}) shows that the separation of $ S $ from $ X $ includes a magnitude scaling and a phase rotation operation. The magnitude of cIRM ($ |M| $) controls how much the magnitude of $ X $ should be scaled, and the angle of cIRM ($ \angle M $) controls how much the angle of $ X $ should be rotated. We now introduce an additive noise model, i.e., $ X = S + N $, which is illustrated in Fig. \ref{fig:cIRM}. Here, we focus on each time-frequency bin of STFTs of source, noise, and mixture ($ S(t, f) $, $ N(t, f) $, and $ X(t,f) $, respectively). Fig. \ref{fig:cIRM} (a) shows an example where the magnitude of cIRM $ |M(t, f)| $ is smaller than 1. This is modelled well in the existing methods where the ranges of complex mask is bound to $[0, 1]$. However, as illustrated in Fig.~\ref{fig:cIRM}~(b), $ |M(t, f)| $ can be larger than 1. As in the figure, this may happen when $S(t, f)$ and $N(t, f)$ are out of phase, since that makes the magnitude of mixture to be smaller than that of (individual) signal. \subsection{Empirical analysis of the effect of bounded magnitude mask}\label{subsec:empirical_analysis} In this section, we empirically investigate the upper bound of the performance when the magnitude mask is bounded to be $< 1$, the common assumption in many previous methods. We use signal-to-distortion ratio (SDR) \cite{vincent2006performance} as an evaluation metric, which is defined as follow: \begin{equation} \label{eq:sdr} SDR(s, \hat{s}) = 10 \text{log}_{10} \frac{|| s ||^{2}}{|| \hat{s} - s ||^{2}}. \end{equation} \noindent A higher SDR indicates better separation results, and vice versa. Ideally, a perfect separation will lead to infinite SDR. We evaluate the upper bound of systems on the vocals, accompaniment, bass, drums and other instruments from the MUSDB18 dataset \cite{rafii2017musdb18}. The first column of Table \ref{table:upper_bound} shows the SDRs of using the mixture without separation as separated sources. The second column (IBM) shows the upper bound of the performance when IBMs are used. According to the third column (IRM (1)), using IRMs whose magnitudes are bounded in [0, 1] has slightly lower upper bounds compared to those of IBM. IRM uses the phases of mixture but not the phases of clean sources for separating sources so the upper bound SDR is limited. Unbounded IRM (IRM (0, inf), the fourth column) shows a small improvement over bounded IRM, but not significantly. Compared to IBM, IRM (1) and IRM (inf), the five cIRM columns show that the upper bounds are significantly higher when correct phase information is used. The upper bounds of cIRM (1) is higher than IRM (1) by around 10~dB. The improvement within cIRMs is also dramatic -- only by increasing the limit from cIRM (1) to cIRM (2), the upper bounds increase by more than 9.89~dB for all the instruments. When magnitude mask is unbounded, the SDR of cIRM (inf) is infinite in theory. Considering the numerical stability when calculating SDRs, we add a small $ \epsilon $ to the denominator of (\ref{eq:sdr}). We observed the SDRs of cIRM (inf) are higher than 50~dB for all the instruments. \subsection{Distribution of cIRMs} In this section, we visualize the distribution of cIRMs to show that there are much space to improve previous MSS systems. Fig. \ref{fig:cIRMs} shows the cIRMs of vocals, accompaniment, bass, drums, other and all sources. The horizontal and vertical axes show the real and imaginary parts of cIRMs calculated by (\ref{eq:cIRM}), where each point in Fig. \ref{fig:cIRMs} corresponds to a $ M(t,f) $. The unit circle shown in Fig. \ref{fig:cIRMs} corresponds to masks with magnitude values equal to 1. Fig \ref{fig:cIRMs} from left to right shows the cIRM distribution of vocals, accompaniment, bass, drums, other instruments, and all sources. It can be seen that there are many cIRMs that having magnitudes larger than 1. The ratio of cIRMs have magnitudes larger than 1 for vocals, accompaniment, bass, drums and others are 20.3\%, 34.5\%, 6.1\%, 26.9\% and 13.9\% respectively. Along with the analysis in Section~\ref{subsec:empirical_analysis}, this observation motivates our work to extend the bounded mask estimation methods to unbound mask estimation methods. Fig. \ref{fig:cIRMs} also shows that, the phases of cIRMs distribute evenly in all directions. However, spectrogram-based methods assume that the phases of cIRMs are all 0. This observation further justifies to predict the phases in a MSS system. \section{Proposed System} In this section, we propose a MSS system that incorporates phase estimation that is based on the proposed decoupling of magnitude and phase (Section~\ref{section:decoupling}). Furthermore, to overcome the limit of bounded magnitude mask as discussed in Section~\ref{sec:background}, we propose a modification to extend the mask estimation method that allows the magnitude of the resulting mask be larger than~1 (Section~\ref{section:attention}). Finally, we propose a deep Residual UNet with 143 layers, which is the first MSS architectures that is deeper than a hundred layers (Section~\ref{subsec:verydeep}). All the proposed systems are trained with a L1-loss that is computed on the waveform domain as illustrated in Figure~\ref{fig:resunet}. \subsection{Decoupling Magnitude and Phase for cIRM Estimation}\label{section:decoupling} Unlike previous works that directly predict real and imaginary parts of masks \cite{choi2018phase, hu2020dccrn}, we propose to decouple the magnitude and phase estimation for MSS so that we can optimize their designs separately. We denote the complex mask to estimate as $ \hat{M} \in \mathbb{C}^{T \times F} $. As a part of the solution, our system outputs a bounded magnitude mask $ \hat{M}_{\text{mag}} \in \mathbb{R}^{T \times F} $ whose value is in $[0, 1]$. In practice, it is implemented by applying sigmoid function. Our system also outputs two more tensors, $ \hat{P}_{\text{r}} \in \mathbb{R}^{T \times F} $ and $ \hat{P}_{\text{i}} \in \mathbb{R}^{T \times F} $. Here, $ \hat{P}_{\text{r}} $ and $ \hat{P}_{\text{i}} $ are real and imaginary parts of $ \hat{M} $, respectively. Then, instead of calculating the angle $ \angle \hat{M} $ directly, we calculate its cosine value $cos \angle \hat{M}$ and sine value $sin \angle \hat{M}$ using $\hat{P}_{\text{r}}$ and $\hat{P}_{\text{i}}$ as follows: \begin{equation} \label{eq:cos_sin} \begin{split} cos \angle \hat{M} & = \hat{P_{\text{r}}} / \sqrt{\hat{P_{\text{r}}}^2 + \hat{P_{\text{i}}}^2} \\ sin \angle \hat{M} & = \hat{P_{\text{i}}} / \sqrt{\hat{P_{\text{r}}}^2 + \hat{P_{\text{i}}}^2}. \\ \end{split} \end{equation} \noindent Then, we estimate the real and imaginary parts of cIRM by: \begin{equation} \label{eq:recover_real_imag} \begin{split} \hat{M}_{\text{r}} = \hat{M}_{\text{mag}} cos \angle \hat{M} \\ \hat{M}_{\text{i}} = \hat{M}_{\text{mag}} sin \angle \hat{M} \\ \end{split} \end{equation} \noindent The cIRM $ \hat{M} = \hat{M}_{r} + j \hat{M}_{i} $ is a complex tensor, and is used to separate a target source from $ X $ by (\ref{eq:mask_mul}) which involves a magnitude scaling and a phase rotation operation. Finally, we apply an inverse STFT to obtain the separated waveform. \subsection{Combination of Bounded Mask Estimation and Direct Magnitude Prediction}\label{section:attention} In previous works we show that directly predicting the unbound linear magnitude $ |\hat{S}| $ lead to the underperformance of the source separation system. To overcome the limit of the performance discussed in Section~\ref{sec:background}, we propose to combine a bounded mask and direct magnitude prediction to estimate the magnitude of cIRMs. The motivation is to use direct magnitude prediction as \textit{residual components}, one that complements the bounded magnitude mask. This is implemented as follow: \begin{equation} \label{eq:attention} |\hat{S}| = \text{relu}(\hat{M}_{\text{mag}} \odot |X| + \hat{Q}) \end{equation} \noindent where $ \hat{Q} \in \mathbb{R}^{T \times F} $ is the direct magnitude prediction. In this way, we take the advantages of both of the methods. The ReLU operation ensures that the predicted magnitude is always larger than 0. The estimation of phase $ \angle \hat{M} $ by using $ \hat{P}_{\text{r}} $ and $ \hat{P}_{\text{i}} $ are the same as the one in Section \ref{section:decoupling}. Then, the separated STFT can be obtained by: \begin{equation} \label{eq:attention_phase} \hat{S} = |\hat{S}| e^{j (\angle \hat{M} + \angle X)}, \end{equation} \noindent where $ |\hat{S}| $ is calculated by Eq.~ (\ref{eq:attention}). In total, the our proposed MSS system contains four outputs: $ \hat{M}_{\text{mag}} $, $ \hat{Q} $, $ \hat{P}_{\text{r}} $ and $ \hat{P}_{\text{i}} $. All of those outputs share the same backbone architecture and apply an individual linear layer to obtain their outputs. We use sigmoid non-linearity to predict $ \hat{M}_{\text{mag}} $ to ensure they have values between 0 and 1. Fig. \ref{fig:resunet} shows the structure of our proposed method. \begin{figure} \centerline{ \includegraphics[width=\columnwidth]{figs/resunet.pdf}} \caption{The proposed MSS system with residual blocks. The details of REB, RDB, and RCB are illustrated in Figure~\ref{fig:resblocks}.} \label{fig:resunet} \end{figure} \subsection{Residual UNet}\label{subsec:verydeep} In this section, we introduce deep residual UNets with hundreds of layers for MSS, which is at least 4 times deeper than previous UNet models \cite{jansson2017singing, hennequin2020spleeter, hu2020dccrn}. We first introduce a baseline UNet with 33 layers. The 33-layer UNet consists of 6 encoder and 6 decoder layers. Each encoder layer consists of two convolutional layers and a downsampling layer. Each decoder layer consists of one transposed convolutional layer for upsampling and two convolutional layers. Finally, three additional convolutional layers are added after decoder layers. In total, there are 33 convolutional layers. \begin{figure} \centerline{ \includegraphics[width=\columnwidth]{figs/resblocks.pdf}} \caption{(a) Residual encoder block (REB), (b) residual decoder block (RDB), (3) residual convolutional block (RCB).} \label{fig:resblocks} \end{figure} Next, we introduce a 143-layer residual UNet. In building a residual UNet with hundreds of layers, we use residual encoder blocks (REB) and residual decoder blocks (RDB) to increase its depth. Fig. \ref{fig:resunet} shows the architecture of our proposed residual UNet where we use 6 REBs and 6 RDBs. Each REB consists of 4 residual convolutional blocks (RCB) as shown in Fig. \ref{fig:resblocks} (a). Each RCB consists of of two convolutional layers with kernel sizes $ 3 \times 3 $ as shown in Fig. \ref{fig:resblocks} (c). A shortcut connection is added between the input and the output of a RCB. A batch normalization \cite{ioffe2015batch} and a leaky ReLU non-linearity \cite{maas2013rectifier} with a negative slope of 0.01 is applied before convolutional layers following the pre-act residual network configuration \cite{he2016identity}. An $ 2 \times 2 $ average pooling layer is applied after each REB to reduce the feature map size. Each REB consists of 8 convolutional layers. The blocks in the decoder (RDBs) are symmetric to those in the encoder (REB). Each RDB consists of a transposed convolutional layer with a kernel size $ 3 \times 3 $ and stride $ 2 \times 2 $ to upsample feature maps, followed by four RCBs as shown in Fig. \ref{fig:resblocks} (b). Each RDB consists of 9 convolutional layers, including 8 convolutional layers and 1 transposed convolutional layer. To further increase the representation ability of the residual UNet, we introduce intermediate convolutional blocks (ICBs) between REBs and RDBs as shown in Fig. \ref{fig:resunet}. We use 4 ICBs, where each ICB consists of 8 convolutional layers which has the same architecture as the REB except the pooling layer. After RDBs, an additional ICB with 8 layers and a final convolutional layer with $ J $ output channels are applied. For example, for a stereo separation task where only the magnitude of masks $ |\hat{M}| $ is used as a baseline, $ J $ is set to $2$. Similarly, if the decoupling of magnitude and phase are predicted (as in Section \ref{section:decoupling}), $ J$ is set to $6 $ (two channels of $ |\hat{M}| $, $ \hat{P}_{\text{r}} $ and $ \hat{P}_{\text{i}} $). In our complete system in Section \ref{section:attention}, where the combination of magnitude mask and direct magnitude prediction is used, $J$ is set to $8$ (two channels of $ |\hat{M}| $, $ |\hat{Q}| $, $ \hat{P}_{\text{r}} $ and $ \hat{P}_{\text{i}} $). In total, there are 143 convolutional layers in our proposed residual UNet. \section{Experiments} \subsection{Dataset} We run an experiment to demonstrate the proposed method on the MUSDB18 dataset \cite{rafii2017musdb18}. The MUSDB18 dataset includes separate vocals, accompaniment, bass, drums, and other instruments. Its training/validation sets contain 100/50 full tracks, respectively. The training set is further decomposed into 86 training songs and 14 songs for development and evaluation. All songs are stereo with a sampling rate of 44.1~kHz. We release the source code of our work online.\footnote{Will be released after acceptance.} \subsection{Data Processing} We split audio recordings into 3-second segments. Since the proposed system is convolutional layer-based UNet, it does not require previous states to calculate current predictions, making our system to be fully parallelizable. For data augmentation, we apply \textit{mix-audio} data augmentation that is used in \cite{song2021catnet} to augment vocals, accompaniment, drums, and other instruments which randomly mix two 3-second segments from a \textit{same} source as a new 3-second segment for training. The motivation is that, the addition of two sources also belongs to that source. We do not apply mix-audio data augmentation to bass because bass are usually monophonic in a song. Then, we create mixtures $ x $ by summing segments after mix-audio augmentation from different sources. We apply short-time Fourier transform (STFT) on $ x $ with a Hann window size of 2048 and a hop size of 441 samples, corresponding to the hop size time of 10 ms. During training of all the proposed and baseline systems, we set batch size to 16 and apply Adam optimizer \cite{kingma2014adam}. The learning rate is set to $ 0.001 $, $ 0.0005 $, $ 0.0001 $, $ 0.0002 $, and $ 0.0005 $ for vocals, accompaniment, bass, drums and other instruments. Different learning rates are used because some sources such as drums are easier to be overfitted. Those learning rates are tuned on the validation set of the MUSDB18 dataset. Learning rates are multiplied by a factor of 0.9 after every 15,000 steps. MSS systems are trained for 300,000 steps. \begin{table}[t] \centering \caption{Comparison of SDRs of previous and our proposed MSS systems.} \label{table:previous} \resizebox{\columnwidth}{!}{% \begin{tabular}{*{6}{c}} \toprule & vocals & bass & drums & other & acc. \\ \midrule Open-Unmix \cite{stoter2019open} & 6.32 & 5.23 & 5.73 & 4.02 & - \\ Wave-U-Net \cite{stoller2018wave} & 3.25 & 3.21 & 4.22 & 2.25 & - \\ Demucs \cite{defossez2019music} & 6.29 & 5.83 & 6.08 & 4.12 & - \\ Conv-TasNet \cite{luo2019conv} & 6.81 & 5.66 & 6.08 & 4.37 & - \\ Spleeter \cite{hennequin2020spleeter} & 6.86 & 5.51 & 6.71 & 4.55 \\ D3Net \cite{takahashi2020d3net} & 7.24 & 5.25 & \textbf{7.01} & 4.53 & 13.52 \\ \midrule ResUNetDecouple+ & \textbf{8.98} & \textbf{6.04} & 6.62 & \textbf{5.29} & \textbf{16.63} \\ \bottomrule \end{tabular}} \end{table} \subsection{Result 1: Comparison with Previous Methods} We compare our proposed system with several systems including previous time domain and frequency domain based systems. Signal-to-Distortion Ratio~(SDR) \cite{vincent2006performance} is used as evaluation metric. The \textit{museval} toolbox \cite{stoter20182018} is used to calculate MSS metrics. Table \ref{table:previous} shows the SDRs of previous MSS systems as well as those of our best performing system. The first row shows the performance of Open-Unmix \cite{stoter2019open}, which consists of three bi-directional long short-term memory layers achieves a vocals SDR of 6.32 dB. The second row shows that the Wave-U-Net \cite{stoller2018wave} system trained in the time-domain achieve slightly lower SDRs than other time-frequency domain systems. The third to to the eighth rows show the results of Demucs \cite{defossez2019music}, Conv-TasNet \cite{luo2019conv}, Spleeter \cite{hennequin2020spleeter}, and D3Net \cite{takahashi2020d3net}. Among the compared methods, D3Net achieves the best vocals and drums SDRs of 7.24 dB and 7.01 dB respectively. The Demucs achieves the best bass SDR of 5.83 dB, and the Spleeter achieves the best other SDR of 4.55 dB in previous works. As in the last row of Table \ref{table:previous} , our proposed residual UNet with the decoupling and the combination of magnitude masks and direct prediction significantly outperforms previous methods in separating vocals, bass, other, and accompaniments. \subsection{Result 2: Ablation Study} \begin{table}[t] \centering \caption{SDRs of the proposed systems (2nd -- 7th rows) in a comparison to the previous system, UNetPhase.} \label{table:proposed} \resizebox{\columnwidth}{!}{% \begin{tabular}{*{6}{c}} \toprule & vocals & bass & drums & other & acc. \\ \midrule UNetPhase \cite{choi2018phase} & 7.45 & 5.42 & 6.51 & 4.86 & 15.23 \\ \midrule UNet & 7.20 & 4.79 & 5.94 & 4.49 & 14.69 \\ UNetDecouple & 7.65 & 5.00 & 6.29 & 4.71 & 15.21 \\ UNetDecouple+ & 7.81 & 5.28 & 6.47 & 5.00 & 15.32 \\ \midrule ResUNet & 7.79 & 5.00 & 6.20 & 5.13 & 16.15 \\ ResUNetDecouple & 8.72 & 5.71 & 6.50 & 5.20 & 16.39 \\ ResUNetDecouple+ & \textbf{8.98} & \textbf{6.04} & \textbf{6.62} & \textbf{5.29} & \textbf{16.63} \\ \bottomrule \end{tabular}} \end{table} In this section, we show the performances of our proposed systems that partially incorporate our modification. We also compare them with the system from \cite{choi2018phase}, which we call UNetPhase. We implement a UNetPhase with 33 layers. In Table \ref{table:proposed}, UNet, UNetDecouple, and UNetDecouple+ are variants of a 33-layer UNet and ResUNet, ResUNetDecouple, ResUNetDecoup+ are variants of a 143-layer residual UNet. UNet and ResUNet are models with magnitude masks only, i.e., phase is not considered in the model. `Decouple` indicates that the proposed decoupling of magnitude and phase is applied. `+' indicates the further improvement of combining the magnitude masks and direct prediction as introduced in Section~\ref{section:attention}. First, UNet, which only predicts the magnitude of masks, performed slightly worse than UNetPhase. Here, we observe the average improvement by predicting phase is 0.57~dB. Second, we can compare the trend within the row 2-4 or the row 5-7. Both for UNet's and ResUNet's, decoupling of the magnitude and phase improves the performance -- by 0.35~dB with UNet and 0.45~dB with ResUNet on average. The `+' models shows further average improvements of 0.2~dB and 0.196~dB with UNet and ResUNet, respectively. This result indicates that combining bounded mask estimation and direct magnitude prediction can improve MSS. Third, when the other conditions are fixed, ResUNet always outperforms UNet for all source instruments. It clearly demonstrates the effectiveness of a very deep architecture in MSS. The average improvement of ResUNet from UNet is 0.7~dB. The results did not show a clear sign that the upper bound that we discussed in Section~\ref{sec:background} is playing a critical role in the current systems. For example, for vocal/bass/drums/other/accompaniments, the upper bounds of cIRM (1), i.e., UNetPhase, are 19.84/17.99/19.10/18.97/26.54~dB, all of which are more than 10~dB higher than the performance of UNetPhase. Compared to UNetPhase, UNetDecouple+, which is a case of cIRM (inf), only slightly outperforms UNetPhase by 0.082~dB on average and did not perform better on bass and drums. \section{Conclusion} In this paper, we investigated the music source separation (MSS) task. We showed that previous MSS methods have upper bound of the performance due to a strong assumption on the magnitude of the masks. We also showed that accurate phase estimation and unbound complex ideal ratio masks (cIRMs) are important for MSS. Finally, we analyzed the distribution of cRIMs for MSS and showed that 22\% of cIRMs have magnitude larger than one. To overcome the limits, We proposed to decouple the estimation of magnitudes and phases. We also proposed to combine bounded magnitude masks and direct prediction methods for more flexible magnitude estimation. Finally, we proposed a very deep MSS architecture, a residual UNet with 143 layers. In the experiment, we showed that our proposed modifications improve the performance, achieving an SDR of 8.98~dB for vocals in MUSDB18. In the future work, we will explore a more effective approach to design a MSS that solve the issues we analyzed better, especially, the issue of the bounded magnitude masks. \section{DeltaPhase} Previous works are limited to the methodology that only apply magnitude masks. However, there is a lack of research investigating the mask distribution of the source separation problem. The masks are denoted as \begin{equation} \label{mask} \begin{split} M = Y / X \\ = \frac{Y_{r} + i Y_{i}}{X_{r} + i X_{i}} \\ = \frac{Y_{r}X_{r} + Y_{i}X_{i} + i(Y_{i}X_{r} - Y_{r}X_{i})}{X_{r}^{2} + X_{i}^{2}} \end{split} \end{equation} Considering the real and imaginary part, the masks can be denoted as \subsection{Upperbound of music source separation targets} To begin with, we analyzed the upperbound of music source separation tasks. The targets we investigated include mixture, ideal binary mask (IBM), ideal ratio mask, complex IRM, etc. This allows us to know the upperbound of systems. \subsection{Distribution of Mask points} To analyze why there are performance gap between IBM and IRMs, we show the distirbution of mask points as follows. To begin with, we plot the masks of vocals, accompaniment, bass and drums in Fig. xxx. We show that the angle of masks are distrbuted equally, while only using ideal binary mask will lead to the 0 angle of prediciton. Therefore, predicting angles and complex masks are neccessary. On the other hand, we evaluate the magnitude masks.Convential methods will limit the scale of ideal ratio masks to a scale between -1 and 1. However, we observe that there are magnitudes that beyond this range. \subsection{Proposed scale method} To tackle this problem, we propose several systems. the first system is to predict the magnitude directly: \begin{equation} \label{mask} mag = relu(x) theta = ... \end{equation} The second strategy is that we can use a weight to balance the prediction: We also propose an IBM classification task, that requires the system to train with predicting IBM. So that if magnitude is less than 1, then weight tend to use sigmoid as output. If magnitude is bigger than 1, then tend to use linear as output. To tackle the problem that the phases are not estimated, we propose an delta phase algorithm. Instead of only predicting the magnitude, we also predict the real and imaginary part of signals as described in Fig. \ref{figs:framework}. We denote the \noindent We denote the angle of mixture as $ \Theta_{\text{mix}} $, and the angle of $ s $ as $ \Theta_{\text{tar}} $. Our system predicts the incremental of angle $ \Theta_{\Delta} $. So that $ \Theta_{\text{mix}} = \Theta_{\text{tar}} + \Theta_{\Delta} $. Then, we have: \begin{equation} \label{eq1} \begin{split} \hat{S} &= |\hat{S}| e^{\angle j\Theta_{\text{tar}}} \\ &= |\hat{S}|(\text{cos} \Theta_{\text{tar}} + j \text{sin} \Theta_{\text{tar}}) \\ &= |\hat{S}|(cos (\Theta_{\text{tar}} + \Theta_{\Delta}) + j sin (\Theta_{\text{tar}} + \Theta_{\Delta})) \\ &= |\hat{S}|(cos \Theta_{\text{tar}} cos \Theta_{\Delta} - sin \Theta_{\text{tar}} sin \Theta_{\Delta} + j sin \Theta_{\text{tar}} cos \Theta_{\Delta} + j cos\Theta_{\text{tar}} sin \Theta_{\Delta}) \end{split} \end{equation} Previous works mainly apply conventional UNet for the source separation task. However, those UNet has several limitations. 1) The convolutional layers are only a few, and can be underfitting to the sound classes. 2) The receptive field size is limited, so the performance of separation can be limited. 3) We argue that immediately apply the decoder after encoder layers may lead to underperformance of systems. To solve this problem, we propose a deep residual UNet to solve this problem. To begin with, the ResUNet consists of several residual blocks. We denote the residual block as follows. In previous works, Unets are shallow but wide. We argue that this kind of architecture may lead to underperofmrance in music source separation, because the deep architectures are important for MSS. We denote the residual blocks as: The system contains 6 encoder layers, 4 intermediate layers and 6 decoder layers. Each encoder layer consists of 4 residual blocks, where each residual block consists of 2 convolutional blocks that are described in in Fig. xxx. Briefely speaking, a BN, leaky relu function with leakage of 0.01, and a linear convolutional layer. The input of the whole system is a complex spectrogram, and then converted to linear magnitude. For music source separation, there are stereo two channels as input. And for output, there are 6 channels, where magnitude, real and imaginary channels are individual. A few changes from previous ResNet include as follows: 1) Intermediate layers. We show that the intermediate layers are important for mss, which are increases the receptive field. 2) Transpose and pooling layers 3) Arbitrary loss function that can be calcualted on the wave domain. Fig. \ref{fig:resunet} shows the entire ResUNet architecture. There are encoder blocks, intermeidate blocks and decoder blocks in the diagram. The encoder and decoder blocks are symmetric. The output of the decoder block includes a magnitude, a real and an imaginary part. Then, the loss functions are calculated on the top of the system. Fig. \ref{fig:resblocks} shows the residual blocks of the resnet architecture. We show that this kind of deep architecture is helpful for the MSS task. Therefore, estimating cIRM includes estimating the real and imaginary parts of mask $ M $. Fig. \ref{fig:cIRM} shows the demonstration of source signal, noise signal and mixture. The mixture signal is $ X_{t,f} = S_{t, f} + N_{t, f} $. It can be shown that the prediction of $ s $ from $ x $ includes a scaling and a phase rotation operation. Because: \begin{equation} \label{eq:mask} \begin{split} Y & = MX \\ & = |M||X|e^{j (\angle M + \angle X)} \end{split} \end{equation} \noindent so that $ |M| $ is the magnitude scaling factor, and the angle of $ M $ is the phase shift factor. In this work, we propose to predict the mask $ M $ to achieve the MSS task, that is different previous works \cite{}. \begin{table*}[t] \centering \caption{Baseline result of IS paradigm and ES paradigm} \label{table:upper_bound} \begin{tabular}{*{12}{c}} \toprule & Mixture & IBM & cIBM & IRM (0, 1) & IRM (0, inf) & cIRM 1 & cIRM 2 & cIRM 3 & cIRM 5 & cIRM 10 & cIRM (0, inf) \\ \midrule vocals & -5.69 & 10.59 & 12.44 & 10.04 & 10.42 & 19.84 & 31.02 & 35.58 & 41.04 & 47.62 & 54.50 \\ accompaniment & -5.68 & 16.10 & 17.75 & 15.31 & 15.97 & 26.54 & 37.62 & 42.28 & 47.33 & 53.51 & 60.63 \\ bass & -6.36 & 7.17 & 8.21 & 6.05 & 6.07 & 17.99 & 27.88 & 32.38 & 37.86 & 44.30 & 54.12 \\ drums & -4.30 & 8.75 & 11.17 & 8.03 & 8.61 & 19.10 & 30.38 & 34.81 & 39.91 & 46.45 & 56.08 \\ other & -4.92 & 8.20 & 9.54 & 7.28 & 7.37 & 18.97 & 28.91 & 33.63 & 39.08 & 45.64 & 56.00 \\ \bottomrule \end{tabular} \end{table*} \noindent Different mask types we evaluate include IBM, IRM, cIRM, and limited bounded cIRM etc. Those masks have been adopted to different MSS systems in previous works. We evaluate SDRs of different instruments on the test set of the MUSDB18 dataset, including vocals, accompaniment, drums and other. To begin with, we evaluate using mixture as source separation results. Table \ref{table:upper_bound} shows that vocals, bass, drums and other have negative SDRs when using mixture as separation result. The mixture result is used as a baseline for comparing with other mask based systems. We show that the upper bound of vocals using IRM is 10.02, which is the upper bound of several previous MSS systems. Considering current MSS systems can achieve higher performance than 7.0 dB, this result indicates that phase information must be incorporated into the model to achieve better performance. For accompaniment, the upperbound of using IRM is 15.97 dB, and current MSS system has higher performance than 13 dB. For bass, drums and other, the upperbound of IRM are 6.07 dB, 8.61 dB and 7.37 dB respectively. To further improve the system performance, phase information are important. When extending IRM to cIRM, Table \ref{table:upper_bound} shows that the upperbound of MSS systems increase. Many previous works limit the magnitude of cIRMs to a constant such as 1. This assumes that the mixture magnitude is always larger than sources. We show that when limiting the magnitude of masks to 1, the upper bound SDR is 19.84 dB, which has a big gap to 54.50 dB, indicating that there are room for improvement. Table \ref{table:upper_bound} shows that the upperbound increase from 19.84 dB, to 31.02 dB, 41.04 dB, 47.62 dB and 54.50 dB when setting the mask magnitude to 1, 2, 5, 10, +inf, respectively. For other instruments such as accompaniment, bass, drums and other, the upperbound SDR increases significantly from IRM to cRIM, and also further increases when not limiting the magnitude of masks. Previous IRM based methods assume that the angles between mixture and target source is unchanged. This is equavilent to that the angle is all 0. Fig. \ref{fig:cIRMs} shows the cIRMs distribution of vocals, accompaniment, bass, drums and other instruments. There are several T-F units that is beyond the -1 and 1 circle, indicating that limiting the mask magnitude to 1 will limit the MSS performance. There are more T-F units that have mask magnitudes larger than 1. Fig. \ref{fig:cIRMs} show that the cIRM distribution of different instruments are different. The angles distribute equally in all angles. We calculate how many TF bins have mask values larger than 1, and counted that 20.3\%, 34.5\%, 6.1\%, 26.9\% and 13.9\% TF bins have mask values larger than 1. This observation indicates that the cIRMs should be designed to have magnitudes larger than 1. To begin with, we denote the magnitude of the estimated mask as $ | \hat{M}_{\text{mag}} | \in [0, \infty)^{T \times F} $. Predicting the unbound mask $ | \hat{M}_{\text{mag}} | $ can be difficult. Following previous works, we can limit the magnitude of masks to $ (0, 1) $ by applying a sigmoid nonlinearity. Table \ref{table:upper_bound} shows the upper bound results of MSS systems by limiting different magnitudes of masks. After calculating the magnitudes, we calculate the phases of $ \hat{M} $ as follows. The neural network outputs $ \hat{P}_{\text{r}} \in \mathbb{R}^{T \times F} $ and $ \hat{P}_{\text{r}} \in \mathbb{R}^{T \times F} $ to calculate the phases of $ \hat{M} $ by: In addition, the estimation of $ \hat{P_{\text{r}}} $ and $ \hat{P_{\text{}}} $ decouples the estimation of magnitude and phase. In total, a neural network contains three outputs: $ \hat{M} $, $ \hat{P_{\text{r}}} $ and $ \hat{P_{\text{}}} $ to calculate the cIRM of a source to be separated. The real and imaginary parts of the cIRM is calculated by: contains both magnitude and angle information that should be applied on the mixture complex STFT. Then, we apply (\ref{eq:cIRM}) to calculate the complex STFT of the source to be separated. That is, we estimate the magnitude and phases of target source simultaneously instead of using the phase of mixture. \noindent where $ \angle \hat{M} $ is calculated by (\ref{eq:cos_sin}). Previous works have shown that directly estimate the linear spectrogram of $ \hat{S}_{\text{mag}} $ is difficult. Therefore, previous works will instead limit $ \hat{S}_{\text{mag}} $ by a sigmoid or a tanh non-linearity. We have shown that limiting the magnitude of $ \hat{S}_{\text{mag}} $ will have a upper bound of the system performance. Therefore, in this part we propose a combination of mask based and linear based method by introducing a weight function. The motivation is that the mask is used to be the main part of the separation system, and the linear magnitude is used to recover the residual part of the system. The above equation shows that we are adding residual parts to the mask parts. This will break the upperbound of limiting the mask between -1 and 1. There are also other methods that can be used to extend the IRM upperbound. Our desing is to let $ a $ to control how much the system should attend to the mask, and how much it should attend to the linear part. , still, there are many spaces to improve. First, previous UNet architectures are limited to tens of layers, which tend to underfit the training data. There is a lack of research on exploring deeper architectures for MSS. Second, the receptive field sizes of shallower CNNs are limited, and the global information on the spectrogram can not be captured. For example, shallower CNNs can not capture higher and lower frequency correlations on the spectrogram. In this work, we propose a deep residual UNet architecture for MSS. Different from previous UNet architectures, our proposed system contains hundreds of convolutional layers. We describe the residual UNet architecture as follows. To begin with, the waveform of an input mixture is converted into a spectrogram. Then, we apply batch normalization \cite{ioffe2015batch} on each frequency bins of the spectrogram to normalize input features. First, we build a conventional UNet for comparison. The UNet consists of 6 encoder and 6 decoder layers. Each encoder layer consists of two convolutional layers and a downsampling layer. Each decoder layer consists of a transposed convolutional layer for upsampling and two convolutional layers. Finally, three extra convolutional layers are added after decoder layers. In total, there are 33 layers in our UNet architecture. ======================== Conventional MSS systems are designed to separate a recording into vocals and accompaniments. Recently, MSS systems are designed to separate a recording into multiple instruments, such as vocals, bass, drums and other. The coefficient $ A \in {0, 1}^{T \times F} $ is a learnable weight, which works as an attention submodule that controls how much a neural network should attend to $ |\hat{M}_{\text{mag}}||X| $, and how much it should attend to $ |\hat{P}| $. Larger $ A $ indicates that masks are more important for separation, and smaller $ A $ indicates that the linear spectrogram $ \hat{P} $ are more important for separation. \begin{table}[t] \centering \caption{Baseline result of IS paradigm and ES paradigm} \label{table:is_baseline} \begin{tabular}{*{6}{c}} \toprule & vocals & bass & drums & other & accompaniment \\ \midrule IRM oracle & 9.43 & 7.12 & 8.45 & 7.85 & - \\ \midrule Open-Unmix \cite{stoter2019open} & 6.32 & 5.23 & 5.73 & 4.02 & - \\ Wave-U-Net \cite{stoller2018wave} & 3.25 & 3.21 & 4.22 & 2.25 & - \\ Demucs \cite{defossez2019music} & 6.29 & 5.83 & 6.08 & 4.12 & - \\ Conv-Tasnet \cite{luo2019conv} & 6.81 & 5.66 & 6.08 & 4.37 & - \\ splitter \cite{hennequin2020spleeter} & 6.86 & 5.51 & 6.71 & 4.55 \\ D3Net \cite{takahashi2020d3net} & 7.24 & 5.25 & 7.01 & 4.53 & 13.52 \\ Real Imag & 7.08 \\ complex spectral mapping \cite{tan2019complex} & 7.05 \\ DCCRN \cite{hu2020dccrn} \\ phase-aware (withdraw) \cite{choi2020phase} \\ phasen \cite{yin2020phasen} \\ \midrule UNet & 7.20 & 4.16 & 6.14 & 4.62 \\ UNetComplex & 7.52 \\ \bottomrule \end{tabular} \end{table} \begin{table*}[t] \centering \caption{Baseline result of IS paradigm and ES paradigm} \label{table:is_baseline} \begin{tabular}{*{6}{c}} \toprule & vocals & bass & drums & other & accompaniment \\ \midrule UNet & 7.20 (22) & 4.79 (45) & 5.94 (45b) & 4.49 (45c) & 14.69 (51) \\ UNetPhase \cite{choi2018phase} & 7.45 (37) & 5.42 (_47) & 6.51 (_47b) & 4.86 (_47c) & 15.23 (51b) \\ UNetDecouple & 7.65 (39) & 5.00 (42) & 6.29 (42b) & 4.71 (42c) & 15.21 (51c) \\ UNetComplex24 weight & 7.63 (38) & 5.50 (46) & 6.43 (46b) & 4.72 (46c) & 15.35 (51d) \\ UNetDecouple+ & 7.81 (58) & 5.28 (58b) & 6.47 (58d) & 5.00 (58e) & 15.32 (58b) \\ \midrule ResUNet & 7.79 (52) & 5.00 (55) & 6.20 (56) & 5.13 (57) & 16.15 (54) \\ ResUNetDecouple & 8.72 (52b) & 5.71 (55b) & 6.50 (56b) & 5.20 (57b) & 16.39 (54b) \\ ResUNetDecoupe+ & \textbf{8.98} (52c) & \textbf{6.04} (55c) & \textbf{6.62} (56c) & \textbf{5.29} (57c) & \textbf{16.63} (54c) \\ \bottomrule \end{tabular} \end{table*} The first system we compare is a conventional UNet. Then, we compare with several real and imaginary models, and also systems by predicting the phases directly. For fair comparisons with previous methods, we re-implemented many several previous systems including the unet based systems. Therefore, we can only replace several important parts of the system\st{,} and remain all other parts unchanged for fair comparison. \subsection{Comparison with residual architecture} We investigate the residual unet with conventional unet architectures. We show that the residual architecture is indeed helpful for predicting the inversed spectrograms. After the neural network is deep enough, we are able to predict the separated spectrogram with high resolution. \subsection{Visualizing the cRIMS} Fig. \ref{} shows the visualized predicted cIRMs. Comparing with the ground truth masks, we show that the magnitude can break the upper bound of 1. The limitation of this work is as follows. Although we proposed a framework that can achieve arbitrary upper bound of systems, however, there are still many spaces for improvement. For example, the estimated signals are still xx \% that do not overcome the limit 1. This indicates the estimating signals from mixture that has larger values are different tasks. We showed that the predicting of phases is important for source separation and there is an performance gap between using magnitudes with phases and using only magnitudes. We show that by decoupling the prediction of magnitudes and phases, we can achieve better results in MSS than several previous methods. We analyzed the distribution of complex ideal ratio masks (cIRMs). We proposed to combine mask and spectrogram-based methods for magnitude estimation to increase the performance upper bounds of music source separation (MSS) systems. We showed deep architectures are important for MSS and proposed a residual UNet with 143 layers that significantly outperforms shallower UNets. In future, we will explore to combine time-domain and time-frequency domain methods for MSS. \begin{table}[t] \centering \caption{Comparison of SDRs of previous and our proposed MSS systems.} \label{table:previous} \resizebox{\columnwidth}{!}{% \begin{tabular}{*{6}{c}} \toprule & vocals & bass & drums & other & acc. \\ \midrule IRM oracle & 9.43 & 7.12 & 8.45 & 7.85 & - \\ \midrule Open-Unmix \cite{stoter2019open} & 6.32 & 5.23 & 5.73 & 4.02 & - \\ Wave-U-Net \cite{stoller2018wave} & 3.25 & 3.21 & 4.22 & 2.25 & - \\ Demucs \cite{defossez2019music} & 6.29 & 5.83 & 6.08 & 4.12 & - \\ Conv-Tasnet \cite{luo2019conv} & 6.81 & 5.66 & 6.08 & 4.37 & - \\ Spleeter \cite{hennequin2020spleeter} & 6.86 & 5.51 & 6.71 & 4.55 \\ D3Net \cite{takahashi2020d3net} & 7.24 & 5.25 & \textbf{7.01} & 4.53 & 13.52 \\ \midrule ResUNetDecouple+ & \textbf{8.98} & \textbf{6.04} & 6.62 & \textbf{5.29} & \textbf{16.63} \\ \bottomrule \end{tabular}} \end{table}
{'timestamp': '2021-09-14T02:18:49', 'yymm': '2109', 'arxiv_id': '2109.05418', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05418'}
arxiv
\section{Introduction} \label{sec:intro} A common theme in statistical inference and machine learning is to select a few relevant features or variables (among many) that are associated with the responses of interest. Controlling the expected proportion of falsely selected features (or the FDR~\cite{benjamini1995}) for the variable selection problem has attracted much attention since the development of the \emph{knockoff filter} procedure due to its flexibility (in constructing test statistics) as well as good finite-sample performances~\cite{barber2015controlling,barber2019knockoff}. In this procedure, a test statistic is computed for every feature of the model and the variables are selected by (data-dependent) thresholding the statistics according to the target FDR. The knockoff filter has been generalized to various settings such as the high-dimensional case ($p>n$)~\cite{barber2019knockoff}, beyond linear models (the model-X framework)~\cite{candes2018panning}, and deep learning-based procedure~\cite{romano2019deep }, with applications in a variety of domains~\cite{lu2018deeppink,fan2019ipad }. In this work, we aim to develop $(\epsilon,\delta)$-differentially-private statistics that ensure (finite-sample) FDR control while being empirically powerful. Differential privacy is currently the standard framework concerning the privacy of individuals. The differential privacy of other variable selection methods like the Lasso \cite{tibshirani1996regression} and BH procedure \cite{benjamini1995} are investigated in \cite{thakurta2013differentially} and \cite{dwork2018differentially}, respectively. However, the privacy of the knockoff procedure hasn't been discussed in the literature yet. Related works are \cite{dwork2014analyze,sheffet2017differentially} where they consider the differential privacy of the sample covariance and the least-squares estimator. Although our approach is similar, the work is different in the sense that we take care of the FDR control and the knockoff design which is a function of the data. We adopt the sensitivity analysis and output perturbation method~\cite{dwork2006calibrating} and randomize the statistics by adding noise according to Gaussian and Laplace mechanism \cite{dwork2014algorithmic}. \section{Preliminaries} \label{sec:prob} \subsection{Fixed-X Knockoff Filter} Let ${\bf y}\in \mathbb{R}^n$ denote a vector of responses, and ${\bf X}\in\mathbb{R}^{n\times p}$ a data matrix consisting of $p$ (explanatory) variables and $n$ samples. A canonical linear regression model is given by \begin{align} {\bf y} = {\bf X} \boldsymbol \beta + {\bf w},\label{linear_model} \end{align} where $\boldsymbol \beta = [\beta_1,...,\beta_p]^\top\in \mathbb{R}^p$ is the unknown regression vector and the model assumptions are as follows. \begin{assumption} ${\bf w}$ is Gaussian with constant variance $\sigma^2$ i.e. ${\bf w}\sim \mathcal{N}(0, \sigma^2 {\bf I}_n)$. \end{assumption} \begin{assumption} $\boldsymbol \Sigma={\bf X}^\top{\bf X}$ is invertible. \end{assumption} We say the $i$-th variable is a null variable if $\beta_i = 0$. The goal is to select the non-null variables (i.e. $\beta_i \neq 0$) without selecting too many nulls. For the linear model~\eqref{linear_model}, let $\hat{S}\subseteq\{1,2,\hdots,p\}$ denote the selected variables by some procedure. Then the FDR is defined as follows \begin{equation} \text{FDR}=\mathbb{E}\Bigg[\frac{\#\{j:\beta_j=0\ \text{and}\ j\in\hat{S}\}}{\#\{j: j\in\hat{S}\}\vee 1}\Bigg], \end{equation} where the expectation is taken over the randomness of the error terms, ${\bf w}$. A selection rule controls the FDR at level $q$ if its corresponding FDR is guaranteed to be at most $q$. In the knockoff procedure, the FDR control is achieved by computing a vector of statistics ${\bf W}=(W_1, W_2,\hdots,W_p)^\top$ with components corresponding to each variable and selecting $\{j:W_j\geq T(q,\Omega)\}$, where the threshold $T\geq 0$ depends on the target FDR $q$ and the set of computed statistics, i.e., $\Omega=\{W_1,\hdots,W_p\}$. The main idea in computing the statistics is to use a fake copy of the design that preserve the correlation structure of ${\bf X}$ but destroys the relationship between ${\bf X}$ and ${\bf y}$. For example, if we shuffle (or permute) the samples in ${\bf X}$, we preserve the geometry of ${\bf X}$ but the relation with ${\bf y}$ would be diminished. The knockoff filter is based on a more elegant construction of such a fake design, namely, the knockoff design. \subsubsection{Knockoff Design} Knockoff copies are constructed using only the original features and the subtle geometrical relation between the data matrix ${\bf X}$ and its knockoff $\mathbf{\Tilde{X}}\in\mathbb{R}^{n\times p}$ makes them an appropriate tool for FDR control. Let $\boldsymbol{\Sigma}={\bf X}^\top{\bf X}$ denote the Gram matrix of the original features. The relationship between ${\bf X}$ and $\mathbf{\Tilde{X}}$ can be summarized as below \begin{align} &{\bf G} := [ {\bf X}\ \mathbf{\Tilde{X}}]^\top[ {\bf X}\ \mathbf{\Tilde{X}}]\nonumber\\ &\:\quad=\begin{bmatrix} {\boldsymbol{\Sigma}\qquad\qquad\quad \boldsymbol{\Sigma}-\text{diag}\{{\bf s}\}}\\{\boldsymbol{\Sigma}-\text{diag}\{{\bf s}\}\qquad\qquad\quad \boldsymbol{\Sigma}}\end{bmatrix},\label{eq:data_gram} \end{align} where ${\bf s}\in\mathbb{R}^p_+$ is chosen in a way that $\bf G$ is positive semidefinite. If $n\geq 2p$, $\mathbf{\Tilde{X}}$ can be constructed as follows \begin{equation} \mathbf{\Tilde{X}}={\bf X}\,({\bf I}_p-\boldsymbol{\Sigma}^{-1} \text{diag}\{{\bf s}\})+\mathbf{\tilde{U}}{\bf C},\label{KOconst} \end{equation} where $\bf C$ is obtained by Cholesky decomposition of the Schur complement of ${\bf G}$ and $\mathbf{\tilde{U}}^{n\times p}$ is an orthonormal matrix that satisfies $\mathbf{\tilde{U}}^\top{\bf X}=0$. The existence of $\mathbf{\tilde{U}}$ is guaranteed by $n\geq 2p$. By looking at \eqref{eq:data_gram}, one can observe that the knockoff features matrix $\tilde{{\bf X}}$ preserves the correlation structure of ${\bf X}$ and the vector ${\bf s}$ gives us a degree of freedom to make knockoff features different than the original ones, e.g., if ${\bf s}=0$ then $\mathbf{\Tilde{X}}={\bf X}$. For maximum detection power, the knockoff and original features should be as orthogonal to each other as possible. The restriction on this matter is imposed by ${\bf G}\succeq 0$ which is the necessary and sufficient condition for $\mathbf{\Tilde{X}}$ to exist. \begin{remark} A suggestion in \cite{barber2015controlling} regarding the choice of ${\bf s}$ for a normalized design, is to set $\text{diag}\{{\bf s}\} =\text{min}( 2\lambda_{\text{min}}(\boldsymbol \Sigma),1)\,{\bf I}_p$. If $2\lambda_{\text{min}}(\boldsymbol \Sigma) \leq 1$, this choice (as we shall see in Lemma \ref{ev}) forces the minimum eigenvalue of ${\bf G}$ to be zero. For the differential privacy purposes we recommend using $\text{diag}\{{\bf s}\} = \lambda_{\text{min}}(\boldsymbol \Sigma)\,{\bf I}_p$ to make the regression operators stable. \end{remark} \subsubsection{Statistics} Using the knockoff features, we are now able to construct a vector of statistics ${\bf W}$ allowing FDR control. For instance, the Lasso penalized least-squares estimate can be used to construct the statistics. \begin{equation} \boldsymbol{\hat{\beta}}^*:=\underset{{\bf b}\,\in\mathbb{R}^{2p}}{\arg\min}\Big\{\,\Big\|{\bf y}-[{\bf X}\ \mathbf{\Tilde{X}}]{\bf b}\Big\|_2^2\,+\lambda \|{\bf b}\|_1 \Big\},\label{eq:LS_model} \end{equation} where $\lambda \geq 0$. Using this estimate, one way to define the statistics ${\bf W}$ is as follows \begin{equation} W_i^{\textsc{LCD}} = |\hat{\beta}^*_i| - |\hat{\beta}^*_{i+p}|\ ,\qquad 1\leq i\leq p\ .\label{stat:LCD} \end{equation} We can also define the statistics differently, \begin{equation} W_i = \text{sgn}(|\hat{\beta}^*_i| - |\hat{\beta}^*_{i+p}|)\,\max(|\hat{\beta}^*_i|,|\hat{\beta}^*_{i+p}|)\ .\label{lcsm} \end{equation} The key feature of these statistics that make them suitable for the purpose of FDR control is the \textit{\iid sign property} of the nulls, i.e., the signs of null statistics (signs of $W=\{W_j: \beta_j=0\}$) are independent of their magnitudes and have \iid $\mathrm{Bern}(1/2)$ distribution. We will look at this property in more details in the subsequent subsection. Unlike the nulls, non-null statistics are expected to get large positive values. Thus, a selection rule of the form $\{j:W_j\geq T\}$ for some $T>0$ seems reasonable. However, $T$ should be characterized such that guarantees FDR control. \subsubsection{IID Sign Property of Nulls} In general, satisfying the following two properties is sufficient to guarantee the \iid sign property of the null statistics. Let ${\bf X}^{(i)}$ denote the $i$-th column of ${\bf X}$. \smallskip \textit{\textbf{Property I} : Swapping ${\bf X}^{(i)}$ and $\mathbf{\Tilde{X}}^{(i)}$ for all $i\in F$ and any $F\subseteq \{1,2,\hdots,p\}$ has the effect of switching the signs of $\{W_i:i\in F\}$. This property is called \textbf{antisymmetry} in \cite{barber2015controlling}.} \smallskip In the least-squares problem \eqref{eq:LS_model}, it can be observed that swapping ${\bf X}^{(i)}$ and $\mathbf{\Tilde{X}}^{(i)}$ for any $i\in \{1,2,\hdots,p\}$ will swap $\hat{\beta}^*_i$ and $\hat{\beta}^*_{i+p}$ and this will result in switching the sign of $W_i$ according to~\eqref{stat:LCD} and \eqref{lcsm}. \smallskip \textit{\textbf{Property II}: Let ${\bf W}_{\text{swap}(F)}$ denote the vector of statistics obtained when ${\bf X}^{(i)}$ and $\mathbf{\Tilde{X}}^{(i)}$ are swapped in the regression problem for all $i\in F$ where $F\subseteq \{j:\beta_j = 0\}$. Then ${\bf W}_{\text{swap}(F)}$ and ${\bf W}$ have the same distribution, i.e. ${\bf W}_{\text{swap}(F)} \overset{d}{=}\, {\bf W}$.} \smallskip In the least-squares problem \eqref{eq:LS_model}, it can be shown that the estimated coefficients for null variables and their corresponding knockoff variable are exchangeable which immediately implies \textbf{Property II}. Using the \iid sign property for the null statistics, it can be shown that the selection rule $\hat{\mathcal{S}}(T)=\{j:W_j\geq T\}$ controls the FDR at level $q\in[0,1]$, where \begin{equation} T = \min\Big\{t \in \Psi:\frac{1+\#\{j: W_j \leq -t\}}{\#\{j: W_j\geq t\}\vee 1}\leq q\Big\},\label{threshold} \end{equation} if $\Psi =\{|W_i|:i=1,2,\hdots p\}\setminus\{0\}$ is not empty and $T=+\infty$ if $\Psi = \emptyset$. \subsection{Differential Privacy} Differential privacy provides a rigorous formulation of individual privacy that allows for the development of (randomizing) mechanisms that release some information about the data without revealing too much about any individuals. In other words, the goal is to have a guarantee that the effect of each observation in the output is negligible. \begin{definition} Two databases (matrices) are called neighbors or adjacent if they differ only in a single observation (row). \end{definition} \begin{definition}[Differential Privacy] A randomized mechanism $\mathcal{M}$ with domain $\mathcal{D}$ and range $\mathcal{R}$ is $(\epsilon,\delta)$-differentially private if for all pairs of neighboring inputs ${\bf A},{\bf A}'\in\mathcal{D}$ and all measurable subsets $\mathcal{S}\subset \mathcal{R}$, it holds that, \begin{equation*} \mathbb{P}(\mathcal{M}({\bf A})\in\mathcal{S})\le e^{\epsilon}\,\mathbb{P}(\mathcal{M}({\bf A}')\in\mathcal{S})+\delta\ . \end{equation*} \end{definition} The algorithms we are going to propose are based on the \textit{output perturbation} mechanisms. In general, the class of additive noise mechanisms perturb the output by adding random noise proportional to the (differential) sensitivity of the output, that is, $\mathcal{M}({\bf A}) = f({\bf A}) + Z$, where $f$ is some (vector-valued) mapping and $Z$ denotes the noise. The classical Gaussian mechanism~\cite{dwork2014algorithmic} and Laplace mechanism~\cite{dwork2006calibrating} adopt $Z\sim \mathcal{N}(0,\kappa^2 I)$ and $Z_i\overset{\iid}{\sim}\text{Lap}(\eta)$, where $\kappa^2$ and $\eta$ are determined by the $\ell_2$ and $\ell_1$-sensitivity of $f$, respectively. \begin{definition}\label{l2def} The $\ell_2$-sensitivity of a function $f:\mathcal{D}(f)\longrightarrow\mathbb{R}^p$ is defined as $\Delta_2 f = \underset{{\bf A} \& {\bf A}' \texttt{adjacent}}{max} \|f({\bf A}) - f({\bf A}')\|_2$. In case of a function with range in matrices we use the Frobenius norm $\|.\|_F$ in the definition. \end{definition} \begin{theorem}[\cite{dwork2014algorithmic}] For any $\epsilon\in(0,1)$ and $\delta\in(0,1)$ the Gaussian mechanism with $\kappa^2>2\ln{(1.25/\delta)}(\frac{\Delta_2 f}{\epsilon})^2$ is $(\epsilon,\delta)$-differentially private.\label{thm:GM} \end{theorem} \begin{theorem}[\cite{dwork2006calibrating}] Defining $\ell_1$-sensitivity similar to Definition \ref{l2def} $\Delta_1 f = \underset{{\bf A} \& {\bf A}' \texttt{adjacent}}{max} \|f({\bf A}) - f({\bf A}')\|_1$, adding \iid $\text{Lap}\big(\frac{\Delta_1 f}{\epsilon}\big)$ to the components of $f({\bf A})$ is $(\epsilon,0)$-differentially private.\label{LapM} \end{theorem} \section{Main Results} In this section we provide two methods for computing differential private statistic under the assumptions 1,2, and the following assumption. \begin{assumption} $B$ is an upper bound for the $\ell_2$-norm of the rows in ${\bf X}$ and a lower bound for the $\ell_2$-norm of the columns. \end{assumption} For the purpose of variable selection with knockoffs, it is natural to normalize ${\bf X}$ by columns. So in both methods, the normalization is considered as a part of the procedure. Also, we let $\text{diag}\{{\bf s}\} = \lambda_{\text{min}}(\boldsymbol \Sigma')\,{\bf I}_p$ in creating knockoffs \eqref{KOconst}, where $\boldsymbol \Sigma' = {\bf X}'^\top{\bf X}'$ and ${\bf X}'$ denotes the design matrix ${\bf X}$ normalized by the $\ell_2$-norm of its columns. \subsection{Method I} In this method we consider statistics that depend on the data through the following form, \begin{equation} \widehat{{\bf W}}_1 = {\bf f}([{\bf X}'\ \widetilde{{\bf X}'}]^\top[{\bf X}'\ \widetilde{{\bf X}'}]+E,[{\bf X}'\ \widetilde{{\bf X}'}]^\top{\bf y}+{\bf e})\ ,\label{mthd1} \end{equation} where $E$ and ${\bf e}$ denote the additive noise terms ensuring the differential privacy. Define $C_{\text{min}}=\underset{1\leq i \leq p}{\text{min}}\big\|{\bf X}^{(i)}\big\|_2 $ and $\eta^2= \frac{B^2}{C_{\text{min}}^2-B^2}$, where ${\bf X}^{(i)}$ denotes the $i$-th column of ${\bf X}$. In the first argument of \eqref{mthd1}, $E\in\mathbb{R}^{2p\times2p}$ is a random term of the following structure, \begin{equation} E = \boldsymbol \theta_1 \begin{bmatrix}{{\bf O}_p\qquad{\bf I}_p}\\{{\bf I}_p\qquad {\bf O}_p}\end{bmatrix}+\begin{bmatrix}{1\quad 1}\\{1\quad 1} \end{bmatrix}\otimes\boldsymbol \theta_2 \nonumber\ , \end{equation} where $\boldsymbol \theta_1\sim\text{Lap}\big(\eta^2(1+ \lambda_{\text{min}}(\boldsymbol \Sigma'))/\epsilon_1\big)$ and $\boldsymbol \theta_2\in\mathbb{R}^{p\times p}$ is a symmetric matrix with zero diagonal entries such that the elements of the upper triangle are drawn i.i.d. from $\mathcal{N}(0,\kappa_1^2)$, where $\kappa_1^2 \geq \frac{2\ln{(1.25/\delta)}}{\epsilon_2^2}\eta^4(\sqrt{2}+\|\boldsymbol \Sigma'\|_F)^2$, and each lower triangle entry is copied from its upper triangle counterpart. Regarding the second argument of \eqref{mthd1}, ${\bf e}$ is a vector with \iid $\mathcal{N}(0,\kappa_2^2)$ components with $\kappa_2^2>\frac{2\ln{(1.25/\delta_1)}}{\epsilon^2}\Delta_2\big([{\bf X}'\ \widetilde{{\bf X}'}]^\top{\bf y}\big)^2$ computed according to the following $\ell_2$-sensitivity, \begin{align} \Delta_2\big([{\bf X}'\ \widetilde{{\bf X}'}]^\top&{\bf y}\big) =\, \label{mthd1_Sen} \zeta^{\frac{1}{2}}\Big(2\sqrt{\gamma}+\eta\,\big(3+2\lambda_{\text{max}}(\boldsymbol \Sigma')\\+\lambda_{\text{min}}(\boldsymbol \Sigma')\big)^{\frac{1}{2}}&\Big)+\big\|\boldsymbol \beta\big\|\Bigg(\sqrt{2}\, \Big(\frac{\eta}{B}-\frac{1}{C_{\text{min}}}\Big)\big\|\boldsymbol \Sigma\big\|_F+2\,\eta B \nonumber\\ +\big(C_{\text{min}}-\frac{B}{\eta}\big)&\lambda_{\text{min}}(\boldsymbol \Sigma') +\eta^2\big(\lambda_{\text{min}}(\boldsymbol \Sigma')+1\big)\sqrt{C_{\text{min}}^2+B^2}\Bigg)\nonumber\ , \end{align} where, $\zeta = \frac{2p\,\sigma^2}{1-\sqrt{\frac{2}{p}\ln(2/\delta_2)}}$, $\gamma=2\lambda_{\text{max}}(\boldsymbol \Sigma')-\lambda_{\text{min}}(\boldsymbol \Sigma')$, and $\delta_2>2e^{-p/2}$. \begin{theorem}[Privacy]\label{M1prv} Releasing $\widehat{{\bf W}}_1$ is $(\epsilon+\epsilon',\delta+\delta')$-differentially private for arbitrary ${\bf f}$, where $\delta' = \delta_1+\delta_2$ and $\epsilon' = \epsilon_1+\epsilon_2$. \end{theorem} \begin{theorem}[FDR control]\label{M1fdr} Let $F\subseteq\{1,...,p\}$ and $P_F$ denote a $2p\times 2p$ symmetric permutation matrix corresponding to swapping the $i$-th column (or row) with $(i+p)$-th for all $i\in F$. Suppose the operator ${\bf f}(\cdot,\cdot):\mathcal{D}\longrightarrow\mathbb{R}^p$ (with $\mathcal{D}\subseteq\mathbb{R}^{2p\times2p}\times \mathbb{R}^{2p}$) is antisymmetric in the sense that for all $({\bf A},{\bf b})\in\mathcal{D}$, computing ${\bf f}(P_F^\top{\bf A} P_F,P_F{\bf b})$ has the effect of switching the signs of the components of ${\bf f}({\bf A},{\bf b})$ corresponding to $F$. Then, applying the knockoff selection rule on $\widehat{{\bf W}}_1$ controls the FDR. \end{theorem} For instance, we observe that if ${\bf f}({\bf A},{\bf b})$ denotes the vector of statistics computed using the estimate ${\bf A}^{-1}{\bf b}$, then ${\bf f}(\cdot,\cdot)$ satisfies the antisymmetry condition in Theorem \ref{M1fdr}, because we have $(P_F{\bf A} P_F)^{-1}P_F{\bf b}=P_F{\bf A}^{-1}{\bf b}$. \subsection{Method II} In this method, we add noise directly to the least-squares estimate $\boldsymbol{\hat{\beta}^{'}}$, i.e. \eqref{eq:LS_model} with normalized design and $\lambda = 0$. \begin{theorem}[Privacy]\label{M2prv} Fix $\delta_2>2e^{-p/2}$. If $\lambda_{\text{min}}(\boldsymbol \Sigma')>\frac{\eta^2}{1-\eta^2}$, then by the Gaussian mechanism, releasing $\boldsymbol{\hat{\beta}^{'}}+{\bf e}$ with noise variance $\kappa^2>\frac{2\ln{(1.25/\delta_1)}}{\epsilon^2} \Delta_2(\boldsymbol{\hat{\beta}^{'}})^2$ and the following $\ell_2$-sensitivity, \begin{align} \Delta_2(\boldsymbol{\hat{\beta}^{'}}) = \frac{2\,\zeta^\frac{1}{2}}{\sqrt{(1-\eta^2)\lambda_{\text{min}}(\boldsymbol{\Sigma^{'}})-\eta^2}} +\Big(C_{\text{min}}-\frac{B}{\eta}\Big) \big\|\boldsymbol \beta\big\|\ ,\nonumber \end{align} is $(\epsilon,\delta_1+\delta_2)$-differentially private, where $\zeta = \frac{2p\,\sigma^2}{1-\sqrt{\frac{2}{p}\ln(2/\delta_2)}}$.\label{thm:olspert} \end{theorem} \begin{theorem}[FDR control]\label{M2fdr} Let $F\subseteq\{1,...,p\}$ and define $P_F$ as in Theorem \ref{M1fdr}. Suppose the operator ${\bf g}(\cdot):\mathcal{D}\longrightarrow\mathbb{R}^p$ (with $\mathcal{D}\subseteq\mathbb{R}^{2p}$) is antisymmetric in the sense that for all ${\bf b}\in\mathcal{D}$, computing ${\bf g}(P_F{\bf b})$ has the effect of switching the signs of the components of ${\bf g}({\bf b})$ corresponding to $F$. Then, for any vector ${\bf e}$ with \iid elements, applying the knockoff selection rule on $\widehat{{\bf W}}_2={\bf g}(\boldsymbol{\hat{\beta}^{'}}+{\bf e})$ will control the FDR. \end{theorem} \begin{remark} The sensitivities we compute depend on the data, so the additive noise is calibrated according to the observed data set. As a result, the privacy holds in a local sense and not globally. In Method II, the term $\lambda_{\text{min}}(\boldsymbol \Sigma')$ in the denumerator can make the $\ell_2$-sensitivity $\Delta_2(\boldsymbol{\hat{\beta}^{'}})$, sensitive to the data. This may be an issue in case the adversary has some side information about the data. However, we can use the Ridge regression to alleviate this issue and stabilize the regression operator, i.e., if we add $\omega^2\,{\bf I}_{2p}$ to ${\bf G}'$ we get $\lambda_{\text{min}}({\bf G}')=\lambda_{\text{min}}(\boldsymbol \Sigma')+\omega^2$, which is lower bounded by $\omega^2$. Also, the sensitivities depend on the unknown parameters $\sigma^2$ and $\boldsymbol \beta$ which should be estimated or bounded for the use in practice. \end{remark} \section{Simulation Results} \label{sec:simulation} In this section we present simulation results on synthetic data sets for both Method I and II. The sample size $n$ is swept between $10^3$ to $10^{6.6}$. We have $p = 50$ measurements per sample and the entries of the design matrix ${\bf X}$ are generated \iid according to $\mathcal{N}(0,{\bf I}_p)$. The responses ${\bf y}$ are generated according to the linear model \eqref{linear_model} with noise variance $\sigma^2 = 1$ and $k=15$ (non-zero) underlying coefficients of the same amplitude $A=4.5$ and sign. We adopt the OLS estimator and the \textit{Coefficient Signed Max} (CSM) statistic \eqref{lcsm}. The target FDR is $q=0.2$ and the plots are based on averaging 250 trials. Each trial is $(0.2,\frac{2p}{n})$-differentially private, meaning we let the overall $\delta$ parameter drop as the sample size grows, so the privacy hold in a more strict sense for larger sample sizes\footnote{In practice it is common to take $\delta$ to scale as $\frac{1}{n}$.}. In Method I we set $\epsilon = 0.1$, $\epsilon_1=\epsilon_2=0.05$, and $\delta=\delta_1=\delta_2$. In Method II we have $\epsilon = 0.2$ and $\delta_1=\delta_2$. The power is defined as follows, \begin{equation} \text{Power}=\frac{1}{k}\,\mathbb{E}\big[\#\{j:\beta_j\neq 0\ \text{and}\ j\in\hat{S}\}\big]\ . \end{equation} \begin{figure}[h] \centering \includegraphics[width=0.9\linewidth]{pow_fdr_02_9.eps} \caption{Power and FDR for the two differentially private knockoff procedures. The FDR is controlled at the desired level $q=0.2$ for both methods. However, Method II has the superior power in this experiment.} \label{fig:my_label} \end{figure}
{'timestamp': '2022-02-01T02:35:38', 'yymm': '2109', 'arxiv_id': '2109.05402', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05402'}
arxiv
\section{Introduction} Rule-based reasoning is an essential part of human intelligence prominently formalized in artificial intelligence research via logic programs with important applications to expert systems, database theory, and knowledge representation and reasoning (cf. \citeN{Apt90,Lloyd87,Baral03}). Describing complex objects as the composition of elementary ones is a common strategy in computer science and science in general. \citeN{Antic_i2} has recently introduced the sequential composition of logic programs in the context of logic-based analogical reasoning and learning in logic programming. The sequential composition operation has been studied by \citeN{Antic_i3} in the propositional case and by \citeN{Antic_i6} in the non-monotonic case of answer set programming. Motivated by the aforementioned applications to analogical reasoning, in this paper we study the sequential decomposition of logic programs and show that it gives rise to a qualitative and algebraic notion of syntactic logic program similarity. More precisely, we say that a program $P$ can be {\em one-step reduced} to a program $R$---in symbols, $P\lesssim R$---iff $P=(Q\circ R)\circ S$ for some programs $Q$ (prefix) and $S$ (suffix). Now given a query $q$ to $P$, we can answer $q$ by translating every SLD-resolution step of $P$ via the prefix $Q$ into an SLD-resolution step of $R$ and translating the result back again with the suffix $S$ (cf. \prettyref{exa:Plus}). We then say that $P$ and $R$ are {\em syntactically similar} iff $P$ can be one-step reduced to $R$ and vice versa, that is, iff $P\lesssim R$ and $R\lesssim P$. This definition has appealing mathematical properties. For example, we can show that the programs $Plus$ for the addition of numerals and the program $Append$ for list concatenation are syntactically similar according to our definition (cf. \prettyref{exa:Plus}). Interestingly, when translating queries to $Append$ into queries of the seemingly simpler program $Plus$, we obtain `entangled' terms of the form $s([\;\,])$ and $s([b,c])$ which are neither numerals nor lists, and we believe that dual syntactic objects like these are essential for cross-domain analogical reasoning (see the discussion in \prettyref{sec:Conclusion}). Syntactic similarity is related to the number of bound variables per rule of a program and we deduce from this fact that, for example, the program $Member$ for checking list membership, containing maximally two bound variables per rule, can be one-step reduced to the program $Append$ containing maximally three bound variables per rule, but not vice versa: $Member<Append$ (cf. Examples \ref{exa:Member} and \ref{exa:Member2}). This is interesting as the prefix $Q$ witnessing $Member=Q\circ Append$ resembles the mapping between $Member$ and $Append$ of \citeN{Tausend91} introduced for analogical reasoning. In a broader sense, this paper is a further step towards an algebra of logic programs first envisioned by \citeN{OKeefe85} with applications to logic-based analogical reasoning and learning in logic programming \cite{Antic_i2}. \section{Logic Programs} We recall the syntax and semantics of logic programs by mainly following the lines of \citeN{Apt90}. \subsection{Syntax}\label{sec:Syntax} An ({\em unranked first-order}) {\em language} $L$ is defined as usual from predicate, function, and constant symbols and variables. Terms and atoms over $L$ are defined in the usual way. We denote the set of all ground $L$-atoms by $HB_L$ or simply by $HB$ called the {\em Herbrand base} over $L$, and we denote the set of all $L$-atoms not containing function or constant symbols by $XHB_L$. Substitutions and (most general) unifiers of terms and (sets of) atoms are defined as usual. We call any bijective substitution mapping variables to variables a {\em renaming}. Let $L$ be a language. A ({\em Horn logic}) {\em program} over $L$ is a set of {\em rules} of the form \begin{align}\label{equ:r} A_0\leftarrow A_1,\ldots,A_k,\quad k\geq 0, \end{align} where $A_0,\ldots,A_k$ are $L$-atoms. It will be convenient to define, for a rule $r$ of the form \prettyref{equ:r}, $head(r):=\{A_0\}$ and $body(r):=\{A_1,\ldots,A_k\}$, extended to programs by $head(P):=\bigcup_{r\in P}head(r)$ and $body(P):=\bigcup_{r\in P}body(r)$. In this case, the {\em size} of $r$ is $k$ denoted by $sz(r)$. A {\em fact} is a rule with empty body and a {\em proper rule} is a rule which is not a fact. We denote the facts and proper rules in $P$ by $facts(P)$ and $proper(P)$, respectively. A program $P$ is {\em ground} if it contains no variables and we denote the grounding of $P$ which contains all ground instances of the rules in $P$ by $gnd(P)$. We call a ground program {\em propositional} if it contains only propositional atoms with no arguments. The set of all {\em variants} of $P$ is defined by $variants(P):=\bigcup_{\theta\text{ renaming}}P[\theta]$. The variants of a program will be needed to avoid clashes of variables in the definition of composition. A variable is {\em bound} in a rule if it appears in the head and body. Define the {\em dual} of $P$ by \begin{align*} P^d:=facts(P)\cup\{A\leftarrow head(r)\mid r\in proper(P): A\in body(r)\}. \end{align*} Roughly, we obtain the dual of a theory by reversing all the arrows of its proper rules. We define the {\em left} and {\em right reduct} of $P$, with respect to some interpretation $I$, respectively by \begin{align*} ^IP:=\{r\in P\mid I\models head(r)\} \quad\text{and}\quad P^I:=\{r\in P\mid I\models body(r)\}. \end{align*} \subsection{Semantics} An {\em interpretation} is any set of atoms from $A$. We define the {\em entailment relation}, for every interpretation $I$, inductively as follows: (i) for an atom $a$, $I\models a$ if $a\in I$; (ii) for a set of atoms $B$, $I\models B$ if $B\subseteq I$; (iii) for a rule $r$ of the form \prettyref{equ:r}, $I\models r$ if $I\models body(r)$ implies $I\models head(r)$; and, finally, (iv) for a program $P$, $I\models P$ if $I\models r$ holds for each rule $r\in P$. In case $I\models P$, we call $I$ a {\em model} of $P$. The set of all models of $P$ has a least element with respect to set inclusion called the {\em least model} of $P$. We say that $P$ and $R$ are {\em logically equivalent} if their least models coincide. Define the {\em van Emden-Kowalski operator} of $P$, for every interpretation $I$, by $T_P(I):=\{head(r)\mid r\in P:I\models body(r)\}$. It is well-known that an interpretation $I$ is a model of $P$ iff $I$ is a prefixed point of $T_P$ and the least model of $P$ coincides with the least fixed point of $T_P$. \subsection{SLD-Resolution} Logic programs compute via a restricted form of resolution, called {\em SLD-resolution}, as follows. For simplicity, we consider here only the ground case. Let $q$ be a ground query $\leftarrow A_1,\ldots,A_k$, $k\geq 1$, and suppose that for some $i$, $1\leq i\leq k$ and $m\geq 0$, $r=A_i\leftarrow A'_1,\ldots,A'_m$ is a rule from $gnd(P)$. Then $q'$ given by \begin{align*} \leftarrow A_1,\ldots,A_{i-1},A'_1,\ldots,A'_m,A_{i+1},\ldots,A_k \end{align*} is called a {\em resolvent} of $q$ and $r$, and $A_i$ is called the {\em selected atom} of $q$. By iterating this process we obtain a sequence of resolvents which is called an {\em SLD-derivation}. A derivation can be finite or infinite. If its last query is empty then we speak of an {\em SLD-refutation} of the original query $q$. In this case we have derived an {\em SLD-proof} of $A_1,\ldots,A_k$. A {\em failed} SLD-derivation is a finite derivation which is not a refutation. In case $A$ is a ground atom with an SLD-proof from $P$, we say that $A$ is an {\em SLD-consequence} of $P$ and write $P\vdash A$. For a rule $r$ of the form \prettyref{equ:r}, we write $P\vdash r$ in case $P\vdash A_0$ whenever $P\vdash A_i$ holds for every $1\leq i\leq k$. We denote the {\em empty query} by $\square$. \section{Composition} In this section, we recall the sequential composition of logic programs as defined by \citeN{Antic_i2} and studied in the propositional case by \citeN{Antic_i3}. \begin{notation} In the rest of the paper, $P$ and $R$ denote logic programs over some joint language $L$. \end{notation} The rule-like structure of logic programs induces naturally a compositional structure as follows \cite[Definition 4]{Antic_i2}. \begin{definition}\label{def:PR} We define the ({\em sequential}) {\em composition} of $P$ and $R$ by\footnote{We write $X\subseteq_k Y$ in case $X$ is a subset of $Y$ consisting of $k$ elements.} \begin{align*} P\circ R:=\left\{head(r\vartheta)\leftarrow body(S\vartheta) \;\middle|\; \begin{array}{l} r\in P\\ S\subseteq_{sz(r)}variants(R)\\ head(S\vartheta)=body(r\vartheta)\\ \vartheta=mgu(body(r),head(S)) \end{array} \right\}. \end{align*} \end{definition} Roughly, we obtain the composition of $P$ and $R$ by resolving all body atoms in $P$ with the `matching' rule heads of $R$. This is illustrated in the next example, where we construct the even from the natural numbers via composition. \begin{example}\label{exa:Even} Consider the program \begin{align*} Nat:= \left\{ \begin{array}{l} nat(0)\\ nat(s(x))\leftarrow nat(x) \end{array} \right\} \end{align*} generating the natural numbers. By composing the only proper rule in $Nat$ with itself, we obtain \begin{align*} \{nat(&s(x))\leftarrow nat(x)\}\circ\{nat(s(x))\leftarrow nat(x)\}=\{nat(s(s(x)))\leftarrow nat(x)\}. \end{align*} Notice that this program, together with the single fact in $Nat$, generates the {\em even} numbers. \end{example} Notice that we can reformulate sequential composition as \begin{align}\label{equ:bigcup} P\circ R=\bigcup_{r\in P}(\{r\}\circ R), \end{align} which directly implies right-distributivity of composition, that is, \begin{align}\label{equ:(P_cup_Q)_circ_R} (P\cup Q)\circ R=(P\circ R)\cup (Q\circ R)\quad\text{holds for all propositional Horn theories }P,Q,R. \end{align} However, the following counter-example shows that left-distributivity fails in general: \begin{align*} \{a\leftarrow b,c\}\circ(\{b\}\cup\{c\})=\{a\} \quad\text{and}\quad (\{a\leftarrow b,c\}\circ\{b\})\cup(\{a\leftarrow b,c\}\circ\{c\})=\emptyset. \end{align*} Define the {\em unit program} by the Krom program\footnote{Recall from \prettyref{sec:Syntax} that $XHB_L$ consists of all $L$-atoms not containing function or constant symbols.} \begin{align*} 1_L:=\{A\leftarrow A\mid A\in XHB_L\}. \end{align*} In the sequel, we will omit the reference to $L$. The space of all logic programs over some fixed language is closed under sequential composition with the neutral element given by the unit program and the empty program serves as a left zero, that is, we have \begin{align*} P\circ 1=1\circ P=1 \quad\text{and}\quad \emptyset\circ P=\emptyset. \end{align*} We can simulate the van Emden-Kowalski operator on a syntactic level without any explicit reference to operators via sequential composition, that is, for any interpretation $I$, we have \begin{align}\label{equ:T_P} T_P(I)=gnd(P)\circ I. \end{align} As facts are preserved by composition and since we cannot add body atoms to facts via composition on the right, we have \begin{align}\label{equ:IP=I} I\circ P=I. \end{align} \subsection{Ground Programs} Ground programs are possibly infinite propositional programs where ground atoms can have a fixed inner structure, which means that we can import here the results of \citeN{Antic_i3} which do not depend on finiteness. \begin{notation} In the rest of this subsection, $P$ and $R$ denote ground programs. \end{notation} For ground programs, sequential composition simplifies to \begin{align*} P\circ R=\{head(r)\leftarrow body(S)\mid r\in P,S\subseteq_{sz(r)}R:head(S)=body(r)\}. \end{align*} Our first observation is that we can compute the heads and bodies of a ground program $P$ via \begin{align}\label{equ:head(P)} head(P)=P\circ HB \quad\text{and}\quad body(P)=proper(P)^d\circ HB. \end{align} Moreover, we have \begin{align}\label{equ:head(PR)} head(PR)\subseteq head(P) \quad\text{and}\quad body(PR)\subseteq body(R). \end{align} Given an interpretation $I$, we define \begin{align*} I^\ominus:=1^{HB-I}\cup I \quad\text{and}\quad I^\oplus:=\{A\leftarrow(\{A\}\cup I)\mid A\in HB\}. \end{align*} It is not difficult to show that $PI^\ominus$ is the program $P$ where all occurrences of the ground atoms in $I$ are removed from the rule bodies in $P$, that is, we have \begin{align*} PI^\ominus&=\{head(r)\leftarrow (body(r)-I)\mid r\in P\}. \end{align*} Similarly, $PI^\oplus$ is the program $P$ with the ground atoms in $I$ added to the rule bodies of all {\em proper} rules in $P$, that is, we have \begin{align*} PI^\oplus&=facts(P)\cup\{head(r)\leftarrow (body(r)\cup I)\mid r\in proper(P)\}. \end{align*} The left and right reducts can be represented via composition and the unit program by \begin{align}\label{equ:^IP} ^IP=1^I\circ P \quad\text{and}\quad P^I=P\circ 1^I. \end{align} Interestingly enough, we can represent the grounding of a (non-ground) program $P$ via composition with the grounding of the unit program by \begin{align}\label{equ:gnd(P)} gnd(P)=(gnd(1)\circ P)\circ gnd(1). \end{align} \section{Decomposition and Similarity} Let us start this section with a definition of a qualitative and algebraic notion of syntactic logic program similarity in terms of sequential decomposition. \begin{definition}\label{def:lesssim} Given two logic programs $P$ and $R$, we define \begin{align*} P\lesssim R\quad:\Leftrightarrow\quad\text{there exist programs $Q$ and $S$ such that $P=(QR)S$.} \end{align*} In that case, we say that $P$ can be {\em one-step reduced} to $R$, and we call $Q$ a {\em prefix} and $S$ a {\em suffix} of $P$. In case $P\lesssim R$ and $R\lesssim P$, we say that $P$ and $R$ are ({\em syntactically}) {\em similar} denoted by $P\approx R$. \end{definition} The computational interpretation of $P=(QR)S$ is that we can answer a query to $P$ by translating it via $Q$ into a query of $R$, computing one SLD-resolution step with $R$, and translating it back to $P$ via $S$ as is demonstrated in the next example. \begin{example}\label{exa:Plus} Consider the programs \begin{align*} Plus:= \left\{ \begin{array}{l} plus(0,y,y)\\ plus(s(x),y,s(z))\leftarrow\\ \qquad plus(x,y,z) \end{array} \right\} \quad\text{and}\quad Append := \left\{ \begin{array}{l} append([\;\,],y,y)\\ append([u\mid x],y,[u\mid z])\leftarrow\\ \qquad plus(x,y,z) \end{array} \right\} \end{align*} implementing the addition of positive numbers (represented as numerals) and the concatenation of lists, respectively. To show that $Plus$ and $Append$ are syntactically similar, we define the programs \begin{align*} Q:= \left\{ \begin{array}{l} append([\;\,],y,y)\leftarrow plus(0,y,y)\\ append([u\mid x],y,[v\mid z])\leftarrow plus(s(x),y,s(z)) \end{array} \right\} \end{align*} and \begin{align*} S:=\{plus(x,y,z)\leftarrow append(x,y,z)\}, \end{align*} and compute \begin{align*} Append=(Q\circ Plus)\circ S \quad\text{and}\quad Plus=(Q^d\circ Append)\circ S^d. \end{align*} This shows: \begin{align*} Plus\approx Append. \end{align*} The following SLD-derivation demonstrates how we can use the prefix $Q$ and suffix $S$ to append two lists via the seemingly simpler program for the addition of numerals: \begin{align*} &\xleftarrow{\;\;\;?\;\;\;} append([a],[b,c],[a,b,c])\\ &\xleftarrow{\;\;Q\;\;\;} plus(s([\;\,]),[b,c],s([b,c]))\\ &\xleftarrow{Plus} plus([\;\,],[b,c],[b,c])\\ &\xleftarrow{\;\;S\;\;\;} append([\;\,],[b,c],[b,c])\\ &\xleftarrow{\;\;Q\;\;\;} plus(0,[b,c],[b,c])\\ &\xleftarrow{Plus} \square. \end{align*} This shows, via a translation to numerals, \begin{align*} Append\vdash append([a],[b,c],[a,b,c]). \end{align*} Interestingly, the SLD-derivation above contains the `entangled' terms $s([\;\,])$ and $s([a,b])$ which are neither numerals nor lists, and we believe that such `dual' syntactic objects---which under the conventional doctrine of programming are not well-typed---are characteristic for reasoning across different domains and deserve special attention (this is discussed in \prettyref{sec:Conclusion}). \end{example} \begin{example}\label{exa:Member} \citeN{Tausend91} derive a mapping between the program $Append$ from \prettyref{exa:Plus} above and the program \begin{align*} Member:= \left\{ \begin{array}{l} member(u,[u\mid x]),\\ member(u,[v\mid x])\leftarrow\\ \qquad member(u,x) \end{array} \right\}, \end{align*} which computes list membership. We can now ask---by analogy to \citeN{Tausend91}---whether $Member$ can be one-step reduced to $Append$ (and vice versa) according to our definition. Define the programs \begin{align*} Q:= \left\{ \begin{array}{l} member(u,[u\mid x]),\\ member(u,[v\mid x])\leftarrow append([v\mid x],u,[v\mid x]) \end{array} \right\} \end{align*} and \begin{align*} S:=\{append(x,y,z)\leftarrow member(y,x)\}. \end{align*} It is not hard to compute \begin{align*} Member=(Q\circ Append)\circ S, \end{align*} which shows that membership can indeed be one-step reduced to the program for appending lists: \begin{align*} Member\lesssim Append. \end{align*} Interestingly enough, the programs $Q$ and $S$, which in combination permute the first two arguments of $Append$ and `forget' about the last one, resemble the mapping computed in \citeN{Tausend91} by other means. The converse fails, roughly, since $Member$ does not contain enough `syntactic structure' to represent $Append$. The intuitive reason is that $Member$ has only two bound variables, whereas $Append$ has three (see \prettyref{exa:Member2}). \end{example} \section{Properties of Similarity} Given ground atoms $A_0,\ldots,A_k$, the identity \begin{align*} \{A_0\}=\{A_0\leftarrow A_1\}\{A_1\} \end{align*} shows \begin{align*} \{A_0\}\lesssim \{A_0\leftarrow A_1\}. \end{align*} Since we cannot add body atoms to facts via composition on the right, we have \begin{align*} \{A_0\leftarrow A_1\}\not\lesssim\{A_0\}. \end{align*} Hence, \begin{align*} \{A_0\}<\{A_0\leftarrow A_1\}. \end{align*} On the other hand, we have \begin{align*} \{A_0\leftarrow A_1\}&=\{A_0\leftarrow A_1,\ldots,A_k\}\{A_2,\ldots,A_k\}^\ominus,\\ \{A_0\leftarrow A_1,\ldots,A_k\}&=\{A_0\leftarrow A_1\}\{A_2,\ldots,A_k\}^\oplus, \end{align*} which shows \begin{align*} \{A_0\leftarrow A_1\}\approx\{A_0\leftarrow A_1,\ldots,A_k\}. \end{align*} In the non-ground case, we have, for example: \begin{align*} \{p\leftarrow p\}<\{p(x_1)\leftarrow p(x_1)\}<\{p(x_1,x_2)\leftarrow p(x_1,x_2)\}<\ldots. \end{align*} This motivates the following definition. \begin{definition} The {\em width} of a rule is given by the number of its bound variables, extended to programs via $width(P):=\max_{r\in P}width(r)$. \end{definition} The number of bound variables cannot increase via composition---for example: \begin{align*} (\{p(x,y)\leftarrow p(x)\}\circ\{p(x)\leftarrow p(x)\})\circ\{p(x)\leftarrow p(x,y)\}=\{p(x,y)\leftarrow p(x,z)\}. \end{align*} This entails \begin{align*} width(PR)\leq width(P) \quad\text{and}\quad width(PR)\leq width(R). \end{align*} Hence, we have \begin{align}\label{equ:width} P\lesssim R \quad\Rightarrow\quad width(P)\leq width(R). \end{align} \begin{example}\label{exa:Member2} Reconsider the programs $Append$ and $Member$ of \prettyref{exa:Member}. We have \begin{align*} width(Member)=2 \quad\text{whereas}\quad width(Append)=3. \end{align*} By \prettyref{equ:width} we thus have $Append\not\lesssim Member$. \end{example} The following propositions summarize some facts about syntactic similarity. \begin{proposition} For any program $P$ and interpretations $I$ and $J$, we have \begin{align} gnd(P)&\lesssim P \quad\text{and}\quad T_P(I)\lesssim gnd(P),\\ I&\lesssim P \quad\text{and}\quad P\cup I\lesssim P,\\ \label{equ:I_approx_J} I&\approx J. \end{align} Moreover, we have \begin{align*} P\approx I \quad&\Leftrightarrow\quad \text{$P$ is an interpretation}. \end{align*} \end{proposition} \begin{proof} The relations in the first line are immediate consequences of \prettyref{equ:gnd(P)} and \prettyref{equ:T_P}, respectively. The relation $I\lesssim P$ follows from \prettyref{equ:IP=I}. The computation \begin{align*} P\cup I\stackrel{\prettyref{equ:IP=I}}=P\cup IP\stackrel{\prettyref{equ:(P_cup_Q)_circ_R}}=(1\cup I)P \end{align*} shows $P\cup I\lesssim P$. The similarity $I\approx J$ follows from $I\lesssim P$. The last similarity follows from \prettyref{equ:I_approx_J} together with \begin{align*} P\lesssim I \quad\Leftrightarrow\quad P=(QI)S\stackrel{\prettyref{equ:IP=I}}=QI\stackrel{\prettyref{equ:T_P}}=T_Q(I),\text{ for some $Q,S$} \quad\Rightarrow\quad \text{$P$ is an interpretation}. \end{align*} \end{proof} \begin{proposition} For any {\em ground} program $P$ and interpretation $I$, we have \begin{align} head(P)&\lesssim P \quad\text{and}\quad body(P)\lesssim proper(P)^d,\\ facts(P)&\lesssim P \quad\text{and}\quad P\lesssim 1\cup facts(P),\\ \label{equ:PI^oplus} PI^\oplus&\approx P\quad\text{and}\quad PI^\ominus\lesssim P,\\ \label{equ:^IP_lesssim_}^IP&\lesssim P \quad\text{and}\quad P^I\lesssim P. \end{align} Moreover, we have \begin{align} \label{equ:ominus} P\approx PI^\ominus \quad&\Leftrightarrow\quad facts(P)=facts(PI^\ominus),\\ \label{equ:facts} P\approx facts(P) \quad&\Leftrightarrow\quad P=facts(P) \end{align} \end{proposition} \begin{proof} The relations in the first line are immediate consequences of \prettyref{equ:head(P)}. The relation $facts(P)\lesssim P$ follows from $facts(P)=P\circ\emptyset$, and the relation $P\lesssim 1\cup facts(P)$ follows from \begin{align*} (1\cup facts(P))proper(P)&\stackrel{\prettyref{equ:(P_cup_Q)_circ_R}}=proper(P)\cup facts(P)proper(P)\\ &\stackrel{\prettyref{equ:IP=I}}=proper(P)\cup facts(P)\\ &=P. \end{align*} The relation $PI^\oplus\lesssim P$ holds trivially; $P\lesssim PI^\oplus$ follows from $P=(PI^\oplus)I^\ominus$. Similarly, the relation $PI^\ominus\lesssim P$ holds trivially; for $P\lesssim PI^\oplus$ see \prettyref{equ:ominus}. The relations in \prettyref{equ:^IP_lesssim_} are immediate consequences of \prettyref{equ:^IP}. Next, we prove \prettyref{equ:ominus}: $facts(P)=facts(PI^\ominus)$ means that by removing the ground atoms in $I$ from all rule bodies in $P$ we do not obtain novel facts---hence, we can add the ground atoms from $I$ back to the rule bodies of $P$ via $P=(PI^\ominus)I^\oplus$ which shows $P\lesssim PI^\ominus$ and see \prettyref{equ:PI^oplus} (recall that we cannot add body atoms to facts via composition); the other direction is analogous. Finally, the equivalence in \prettyref{equ:facts} is shown as follows: we have $P\lesssim facts(P)$ iff \begin{align}\label{equ:Q_circ_facts(P)} P=(Q\circ facts(P))\circ S=Q\circ facts(P),\quad\text{for some $Q$ and $S$,} \end{align} since \begin{align*} Q\circ facts(P)\stackrel{\prettyref{equ:T_P}}=T_Q(facts(P)) \end{align*} is an interpretation and \begin{align*} T_Q(facts(P))\circ S\stackrel{\prettyref{equ:IP=I}}=T_Q(facts(P)). \end{align*} The identity \prettyref{equ:Q_circ_facts(P)} holds iff $P=T_Q(facts(P))$ which is equivalent to $P=facts(P)$ since $T_Q(facts(P))$ yields an interpretation. \end{proof} The following characterization of syntactic similarity follows immediately from \prettyref{def:lesssim}. \begin{proposition}\label{prop:lesssim} For any programs $P$ and $R$, we have $P\lesssim R$ iff for each rule $r\in P$ there is a rule $s_r$, a subset $R_r$ of $R$ with $width(r)\leq width(R_r)$, and a program $S_r$ such that \begin{align*} \{r\}=(\{s_r\}R_r)S_r \quad\text{and}\quad (\{s_r\}R)S\subseteq P,\quad\text{where $S:=\bigcup_{r\in P}S_r$.} \end{align*} In this case, we have $P=(QR)S$ with $Q:=\bigcup_{r\in P}\{s_r\}$. \end{proposition} \begin{example} Consider the propositional programs \begin{align*} P=\left\{ \begin{array}{l} c\\ a\leftarrow b,c\\ b\leftarrow a,c \end{array} \right\} \quad\text{and}\quad \pi_{(a\,b)}=\left\{ \begin{array}{l} a\leftarrow b\\ b\leftarrow a \end{array} \right\}. \end{align*} We construct the programs $Q$ and $S$ such that $P=(Q\pi_{(a\,b)})S$ according to \prettyref{prop:lesssim}. Define \begin{align*} &r_1:=c \quad\Rightarrow\quad s_{r_1}:=c \quad\text{and}\quad S_{r_1}:=\emptyset,\\ &r_2:=a\leftarrow b,c \quad\Rightarrow\quad s_{r_2}:=a\leftarrow a \quad\text{and}\quad S_{r_2}:=\{b\leftarrow b,c\},\\ &r_3:=b\leftarrow a,c \quad\Rightarrow\quad s_{r_3}:=b\leftarrow b \quad\text{and}\quad S_{r_3}:=\{a\leftarrow a,c\}, \end{align*} and \begin{align*} Q:=\{s_{r_1},s_{r_2},s_{r_3}\}=1^{\{a,b\}}\cup\{c\} \quad\text{and}\quad S:=S_{r_1}\cup S_{r_2}\cup S_{r_3}=\{c\}^\oplus-1^{\{c\}}. \end{align*} This yields \begin{align*} P=((1^{\{a,b\}}\cup\{c\})\pi_{(a\,b)})(\{c\}^\oplus-1^{\{c\}}). \end{align*} Similar computations yield \begin{align*} \pi_{(a\,b)}=(1^{\{a,b\}}P)\{c\}^\ominus. \end{align*} This shows \begin{align*} P\approx\pi_{(a\,b)}. \end{align*} \end{example} \begin{example} Consider the propositional programs \begin{align*} \pi_{(a\,b)}:= \left\{ \begin{array}{l} a\leftarrow b\\ b\leftarrow a \end{array} \right\} \quad\text{and}\quad R:= \left\{ \begin{array}{l} a\leftarrow b\\ b\leftarrow b \end{array} \right\}. \end{align*} We have \begin{align*} R=\pi_{(a\,b)}R \quad\Rightarrow\quad R\lesssim \pi_{(a\,b)}. \end{align*} On the other hand, there can be no programs $Q$ and $S$ such that $\pi_{(a\,b)}=(QR)S$ since we cannot rewrite the rule body $b$ of $R$ into $a$ and $b$ simultaneously via composition on the right. This shows \begin{align*} R<\pi_{(a\,b)}. \end{align*} \end{example} The following simple example shows that syntactic similarity and logical equivalence are `orthogonal' concepts. \begin{example} The empty program is logically equivalent with respect to the least model semantics to the propositional program $a\leftarrow a$ consisting of a single rule. Since we cannot obtain the rule $a\leftarrow a$ from the empty program via composition, logical equivalence does not imply syntactic similarity. For the other direction, the computations \begin{align*} \left\{ \begin{array}{l} a\\ b\leftarrow a \end{array} \right\}= \left\{ \begin{array}{l} a\\ b\leftarrow a,b \end{array} \right\}\{b\}^\ominus \quad\text{and}\quad \left\{ \begin{array}{l} a\\ b\leftarrow a,b \end{array} \right\}=\left\{ \begin{array}{l} a\\ b\leftarrow a \end{array} \right\}\{b\}^\oplus \end{align*} show that the programs $P=\{a,\;b\leftarrow a\}$ and $R=\{a,\;b\leftarrow a,b\}$ are syntactically similar; however, $P$ and $R$ are not logically equivalent. \end{example} \section{Conclusion}\label{sec:Conclusion} This paper showed how a qualitative and algebraic notion of syntactic logic program similarity can be constructed from the sequential decomposition of programs. We derived some elementary properties of syntactic similarity and, more importantly, demonstrated how it can be used to answer queries across different domains by giving some illustrative examples. Interestingly, in \prettyref{exa:Plus}, in the process of answering queries in the list domain by translating it to the seemingly simpler domain of numerals, we obtained `entangled' terms of the form $s([\;\,])$ and $s([b,c])$ which are neither numerals nor lists. We believe that `dual' syntactic objects of this form---which under the conventional doctrine of programming are not well-typed (see, for example, the remarks in \cite[§5.8.2]{Apt97})---are characteristic for `creative' analogies across different domains and deserve special attention. More precisely, if we think of (logic) programs as tools for solving problems, then using those tools `creatively' often requires, as in the example mentioned above, a tight coupling between seemingly incompatible objects. However, if those objects are statically typed by the programmer, then this might prevent the creation and exploitation of useful analogical `bridges' for knowledge transfer. \bibliographystyle{acmtrans}
{'timestamp': '2021-09-14T02:13:47', 'yymm': '2109', 'arxiv_id': '2109.05300', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05300'}
arxiv
\section{Introduction} Natural language processing (NLP) has long recognised morphosyntactic features as necessary for solving advanced natural language understanding (NLU) tasks. An~enormous impact of contextual language models on presumably all NLP tasks has slightly weakened the~importance of morphosyntactic analysis. As morphosytnactic features are encoded to some extent in contextual word embeddings \cite[e.g.][]{tenney2018what,lin-etal-2019-open}, doubts arise as to whether explicit morphosyntactic knowledge is still needed. For example, \citet{glavas-vulic-2021-supervised} have recently investigated an~intermediate fine-tuning contextual language models on the~dependency parsing task and suggested that this step does not significantly contribute to advance NLU models. Conversely, \citet{warstadt-etal-2019-investigating} reveal the~powerlessness of contextual language models in encoding linguistic phenomena like negation. This is in line with our intuition about representing negation in Polish sentences (see Figure \ref{fig:trees}). It does not seem trivial to differentiate between the~contradicting meanings of these sentences using contextual language models, as the~word context is similar. The~morphosyntactic features, e.g. parts of speech PART vs. INTJ, and dependency labels \textit{advmod:neg} vs. \textit{discourse:intj}, could be beneficial in determining correct reading. \begin{figure*}[ht!] \centering \begin{dependency}[theme = simple, label style={font=\normalsize}] \begin{deptext}[column sep=0.25cm] (1) \& Nie \& śpię \\ \& \textsc{part} \& \textsc{verb}\\ \& (\textit{I}) \textit{don't} \& \textit{sleep}\\ \end{deptext} \depedge{3}{2}{advmod:neg} \deproot[edge height=5ex]{3}{root} \end{dependency} \begin{dependency}[theme = simple, label style={font=\normalsize}] \begin{deptext}[column sep=0.25cm] (2) \& Nie \& , \& nie \& śpię \\ \&\textsc{intj} \& \textsc{punct} \& \textsc{part} \& \textsc{verb}\\ \& \textit{No} \& , \& (\textit{I}) \textit{don't} \& \textit{sleep}\\ \end{deptext} \depedge{5}{4}{advmod:neg} \deproot[edge height=5ex]{5}{root} \depedge{5}{3}{punct} \depedge{5}{2}{discourse:intj} \end{dependency} \begin{dependency}[theme = simple, label style={font=\normalsize}] \begin{deptext}[column sep=0.25cm] (3) \& Nie \& , \& śpię \\ \& \textsc{intj} \& \textsc{punct} \& \textsc{verb}\\ \& \textit{No} \& , \& (\textit{I}) \textit{sleep}\\ \end{deptext} \deproot[edge height=5ex]{4}{root} \depedge{4}{3}{punct} \depedge{4}{2}{discourse:intj} \end{dependency} \caption{UD trees of Polish sentences: (1) and (2) mean a~\textit{non-sleeping} situation and (3) means \textit{sleeping}.} \label{fig:trees} \end{figure*} In order to verify the~influence of explicit morphosyntactic knowledge on NLU tasks, it is necessary to design a~technique for injecting this knowledge into models or to build morphosyntax-aware representations. The~first research direction was initiated by \citet{glavas-vulic-2021-supervised}. Our objective is to provide a~tool for predicting high-quality morphosyntactic features and exposing their embeddings. These~vectors can be directly combined with contextual word embeddings to build morphosyntactically informed word representations. The emergence of publicly available NLP datasets, e.g. Universal Dependencies \cite{ud25data}, stimulates the development of NLP systems. Some of them are optimised for efficiency, e.g. spaCy \cite{spacy}, and other for accuracy, e.g. UDPipe \cite{straka-2018-udpipe}, the~Stanford system \cite{dozat-manning-2018-simpler}, Stanza \cite{qi-etal-2020-stanza}. In this paper, we introduce COMBO, an~open-source fully neural NLP system which is optimised for both training efficiency and prediction quality. Due to its~end-to-end architecture, which is an~innovation within morphosyntactic analysers, COMBO is faster in training than the~SOTA pipeline-based systems, e.g. Stanza. As a result of applying modern NLP solutions (e.g. contextualised word embeddings), it qualitatively outperforms other systems. COMBO analyses tokenised sentences and predicts morphosyntactic features of tokens (i.e. parts of speech, morphological features, and lemmata) and syntactic structures of sentences (i.e. dependency trees and enhanced dependency graphs). At the same time, its module, COMBO-vectoriser, extracts vector representations of the~predicted features from hidden layers of individual predictors. COMBO user guide is in \S \ref{sec:getting_started} and a~live demo is available on the~website \url{http://combo-demo.nlp.ipipan.waw.pl}. \paragraph{Contributions} 1) We implement COMBO (\S \ref{sec:architecture}), a~fully neural NLP system for part-of-speech tagging, morphological analysis, lemmatisation, and (enhanced) dependency parsing, together with COMBO-vectoriser for revealing vector representations of predicted categorical features. COMBO is implemented as a~Python package which is easy to install and to integrate into a~Python code. 2) We pre-train models for over 40 languages that can be automatically downloaded and directly used to process new texts. 3) We evaluate COMBO and compare its performance with two state-of-the-art systems, spaCy and Stanza (\S \ref{sec:evaluation}). \section{COMBO Architecture} \label{sec:architecture} COMBO's architecture (see Figure~\ref{fig:overview}) is based on the~forerunner \cite{rybak-wroblewska-2018-semi} implemented in the~Keras framework. Apart from a~new implementation in the~PyTorch library \cite{NEURIPS2019_9015}, the~novelties are the~BERT-based encoder, the~EUD prediction module, and COMBO-vectoriser extracting embeddings of UPOS and DEPREL from the~last hidden layers of COMBO's tagging and dependency parsing module, respectively. This section provides an~overview of COMBO's modules. Implementation details are in Appendix \ref{sec:implementationDetails}. \begin{figure}[!h] \centering \includegraphics[width=\linewidth]{pictures/COMBO_architecture_new.pdf} \caption{\label{fig:overview}COMBO architecture. Explanations:\\ \includegraphics[scale=0.8]{pictures/cnn.pdf} \includegraphics[scale=0.8]{pictures/fc.pdf} \includegraphics[scale=0.8]{pictures/emb.pdf} \includegraphics[scale=0.8]{pictures/bilstm2.pdf} \includegraphics[scale=0.8]{pictures/optional.pdf} \includegraphics[scale=0.8]{pictures/required.pdf}} \end{figure} \paragraph{Local Feature Extractors} \label{sec:localFeatureExtraction} Local feature extractors (see Figure~\ref{fig:overview}) encode categorical features (i.e. words, parts of speech, morphological features, lemmata) into vectors. The~feature bundle is configurable and limited by the~requirements set for COMBO. For instance, if we train only a~dependency parser, the~following features can be input to COMBO: internal character-based word embeddings (\textsc{char}), pre-trained word embeddings (\textsc{word}), and embeddings of lemmata (\textsc{lemma}), parts of speech (\textsc{upos}) and morphological features (\textsc{ufeats}). If we train a~morphosyntactic analyser (i.e. tagger, lemmatiser and parser), internal word embeddings (\textsc{char}) and pre-trained word embeddings (\textsc{word}), if available, are input to COMBO. Words and lemmata are always encoded using character-based word embeddings (\textsc{char} and \textsc{lemma}) estimated during system training with a~dilated convolutional neural network (CNN) encoder \cite{dcnn:2015,strubell-etal-2017-fast}. Additionally, words can be represented using pre-trained word embeddings (\textsc{word}), e.g. fastText \cite{grave2018learning}, or BERT \cite{bert:2018}. The~use of pre-trained embeddings is an~optional functionality of the system configuration. COMBO freezes pre-trained embeddings (i.e. no fine-tuning) and uses their transformations, i.e. embeddings are transformed by a~single fully connected (FC) layer. Part-of-speech and morphological embeddings (\textsc{upos} and \textsc{ufeats}) are estimated during system training. Since more than one morphological feature can attribute a~word, embeddings of all possible features are estimated and averaged to build a~final morphological representation. \paragraph{Global Feature Encoder} \label{sec:globalFeatureExtraction} The~encoder uses concatenations of local feature embeddings. A sequence of these vectors representing all the~words in a~sentence is processed by a~bidirectional LSTM \cite{lstm:1997,bilstm:2005}. The~network learns the~context of each word and encodes its global (contextualised) features (see Figure \ref{fig:global}). Global feature embeddings are input to the~prediction modules. \begin{figure}[h!] \centering \includegraphics[width=0.5\linewidth]{pictures/Global_features.pdf} \caption{\label{fig:global}Estimation of global feature vectors.\\ \includegraphics[scale=0.8]{pictures/biLSTM.pdf} \includegraphics[scale=0.8]{pictures/global.pdf}} \end{figure} \vspace*{-6mm} \paragraph{Tagging Module} \label{sec:tagger} The~tagger takes global feature vectors as input and predicts a~universal part of speech (\textsc{upos}), a~language-specific tag (\textsc{xpos}), and morphological features (\textsc{ufeats}) for each word. The~tagger consists of two linear layers followed by a~softmax. Morphological features build a~disordered set of category-value pairs (e.g. Number=Plur). Morphological feature prediction is thus implemented as several classification problems. The~value of each morphological category is predicted with a~FC network. Different parts of speech are assigned different sets of morphological categories (e.g. a~noun can be attributed with grammatical gender, but not with grammatical tense). The~set of possible values is thus extended with the~NA (not applicable) symbol. It allows the model to learn that a~particular category is not a property of a word. \paragraph{Lemmatisation Module} \label{sec:lemmatizer} The~lemmatiser uses an~approach similar to character-based word embedding estimation. A~character embedding is concatenated with the~global feature vector and transformed by a linear layer. The lemmatiser takes a sequence of such character representations and transforms it using a dilated CNN. The softmax function over the result produces the sequence of probabilities over a character vocabulary to form a lemma. \begin{figure}[!h] \centering \includegraphics[width=1\linewidth]{pictures/arc_prediction.pdf} \caption{\label{fig:tree}Prediction of dependency arcs.} \end{figure} \paragraph{Parsing Module} \label{sec:parser} Two single FC layers transform global feature vectors into head and dependent embeddings (see Figure \ref{fig:tree}). Based on these representations, a~dependency graph is defined as an~adjacency matrix with columns and rows corresponding to heads and dependents, respectively. The~adjacency matrix elements are dot products of all pairs of the~head and dependent embeddings (the~dot product determines the certainty of the~edge between two words). The~softmax function applied to each row of the~matrix predicts the~adjacent head-dependent pairs. This approach, however, does not guarantee that the~resulting adjacency matrix is a~properly built dependency tree. The~Chu-Liu-Edmonds algorithm \cite{chuLiu:65,Edmonds:67} is thus applied in the~last prediction step. \begin{figure}[h!] \centering \includegraphics[width=\linewidth]{pictures/label_prediction.pdf} \caption{\label{fig:labels}Prediction of grammatical functions.} \end{figure} The~procedure of predicting words' grammatical functions (aka dependency labels) is shown in Figure \ref{fig:labels}. A~dependent and its head are represented as vectors by two single FC layers. The~dependent embedding is concatenated with the~weighted average of (hypothetical) head embeddings. The~weights are the values from the corresponding row of the~adjacency matrix, estimated by the~arc prediction module. Concatenated vector representations are then fed to a~FC layer with the~softmax activation function to predict dependency labels. \paragraph{EUD Parsing Module} Enhanced Universal Dependencies (EUD) are predicted similarly to dependency trees. The~EUD parsing module is described in details in \citet{klimaszewski-wroblewska-2021-combo}. \begin{table*}[ht!] \renewcommand\tabcolsep{8pt} \setlength\aboverulesep{1pt} \setlength\belowrulesep{1pt} \fontsize{10}{12}\selectfont{ \begin{center} \begin{tabular}{lrrrrrrrrr} \toprule System & UPOS & XPOS & UFeat & Lemma & UAS & LAS & CLAS & MLAS & BLEX \\ \midrule \multicolumn{10}{c}{English EWT (isolating)} \\ \hline spaCy &93.79 &93.10 &94.89 &NA &83.38 &79.76 &75.74 &68.91 &NA \\ Stanza &96.36 &96.15 &97.01 &\bf98.18 &89.64 &86.89 &83.84 &79.44 &82.03\\ COMBO &95.60 &95.21 &96.60 &97.43 &88.56 &85.58 &82.35 &76.56 &79.78 \\ COMBO$_{\textsc{bert}}$ &\bf96.57 &\bf96.44 &\bf97.24 &97.86 &\bf91.76 &\bf89.28 &\bf86.83 &\bf81.71 &\bf84.38 \\ \hline \multicolumn{10}{c}{Arabic PADT (fusional)} \\ \hline spaCy &90.27 &82.15 &82.70 &NA &74.24 &67.28 &63.28 &50.48 &NA\\ Stanza &96.98 &93.97 &94.08 &\bf95.26 &87.96 &83.74 &80.57 &74.96 &\bf76.80\\ COMBO &96.71 &93.72 &93.83 &93.54 &87.06 &82.70 &79.46 &73.25 &73.64\\ COMBO$_{\textsc{bert}}$ &\bf97.04 &\bf94.83 &\bf95.05 &93.95 &\bf89.21 &\bf85.09 &\bf82.36 &\bf76.82 &76.67\\ \hline \multicolumn{10}{c}{Polish PDB (fusional)} \\ \hline spaCy &96.14 &86.94 &87.41 &NA &86.73 &82.06 &79.00 &65.42 &NA \\ Stanza &98.47 &94.20 &94.42 &97.43 &93.15 &90.84 &88.73 &81.98 &85.75 \\ COMBO &98.24 &94.26 &94.53 &97.47 &92.87 &90.45 &88.07 &81.31 &85.53\\ COMBO$_{\textsc{bert}}$ &\bf98.97 &\bf96.54 &\bf96.80 &\bf98.06 &\bf95.60 &\bf93.93 &\bf92.34 &\bf87.59 &\bf89.91 \\ \hline \multicolumn{10}{c}{Finnish TDT (agglutinative)} \\ \hline spaCy &92.15 &93.34 &87.89 &NA &80.06 &74.75 &71.52 &61.95 &NA\\ Stanza &97.24 &97.96 &95.58 &\bf95.24 &89.57 &87.14 &85.52 &80.52 &\bf81.05\\ COMBO &96.72 &98.02 &94.04 &88.73 &89.73 &86.70 &84.56 &77.63 &72.42\\ COMBO$_{\textsc{bert}}$ &\bf98.29 &\bf99.00 &\bf97.30 &89.48 &\bf94.11 &\bf92.52 &\bf91.34 &\bf87.18 &77.84\\ \hline \multicolumn{10}{c}{Korean Kaist (agglutinative)} \\ \hline spaCy &85.21 &72.33 &NA &NA &76.15 &68.13 &61.98 &57.52 &NA\\ Stanza &95.45 &\bf86.31 &NA &\bf93.02 &88.42 &86.39 &83.97 &80.64 &\bf77.59\\ COMBO &94.46 &81.66 &NA &89.16 &87.31 &85.12 &82.70 &78.38 &72.79\\ COMBO$_{\textsc{bert}}$ &\bf95.89 &85.16 &NA &89.95 &\bf89.77 &\bf87.83 &\bf85.96 &\bf82.66 &75.89\\ \hline \multicolumn{10}{c}{Turkish IMST (agglutinative)} \\ \hline spaCy &87.66 &86.18 &82.26 &NA &60.43 &51.32 &47.74 &37.28 &NA\\ Stanza &\bf95.98 &\bf95.18 &\bf93.77 &96.73 &74.14 &67.52 &64.03 &58.13 &61.91\\ COMBO &93.60 &92.36 &88.88 &96.47 &72.00 &64.48 &60.48 &49.88 &58.75\\ COMBO$_{\textsc{bert}}$ &95.14 &94.27 &93.56 &\bf97.54 &\bf78.53 &\bf72.03 &\bf68.88 &\bf60.55 &\bf67.13\\ \hline \multicolumn{10}{c}{Basque BDT (agglutinative with fusional verb morphology)} \\ \hline spaCy &91.96 &NA &86.67 &NA &76.11 &70.28 &66.96 &54.46 &NA\\ Stanza &96.23 &NA &93.09 &\bf96.52 &86.19 &82.76 &81.30 &73.56 &78.27\\ COMBO &94.28 &NA &90.44 &95.47 &84.64 &80.44 &78.82 &67.33 &74.95\\ COMBO$_{\textsc{bert}}$ &\bf96.26 &NA &\bf93.84 &96.38 &\bf88.73 &\bf85.80 &\bf84.93 &\bf75.96 &\bf81.25\\ \hline \multicolumn{10}{c}{\bf Average scores} \\ \hline spaCy &91.03 &85.67 &86.97 &NA &76.73 &70.51 &66.60 &56.57 &NA\\ Stanza &96.67 &93.96 &94.66 &\bf96.05 &87.01 &83.61 &81.14 &75.60 &77.63\\ COMBO &95.66 &92.54 &93.05 &94.04 &86.02 &82.21 &79.49 &72.05 &73.98\\ COMBO$_{\textsc{bert}}$ &\bf96.88 &\bf94.37 &\bf95.63 &94.75 &\bf89.67 &\bf86.64 &\bf84.66 &\bf78.92 &\bf79.01\\ \bottomrule \end{tabular} \end{center} } \caption{\label{tab:2} Processing quality (F$_1$ scores) of spaCy, Stanza and COMBO on the~selected UD treebanks (the language types are given in parentheses). The~highest scores are marked in bold.} \end{table*} \section{COMBO Performance} \label{sec:evaluation} \paragraph{Data} COMBO is evaluated on treebanks from the~Universal Dependencies repository \cite{ud25data}, preserving the~original splits into training, validation, and test sets. The~treebanks representing distinctive language types are summarised in Table \ref{tab:statistics} in Appendix~\ref{sec:data_statistics}. By default, pre-trained 300-dimensional fastText embeddings \cite{grave2018learning} are used. We also test encoding data with pre-trained contextual word embeddings (the~tested BERT models are listed in Table \ref{tab:berts} in Appendix \ref{sec:data_statistics}). The~UD datasets provide gold-standard tokenisation. If BERT intra-tokeniser splits a~word into sub-words, the~last layer embeddings are averaged to obtain a~single vector representation of this word. \paragraph{Qualitative Evaluation} \label{sec:resultOverview} Table \ref{tab:2} shows COMBO results of processing the~selected UD treebanks.\footnote{Check the~prediction quality for other languages at: \compacturl{https://gitlab.clarin-pl.eu/syntactic-tools/combo/-/blob/master/docs/performance.md}.} COMBO is compared with Stanza \cite{qi-etal-2020-stanza} and spaCy.\footnote{\compacturl{https://spacy.io} We use the~project template \compacturl{https://github.com/explosion/projects/tree/v3/pipelines/tagger_parser_ud}. The~lemmatiser is implemented as a standalone pipeline component in spaCy v3 and we do not test it.} The~systems are evaluated with the~standard metrics \cite{zeman-EtAl:2018:K18-2}: \textsc{F1}, \textsc{uas} (unlabelled attachment score), \textsc{las} (labelled attachment score), \textsc{mlas} (morphology-aware \textsc{las}) and \textsc{blex} (bi-lexical dependency score).\footnote{\compacturl{http://universaldependencies.org/conll18/conll18_ud_eval.py} (CoNLL 2018 evaluation script).} COMBO and Stanza undeniably outrun spaCy models. COMBO using non-contextualised word embeddings is outperformed by Stanza in many language scenarios. However, COMBO supported with BERT-like word embeddings beats all other solutions and is currently the~SOTA system for morphosyntactic analysis. Regarding lemmatisation, Stanza has an~advantage over COMBO in most tested languages. This is probably due to the fact that Stanza lemmatiser is enhanced with a~key-value dictionary, whilst COMBO lemmatiser is fully neural. It is not surprising that a~dictionary helps in lemmatisation of isolating languages (English). However, the~dictionary approach is also helpful for agglutinative languages (Finnish, Korean, Basque) and for Arabic, but not for Polish (fusional languages). Comparing COMBO models estimated with and without BERT embeddings, we note that BERT boost only slightly increases the~quality of lemma prediction in the~tested fusional and agglutinative~languages. \begin{table*}[ht!] \renewcommand\tabcolsep{9pt} \setlength\aboverulesep{1pt} \setlength\belowrulesep{1pt} \fontsize{10}{12}\selectfont{ \begin{center} \begin{tabular}{l|c|cccc|cc} \toprule \multirow{2}{*}{Treebank} & spaCy & \multicolumn{4}{c|}{Stanza} & \multicolumn{2}{c}{COMBO}\\ & & Tagger & Lemmatiser & Parser & Total & fastText & BERT\\ \midrule English EWT & 00:22:34 & 02:08:51 & 02:12:17 & 02:29:13 & 06:50:21 & 01:26:55 & 1:54:11 \\ Polish PDB & 01:07:55 & 04:36:51 & 03:19:04 & 05:08:41 & 13:04:36 & 02:39:44 & 3:31:41\\ \bottomrule \end{tabular} \end{center}} \caption{\label{tab:5}Training time of spaCy, Stanza and COMBO. } \end{table*} For a~complete insight into the~prediction quality, we evaluate individual \textsc{upos} and \textsc{udeprel} predictions in English (the~isolating language), Korean (agglutinative) and Polish (fusional). Result visualisations are in Appendix \ref{sec:visualisations}. COMBO took part in IWPT 2021 Shared Task on Parsing into Enhanced Universal Dependencies \cite{bouma-etal-2021-raw}, where it ranked 4th.\footnote{\compacturll{https://universaldependencies.org/iwpt21/results.html}} In addition to \textsc{elas} and \textsc{eulas} metrics, the~third evaluation metric was \textsc{las}. COMBO ranked 2nd, achieving the~average \textsc{las} of 87.84\%. The~score is even higher than the~average \textsc{las} of 86.64\% in Table \ref{tab:2}, which is a~kind of confirmation that our evaluation is representative, reliable, and fair. \paragraph{Downstream Evaluation} According to the~results in Table \ref{tab:2}, COMBO predicts high-quality dependency trees and parts of speech. We therefore conduct a~preliminary evaluation of morphosyntactically informed word embeddings in the~textual entailment task (aka natural language inference, NLI) in English \cite{Bentivogli:2016} and Polish \cite{wroblewska-krasnowska-kieras-2017-polish}. We compare the~quality of entailment classifiers with two FC layers trained on max/mean-pooled BERT embeddings and sentence representations estimated by a~network with two transformer layers which is given morphosyntactically informed word embeddings (i.e. BERT-based word embeddings concatenated with \textsc{upos} embeddings, \textsc{deprel} embeddings, and BERT-based embeddings of the~head word). The~morphosyntactically informed English NLI classifier achieves an~accuracy of 78.84\% and outperforms the~max/mean-pooled classifiers by 20.77~pp and 5.44~pp, respectively. The~Polish syntax-aware NLI classifier achieves an~accuracy of 91.60\% and outperforms the~max/mean-pooled classifiers by 17.2~pp and 7.7~pp, respectively. \paragraph{Efficiency Evaluation} We also compare spaCy, Stanza and COMBO in terms of their efficiency, i.e. training and prediction speed.\footnote{\label{footnote:gpu}A~single NVIDIA V100 card is used in all tests.} According to the~results (see Tables \ref{tab:5} and \ref{tab:6}), spaCy is the~SOTA system, and the~other two are not even close to its processing time. Considering COMBO and Stanza, whose prediction quality is significantly better than spaCy, COMBO is 1.5 times slower (2 times slower with BERT) than Stanza in predicting, but it is definitely faster in training. The~reason for large discrepancies in training times is the~different architecture of these two systems. Stanza is a~pipeline-based system, i.e. its modules are trained one after the~other. COMBO is an~end-to-end system, i.e. its modules are jointly trained and the~training process is therefore faster. \begin{table}[ht!] \setlength\aboverulesep{1pt} \setlength\belowrulesep{1pt} \fontsize{10}{12}\selectfont{ \begin{center} \begin{tabular*}{\linewidth}{l|ccc} \toprule Treebank & Stanza & COMBO & COMBO$_{\textsc{bert}}$\\ \midrule English EWT & $4.7\times$ & $6.8\times$ & $10.8\times$\\ Polish PDB & $4.1\times$ & $5.8\times$ & $10.6\times$\\ \bottomrule \end{tabular*} \end{center}} \caption{\label{tab:6}Prediction time of Stanza and COMBO relative to spaCy ($1\times$) on English and Polish test data. } \end{table} \iffalse \subsection{Extra Facilities} COMBO includes two innovative modules for thematic role labelling and for sentence embedding estimation. Thematic label prediction is evaluated on an~extended version of UD-like Polish dependency treebank \cite{wrob:18},\footnote{\compacturll{http://git.nlp.ipipan.waw.pl/alina/PDBUD/tree/master/PDB-UD_current/PDB-UD-sem}} in which the~thematic roles of some dependents are in the~11th column. The~quality of COMBO semantic labelling is 79.61 of SLAS F$_1$\footnote{SLAS, i.e. semantic-aware labelled attachment \cite{wro:18b}, is the~harmonic mean ($F_1 = \frac{2PR}{P+R}$) of precision $P$ and recall $R$. $P$ is the ratio of the number of the correct words to the total number of the predicted content words. $R$ is the~ratio of the~number of the correct words to the total number of the gold-standard content words. A~predicted word is considered to be correct, if it is assigned the~correct head, dependency label, and thematic role (or `no semantic role').} (precision of 79.67\% and recall of 79.55\%). Evaluation of COMBO sentences embeddings requires large-scale NLU research.\footnote{According to the~empirical study on retention of linguistic information in sentence embeddings using probing tasks \cite{kras:wro:19}, parser-based sentence embeddings encode linguistic information more accurately than fastText \cite{grave2018learning}, LASER \cite{arte:schw:2018} or BERT \cite{bert:2018}.} It is outside the~scope of this paper and we intend to conduct such research in the~future. \fi \section{Getting Started with COMBO} \label{sec:getting_started} \paragraph{Prediction} COMBO provides two main prediction modes: a~Python library and a~command-line interface (CLI). The~Python package mode supports automated model download. The~code snippet demonstrates downloading a~pre-trained Polish model and processing a~sentence: \vspace{-0.5cm} \begin{minted} [ frame=lines, framesep=2mm, baselinestretch=1.2, fontsize=\footnotesize, ] {python} from combo.predict import COMBO nlp = COMBO.from_pretrained("polish") sentence = nlp("Ala ma kota.") print(sentence.tokens) \end{minted} \vspace{-0.4cm} To download a~model for another language, select its name from the~list of pre-trained models.\footnote{The~list of the~pretrained COMBO models: \compacturll{https://gitlab.clarin-pl.eu/syntactic-tools/combo/-/blob/master/docs/models.md\#pre-trained-models}} The~Python mode also supports acquisition of \textsc{deprel} or \textsc{upos} embeddings, for example: \vspace{-0.5cm} \begin{minted} [ frame=lines, framesep=2mm, baselinestretch=1.2, fontsize=\footnotesize, ] {python} sentence = nlp("Ala ma kota.") chosen_token = sentence.tokens[1] print(chosen_token.embeddings["upostag"]) \end{minted} \vspace{-0.4cm} In CLI mode, COMBO processes sentences using either a~downloaded model or a~model trained by yourself. CLI works on raw texts and on the~CoNLL-U files (i.e. with tokenised sentences and even morphologically annotated tokens): \vspace{-0.5cm} \begin{minted} [ frame=lines, framesep=2mm, baselinestretch=1.2, fontsize=\footnotesize, ] {bash} combo --mode predict \ --model_path model.tar.gz \ --input_file input.conllu \ --output_file output.conllu \end{minted} \vspace{-0.4cm} \paragraph{Model Training} COMBO CLI allows to train new models for any language. The~only requirement is a~training dataset in the~CoNLL-U/CoNLL-X format. In the~default setup, tokenised sentences are input and all possible predictors are trained: \vspace{-0.5cm} \begin{minted} [ frame=lines, framesep=2mm, baselinestretch=1.2, fontsize=\footnotesize, ] {bash} combo --mode train \ --training_data training.conllu \ --validation_data valid.conllu \end{minted} \vspace{-0.4cm} \noindent If we only train a~dependency parser, the~default setup should be changed with configuration flags: \mintinline{bash}{--features} with a~list of input features and \mintinline{bash}{--targets} with a~list of prediction targets. \section{Conclusion} \label{sec:conclusions} We have presented COMBO, the~SOTA system for morphosyntacic analysis, i.e. part-of-speech tagging, morphological analysis, lemmatisation, and (enhanced) dependency parsing. COMBO is a~language-agnostic and format-independent system (i.e. it supports the~CoNLL-U and CoNLL-X formats). Its implementation as a Python package allows effortless installation, and incorporation into any Python code or usage in the~CLI mode. In the~Python mode, COMBO supports automated download of pre-trained models for multiple languages and outputs not only categorical morphosyntactic features, but also their embeddings. In the~CLI mode, pre-trained models can be manually downloaded or trained from scratch. The~system training is fully configurable in respect of the~range of input features and output predictions, and the~method of encoding input data. \noindent Last but not least, COMBO maintains a balance between efficiency and quality. Admittedly, it is not as fast as spaCy, but it is much more efficient than Stanza considering the~training time. Tested on the~selected UD treebanks, COMBO morphosyntactic models enhanced with BERT embeddings outperform spaCy and Stanza models. \section*{Acknowledgments} The authors would like to thank Piotr Rybak for his design and explanations of the~architecture of COMBO's forerunner. The research presented in this paper was founded by SONATA 8 grant no 2014/15/D/HS2/03486 from the National Science Centre Poland and the European Regional Development Fund as a part of the 2014-2020 Smart Growth Operational Programme, CLARIN -- Common Language Resources and Technology Infrastructure, project no. POIR.04.02.00-00C002/19. The~computing was performed at Pozna\'{n} Supercomputing and Networking Center.
{'timestamp': '2021-09-14T02:16:40', 'yymm': '2109', 'arxiv_id': '2109.05361', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05361'}
arxiv
\section{Copyright} All papers submitted for publication by AAAI Press must be accompanied by a valid signed copyright form. They must also contain the AAAI copyright notice at the bottom of the first page of the paper. There are no exceptions to these requirements. If you fail to provide us with a signed copyright form or disable the copyright notice, we will be unable to publish your paper. There are \textbf{no exceptions} to this policy. You will find a PDF version of the AAAI copyright form in the AAAI AuthorKit. Please see the specific instructions for your conference for submission details. \section{Formatting Requirements in Brief} We need source and PDF files that can be used in a variety of ways and can be output on a variety of devices. The design and appearance of the paper is strictly governed by the aaai style file (aaai22.sty). \textbf{You must not make any changes to the aaai style file, nor use any commands, packages, style files, or macros within your own paper that alter that design, including, but not limited to spacing, floats, margins, fonts, font size, and appearance.} AAAI imposes requirements on your source and PDF files that must be followed. Most of these requirements are based on our efforts to standardize conference manuscript properties and layout. All papers submitted to AAAI for publication will be recompiled for standardization purposes. Consequently, every paper submission must comply with the following requirements: \begin{itemize} \item Your .tex file must compile in PDF\LaTeX{} --- (you may not include .ps or .eps figure files.) \item All fonts must be embedded in the PDF file --- including your figures. \item Modifications to the style file, whether directly or via commands in your document may not ever be made, most especially when made in an effort to avoid extra page charges or make your paper fit in a specific number of pages. \item No type 3 fonts may be used (even in illustrations). \item You may not alter the spacing above and below captions, figures, headings, and subheadings. \item You may not alter the font sizes of text elements, footnotes, heading elements, captions, or title information (for references and mathematics, please see the limited exceptions provided herein). \item You may not alter the line spacing of text. \item Your title must follow Title Case capitalization rules (not sentence case). \item Your .tex file must include completed metadata to pass-through to the PDF (see PDFINFO below). \item \LaTeX{} documents must use the Times or Nimbus font package (you may not use Computer Modern for the text of your paper). \item No \LaTeX{} 209 documents may be used or submitted. \item Your source must not require use of fonts for non-Roman alphabets within the text itself. If your paper includes symbols in other languages (such as, but not limited to, Arabic, Chinese, Hebrew, Japanese, Thai, Russian and other Cyrillic languages), you must restrict their use to bit-mapped figures. Fonts that require non-English language support (CID and Identity-H) must be converted to outlines or 300 dpi bitmap or removed from the document (even if they are in a graphics file embedded in the document). \item Two-column format in AAAI style is required for all papers. \item The paper size for final submission must be US letter without exception. \item The source file must exactly match the PDF. \item The document margins may not be exceeded (no overfull boxes). \item The number of pages and the file size must be as specified for your event. \item No document may be password protected. \item Neither the PDFs nor the source may contain any embedded links or bookmarks (no hyperref or navigator packages). \item Your source and PDF must not have any page numbers, footers, or headers (no pagestyle commands). \item Your PDF must be compatible with Acrobat 5 or higher. \item Your \LaTeX{} source file (excluding references) must consist of a \textbf{single} file (use of the ``input" command is not allowed. \item Your graphics must be sized appropriately outside of \LaTeX{} (do not use the ``clip" or ``trim'' command) . \end{itemize} If you do not follow these requirements, your paper will be returned to you to correct the deficiencies. \section{What Files to Submit} You must submit the following items to ensure that your paper is published: \begin{itemize} \item A fully-compliant PDF file that includes PDF metadata. \item Your \LaTeX{} source file submitted as a \textbf{single} .tex file (do not use the ``input" command to include sections of your paper --- every section must be in the single source file). (The only allowable exception is .bib file, which should be included separately). \item The bibliography (.bib) file(s). \item Your source must compile on our system, which includes only standard \LaTeX{} 2020 TeXLive support files. \item Only the graphics files used in compiling paper. \item The \LaTeX{}-generated files (e.g. .aux, .bbl file, PDF, etc.). \end{itemize} Your \LaTeX{} source will be reviewed and recompiled on our system (if it does not compile, your paper will be returned to you. \textbf{Do not submit your source in multiple text files.} Your single \LaTeX{} source file must include all your text, your bibliography (formatted using aaai22.bst), and any custom macros. Your files should work without any supporting files (other than the program itself) on any computer with a standard \LaTeX{} distribution. \textbf{Do not send files that are not actually used in the paper.} We don't want you to send us any files not needed for compiling your paper, including, for example, this instructions file, unused graphics files, style files, additional material sent for the purpose of the paper review, and so forth. \textbf{Do not send supporting files that are not actually used in the paper.} We don't want you to send us any files not needed for compiling your paper, including, for example, this instructions file, unused graphics files, style files, additional material sent for the purpose of the paper review, and so forth. \textbf{Obsolete style files.} The commands for some common packages (such as some used for algorithms), may have changed. Please be certain that you are not compiling your paper using old or obsolete style files. \textbf{Final Archive.} Place your PDF and source files in a single archive which should be compressed using .zip. The final file size may not exceed 10 MB. Name your source file with the last (family) name of the first author, even if that is not you. \section{Using \LaTeX{} to Format Your Paper} The latest version of the AAAI style file is available on AAAI's website. Download this file and place it in the \TeX\ search path. Placing it in the same directory as the paper should also work. You must download the latest version of the complete AAAI Author Kit so that you will have the latest instruction set and style file. \subsection{Document Preamble} In the \LaTeX{} source for your paper, you \textbf{must} place the following lines as shown in the example in this subsection. This command set-up is for three authors. Add or subtract author and address lines as necessary, and uncomment the portions that apply to you. In most instances, this is all you need to do to format your paper in the Times font. The helvet package will cause Helvetica to be used for sans serif. These files are part of the PSNFSS2e package, which is freely available from many Internet sites (and is often part of a standard installation). Leave the setcounter for section number depth commented out and set at 0 unless you want to add section numbers to your paper. If you do add section numbers, you must uncomment this line and change the number to 1 (for section numbers), or 2 (for section and subsection numbers). The style file will not work properly with numbering of subsubsections, so do not use a number higher than 2. \subsubsection{The Following Must Appear in Your Preamble} \begin{quote} \begin{scriptsize}\begin{verbatim} \def\year{2022}\relax \documentclass[letterpaper]{article} \usepackage{aaai22} \usepackage{times} \usepackage{helvet} \usepackage{courier} \usepackage[hyphens]{url} \usepackage{graphicx} \urlstyle{rm} \def\UrlFont{\rm} \usepackage{graphicx} \usepackage{natbib} \usepackage{caption} \DeclareCaptionStyle{ruled}% {labelfont=normalfont,labelsep=colon,strut=off} \frenchspacing \setlength{\pdfpagewidth}{8.5in} \setlength{\pdfpageheight}{11in} \pdfinfo{ /Title (AAAI Press Formatting Instructions for Authors Using LaTeX -- A Guide) /Author (AAAI Press Staff, Pater Patel Schneider, Sunil Issar, J. Scott Penberthy, George Ferguson, Hans Guesgen, Francisco Cruz, Marc Pujol-Gonzalez) /TemplateVersion (2022.1) } \end{verbatim}\end{scriptsize} \end{quote} \subsection{Preparing Your Paper} After the preamble above, you should prepare your paper as follows: \begin{quote} \begin{scriptsize}\begin{verbatim} \begin{document} \maketitle \begin{abstract} \end{abstract}\end{verbatim}\end{scriptsize} \end{quote} \noindent You should then continue with the body of your paper. Your paper must conclude with the references, which should be inserted as follows: \begin{quote} \begin{scriptsize}\begin{verbatim} \section{Algorithm} \input{algorithm_table} \noindent We now present our algorithm \textsc{UC-CURL}\ and the key ideas used in designing the algorithm. Note that if the agent is aware of the true transition $P$, it can solve the following optimization problem for the optimal feasible policy. \begin{align} \max_{\rho(s,a)} f\big(\sum_{s,a}r(s, a)\rho(s,a)\big) \label{eq:optimization_equation} \end{align} with the following set of constraints, \begin{align} &\sum\nolimits_{s,a} \rho(s, a) = 1,\ \ \rho(s, a) \geq 0 \label{eq:valid_prob_constrant}\\ &\sum\nolimits_{a\in\mathcal{A}}\rho(s',a) = \sum\nolimits_{s,a}P(s'|s, a)\rho(s, a)\label{eq:transition_constraint}\\ &g\big(\sum_{s,a}c_1(s, a)\rho(s,a), \cdots, \sum_{s,a}c_d(s, a)\rho(s,a)\big) \leq 0\label{eq:cmdp_constraints} \end{align} for all $ s'\in\mathcal{S},~\forall~s\in\mathcal{S},$ and $\forall~a\in\mathcal{A}$. Equation \eqref{eq:transition_constraint} denotes the constraint on the transition structure for the underlying Markov Process. Equation \eqref{eq:valid_prob_constrant} ensures that the solution is a valid probability distribution. Finally, Equation \eqref{eq:cmdp_constraints} are the constraints for the constrained MDP setup which the policy must satisfy. Using the solution for $\rho$, we can obtain the optimal policy as: \begin{align} \pi^*(a|s) = \frac{\rho(s,a)}{\sum_{b\in\mathcal{A}}\rho(s,b)} \forall\ s,a \end{align} However, the agent does not have the knowledge of $P$ to solve this optimization problem, and thus starts learning the transitions with an arbitrary policy. We first note that if the agent does not have complete knowledge of the transition $P$ of the true MDP $\mathcal{M}$, it should be conservative in its policy to allow room to violate constraints. Based on this idea, we formulate the $\epsilon$-tight optimization problem by modifying the constraint in Equation \eqref{eq:cmdp_constraints} as. \begin{align} g\big(\sum_{s,a}(c_1\rho_\epsilon)(s,a), \cdots, \sum_{s,a}(c_1\rho_\epsilon)(s,a)\big) \leq -\epsilon \label{eq:eps_cmdp_constraints} \end{align} Let $\rho_\epsilon$ be the solution of the $\epsilon$-tight optimization problem, then the optimal conservative policy becomes: \begin{align} \pi_\epsilon^*(a|s) = \frac{\rho_\epsilon(s,a)}{\sum_{b\in\mathcal{A}}\rho_\epsilon(s,b)} \forall\ s,a \end{align} We are now ready to design our algorithm \textsc{UC-CURL}\ which is based on the optimism principle \cite{jaksch2010near}. The \textsc{UC-CURL}\ algorithm is presented in Algorithm \ref{alg:algorithm}. The algorithm proceeds in epochs $e$. The algorithm maintains three key variables $\nu_e(s,a)$, $N_e(s,a)$, and $\hat{P}(s,a,s')$ for all $s,a$. $\nu_e(s,a)$ stores the number of times state-action pair $(s,a)$ are visited in epoch $e$. $N_e(s,a)$ stores the number of times $(s,a)$ are visited till the start of epoch $e$. $\hat{P}(s,a,s')$ stores the number of times the system transitions to state $s'$ after taking action $a$ in state $s$. Another key parameter of the algorithm is $\epsilon_e = K\sqrt{(\log t_e)/t_e}$ where $t_e$ is the start time of the epoch $e$ and $K$ is a configurable constant. Using these variables, the agent solves for the optimal $\epsilon_e$-conservative policy for the optimistic MDP by replacing the constraints in Equation \eqref{eq:transition_constraint} by: \begin{align} &\sum\nolimits_{a\in\mathcal{A}}\rho_e(s',a) = \sum\nolimits_{s,a}\Tilde{P}_e(s'|s, a)\rho(s, a)\label{eq:opt_eps_transition_constraint}\\ &\|\Tilde{P}_e(\cdot|s,a) - \frac{\hat{P}(s,a,\cdot)}{1\vee N_e(s,a)}\|_1 \le \sqrt{\frac{14S\log(2At)}{1\vee N_e(s,a)}}\label{eq:opt_transition_probability} \end{align} for all $ s'\in\mathcal{S},~\forall~s\in\mathcal{S},$ and $\forall~a\in\mathcal{A}$. Equation \eqref{eq:opt_transition_probability} ensures that the agent searches for optimistic policy in the confidence intervals of the transition probability estimates. Let $\rho_e$ be the solution for $\epsilon_e$-tight optimization equation for the optimistic MDP. Then, we obtain the optimal conservative policy for epoch $e$ as: \begin{align} \pi_e(a|s) = \frac{\rho_e(s,a)}{\sum_{b\in\mathcal{A}}\rho_e(s,b)} \forall\ s,a \label{eq:opt_cons_optimal_policy} \end{align} The agent plays the optimistic conservative policy $\pi_e$ for epoch $e$. Note that the conservative parameter $\epsilon_e$ decays with time. As the agent interacts with the environment, the system model improves and the agent does not need to be as conservative as before. This allows us to bound both constraint violations and the objective regret. For the \textsc{UC-CURL}\ algorithm described in Algorithm \ref{alg:algorithm}, we choose $\{\epsilon_e\} = \{K\sqrt{(\log t_e)/t_e}\}$. However, if the agent has access to a lower bound $T_l$ (Assumption \ref{slaters_conditon}) on the time horizon $T$, the algorithm can change the $\epsilon_e$ in each epoch $e$ as follows. \begin{align} \epsilon_e =K\sqrt{\frac{\ln (t_e \vee T_{l})}{t_e\vee T_{l}}} \le \delta \end{align} Note that if $T_l = 0$, $\epsilon_e$ becomes as specified in Algorithm \ref{alg:algorithm} and if $T_l = T$, $\epsilon_e$ becomes constant for all epochs $e$. \section{Concentration bound results} We want to bound the deviation of the estimates of the estimated transition probabilities of the Markov Decision Processes $\mathcal{M}$. For that we use $\ell_1$ deviation bounds from \citep{weissman2003inequalities}. Consider, the following event, \begin{align} \mathcal{E}_t = \left\{\|\hat{P}(\cdot|s, a) - P(\cdot|s, a)\|_1 \leq \sqrt{\frac{14S\log(2AT)}{\max\{1, n(s,a)\}}}\forall (s,a)\in\mathcal{S}\times\mathcal{A}\right\} \end{align} where $n=\sum_{t'=1}^t \bm{1}_{\{s_{t'} = s, a_{t'}= a\}}$. Then we have, the following lemma: \begin{lemma}\label{lem:deviation_of_probability_estimates} The probability that the event $\mathcal{E}_t$ fails to occur us upper bounded by $\frac{1}{20t^6}$. \end{lemma} \begin{proof} From the result of \citep{weissman2003inequalities}, the $\ell_1$ distance of a probability distribution over $S$ events with $n$ samples is bounded as: \begin{align} \mathbb{P}\left(\|P(\cdot|s,a) - \hat{P}(\cdot|s,a)\|_1\geq \epsilon\right)\leq (2^S-2)\exp{\left(-\frac{n\epsilon^2}{2}\right)}\le (2^S)\exp{\left(-\frac{n\epsilon^2}{2}\right)} \end{align} This, for $\epsilon = \sqrt{\frac{2}{n(s,a)}\log(2^S20 SAt^7)}\leq \sqrt{\frac{14S}{n(s,a)}\log(2At)} \leq \sqrt{\frac{14S}{n(s,a)}\log(2AT)}$ gives, \begin{align} \mathbb{P}\left(\|P(\cdot|s,a) - \hat{P}(\cdot|s,a)\|_1\geq \sqrt{\frac{14S}{n(s,a)}\log(2At)}\right)&\leq (2^S)\exp{\left(-\frac{n(s,a)}{2}\frac{2}{n(s,a)}\log(2^S20 SAt^7)\right)}\\ &= 2^S \frac{1}{2^S 20 SAt^7}\\ &= \frac{1}{20ASt^7} \end{align} We sum over the all the possible values of $n(s,a)$ till $t$ time-step to bound the probability that the event $\mathcal{E}_t$ does not occur as: \begin{align} \sum_{n(s,a)=1}^t \frac{1}{20SAt^7} \leq \frac{1}{20SAt^6} \end{align} Finally, summing over all the $s,a$, we get, \begin{align} \mathbb{P}\left(\|P(\cdot|s,a) -\hat{P}(\cdot|s,a) \|_1\geq \sqrt{\frac{14S}{n(s,a)}\log(2At)}~\forall s,a\right) \leq \frac{1}{20t^6} \end{align} \end{proof} The second lemma is the Azuma-Hoeffding's inequality, which we use to bound Martingale difference sequences. \begin{lemma}[Azuma-Hoeffding's Inequality]\label{lem:azuma_inequality} Let $X_1,\cdots,X_n$ be a Martingale difference sequence such that $|X_i|\leq c$ for all $i\in\{1,2,\cdots, n\}$, then, \begin{align} \mathbb{P}\left(|\sum_{i=1}^nX_i|\geq \epsilon\right)\leq 2\exp{\left(-\frac{\epsilon^2}{2nc^2}\right)}\label{eq:azuma_hoeffdings} \end{align} \end{lemma} \begin{corollary} Let $X_1,\cdots,X_n$ be a Martingale difference sequence such that $|X_i|\leq c$ for all $i\in\{1,2,\cdots, n\}$, then, \begin{align} \mathbb{E}\left(|\sum_{i=1}^nX_i|\right)\leq \mathcal{O}(c\sqrt{n\log n}) \end{align} We can now use the Azuma-Hoeffding's inequality to upper bound the expected value of the expected value of the absolute value of the sum of the $n$ terms of the Martingale difference sequence $\{X_i\}_{i=1}^n$. \end{corollary} \begin{proof} \begin{align} \mathbb{E}\left(|\sum_{i=1}^nX_i|\right) &\leq c\sqrt{n\log n}\mathbb{P}\left(|\sum_{i=1}^nX_i|\leq c\sqrt{n\log n}\right) + cn\mathbb{P}\left(|\sum_{i=1}^nX_i|\geq c\sqrt{n\log n}\right)\label{eq:separation_to_probability}\\ &\leq c\sqrt{n\log n} + cn\left(2\exp{\left(-\frac{c^2n\log n}{2nc^2}\right)}\right)\label{eq:put_epsilon_in_azuma}\\ &= c\sqrt{n\log n} + cn\left(2\exp{\left(-\frac{\log n}{2}\right)}\right)\\ &= c\sqrt{n\log n} + cn\frac{2}{\sqrt{n}}\\ &= 3c\sqrt{n\log n}\\ \end{align} where Equation \eqref{eq:put_epsilon_in_azuma} follows by putting $\epsilon = c\sqrt{n\log n}$ in Equation \eqref{eq:azuma_hoeffdings}. \end{proof} \section{Conclusion} We considered the problem of constrained Markov Decision Process with concave objective and convex constraint. For this problem, we proposed \textsc{UC-CURL}\ algorithm which works on the principle of optimism. To bound the constraint violations, we solve for a conservative policy using an optimistic model for an $\epsilon$-tight optimization problem. Using a novel analysis based on Bellman error for infinite-horizon MDPs, we show the \textsc{UC-CURL}\ algorithm achieves $O(1/T)$ constraint violations with a regret bound of $\Tilde{O}(LdT_MS\sqrt{A/T})$. A major limitation of the work in its current form is the algorithm parameter $K$. Dynamically configuring $K$ is an interesting direction for future work. Other future works include making the algorithm more computationally efficient and creating model-free algorithms. \section{Bounding Constraint Violations}\label{app:constraint_violation_bounds} To bound the constraint violations $C(T)$, we break it into multiple components. We can then bound these components individually. \subsection{Constraint breakdown} We first break down our regret into multiple parts which will help us bound the regret. \begin{align} C(T) &= \left(g\left(\frac{1}{T}\sum_{t=1}^Tc_1(s_t, a_t),\cdots, \frac{1}{T}\sum_{t=1}^Tc_d(s_t, a_t)\right)\right)_+\\ &= \left(g\left(\frac{1}{T}\sum_{t=1}^Tc_1(s_t, a_t),\cdots, \frac{1}{T}\sum_{t=1}^Tc_d(s_t, a_t)\right) + \frac{1}{T}\sum_{e=1}^E T_e g\left(\zeta_{\pi_e}^{\Tilde{P}_e}(1),\cdots, \zeta_{\pi_e}^{\Tilde{P}_e}(d)\right) - \frac{1}{T}\sum_{e=1}^E T_e g\left(\zeta_{\pi_e}^{\Tilde{P}_e}(1),\cdots, \zeta_{\pi_e}^{\Tilde{P}_e}(d)\right)\right)_+\\ &\le \left(g\left(\frac{1}{T}\sum_{t=1}^Tc_1(s_t, a_t),\cdots, \frac{1}{T}\sum_{t=1}^Tc_d(s_t, a_t)\right) - \frac{1}{T}\sum_{e=1}^E T_e g\left(\zeta_{\pi_e}^{\Tilde{P}_e}(1),\cdots, \zeta_{\pi_e}^{\Tilde{P}_e}(d)\right) - \frac{1}{T}\sum_{e=1}^E T_e\epsilon_e\right)_+\\ &\le \left(g\left(\frac{1}{T}\sum_{t=1}^Tc_1(s_t, a_t),\cdots, \frac{1}{T}\sum_{t=1}^Tc_d(s_t, a_t)\right) - g\left(\frac{1}{T}\sum_{e=1}^E T_e\zeta_{\pi_e}^{\Tilde{P}_e}(1),\cdots, \frac{1}{T}\sum_{e=1}^E T_e\zeta_{\pi_e}^{\Tilde{P}_e}(d)\right) - \frac{1}{T}\sum_{e=1}^E T_e\epsilon_e\right)_+\\ &\le \left(L\sum_{i=1}^d\Big|\frac{1}{T}\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}\left(c_i(s_t, a_t) - \zeta_{\pi_e}^{\Tilde{P}_e}(i) \right)\Big| - \frac{1}{T}\sum_{e=1}^E T_e\epsilon_e\right)_+\\ &\le \left(L\sum_{i=1}^d\Big|\frac{1}{T}\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}\left(c_i(s_t, a_t) - \zeta_{\pi_e}^{P}(i) + \zeta_{\pi_e}^{P}(i) - \zeta_{\pi_e}^{\Tilde{P}_e}(i) \right)\Big| - \frac{1}{T}\sum_{e=1}^E T_e\epsilon_e\right)_+\\ &\le \left(\frac{L}{T}\sum_{i=1}^d\Big|\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}\left(c_i(s_t, a_t) - \zeta_{\pi_e}^{P}(i)\right)\Big| + \frac{L}{T}\sum_{i=1}^d\Big|\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}\left(\zeta_{\pi_e}^{P}(i) - \zeta_{\pi_e}^{\Tilde{P}_e}(i) \right)\Big| - \frac{1}{T}\sum_{e=1}^E T_e\epsilon_e\right)_+\\ &\le \left(C_3(T) + C_2(T) - C_1(T)\right)_+ \end{align} where Equation \eqref{eq:regret_use_optimism} comes from the fact that the policy $\pi_e$ is for the optimistic CMDP and provides a higher value of the function $f$. Equation \ref{eq:regret_use_concavity} comes from the concavity of the function $f$, and Equation \ref{eq:regret_use_lipschitz} comes from the Lipschitz continuity of the function $f$. The three terms in Equation \eqref{eq:define_broken_regret} are now defined as: \begin{align} C_1(T) &= \frac{1}{T}\sum_{e=1}^E T_e \epsilon_e \end{align} $C_1(T)$ denotes the gap left by playing the policy for $\epsilon_e$-tight optimization problem on the optimistic MDP. \begin{align} C_2(T) &= \frac{L}{T}\sum_{i=1}^d\Big|\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}\left(\zeta_{\pi_e}^{P}(i)-\zeta_{\pi_e}^{\Tilde{P}_e}(i) \right)\Big| \end{align} $C_2(T)$ denotes the difference between long-term average costs incurred by playing the policy $\pi_e$ on the true MDP with transitions $P$ and the optimistic MDP with transitions $\Tilde{P}$. This term is bounded similar to the bound of $R_2(T)$. \begin{align} C_3(T) &= \frac{L}{T}\sum_{i=1}^d\Big|\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}\left(c_i(s_t, a_t) - \zeta_{\pi_e}^{P}(i)\right)\Big| \end{align} $C_3(T)$ denotes the difference between long-term average costs incurred by playing the policy $\pi_e$ on the true MDP with transitions $P$ and the realized costs. This term is bounded similar to the bound of $R_3(T)$. \newpage \subsection{Bounding $C_1(T)$} Note that $C_1(T)$ allows us to violate constraints by not having the knowledge of the true MDP and allowing deviations of incurred costs from the expected costs. We now want to lower bound $C_1$ to allow us sufficient slackness. With this idea, we have the following set of equations. \begin{align} C_1(T) &= \frac{1}{T}\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}\epsilon_e\\ &= \frac{1}{T}\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}K\sqrt{\frac{\log t_e}{t_e}}\\ &\ge K\frac{1}{T}\sum_{e=E'}^E\sum_{t=t_e}^{t_{e+1}-1}\sqrt{\frac{\log (T/4)}{t_e}}\\ &\ge K\frac{1}{T}\sum_{e=E'}^E\sum_{t=t_e}^{t_{e+1}-1}\sqrt{\frac{\log (T/4)}{T}}\\ &= K\frac{1}{T}\left(T-t_{E'}\right)\sqrt{\frac{\log (T/4)}{T}}\\ &\ge K\frac{1}{2}\sqrt{\frac{\log (T/4)}{T}}\\ &\ge K\frac{1}{4}\sqrt{\frac{\log T}{T}} \end{align} where $E'$ is some epoch for which $T/4\le t_{E'} < {T/2}$. \subsection{Bounding $C_2(T)$, and $C_3(T)$} We note that costs incurred in $C_2(T)$, and $C_3(T)$ follows the same bound as $R_2(T)$ and $R_3(T)$ respectively. Summing the three terms gives the required bound and choosing $K = \Theta(LdT_MS\sqrt{A})$. \section{Introduction} Reinforcement Learning is being increasingly applied to various interesting Markov Decision Processes (MDP) setups where the system model is not known apriori \cite{sutton2018reinforcement,recht2019tour}. Various algorithms have been developed to learn efficient policies using deep neural networks \cite{mnih2015human,schulman2017proximal,haarnoja2018soft}. Much work is also done to develop algorithms that are provably sample-efficient \cite{jaksch2010near,agrawal2017optimistic,jin2018provably}. However, in many applications, the learning agent (or algorithm) needs to satisfy certain constraints while maximizing an objective \cite{altman1991constrained}. For example, in robotics, a good policy for reaching a target pose should avoid hazardous poses which may damage the environment \cite{achiam2017constrained}. Also, consider the example of autonomous vehicles, the goal is not just to reach the destination as early as possible, but also to ensure the safety of the surroundings \cite{le2019batch,tessler2018reward}. Further, there are certain environments in which the agent is required to ensure the constraint violations are reduced while optimizing the objective as well \cite{leike2017ai,ray2019benchmarking}. Owing to the importance of RL with constraints, recently, there has been significant work in the area. For episodic setup, there is a significant line of work ranging from model based algorithms \cite{brantley2020constrained,yu2021morl} to primal-dual based model-free algorithms \cite{ding2021provably}. Much recently, \citet{wei2021provably} proposed TripleQ algorithm which achieves zero constraint violations\footnote{We note that even with zero constraint violations, an agent can violate constraints in the initial learning periods. Hence, zero constraints violations should be treated as $O(1/T)$, \textit{i.e.}, $O(1)$ violations in time $T$.} at the expense of an increased regret order of $O(T^{-1/5})$. However, for the episodic setup, the majority of the current work considers the weaker regret definition specified by \citet{efroni2020exploration}. Averaging over value function of multiple episodes allows for oscillations for constraints values around bounds, and does not imply that the policy (and the corresponding value function) necessarily converge to the optimal policy (and the corresponding value function) which satisfies the constraints. We note that the definition which considers the average over time makes sense when considering an infinite horizon setup as the long-term average is naturally defined \cite{puterman2014markov}. For a tabular infinite-horizon setup, \citet{singh2020learning} proposed an epoch-based algorithm which bounds the regret by $O(S\sqrt{A/T^{5}})$ with convergence in policy. We improve on this result by three folds, first by reducing the regret order from $O(T^{-1/4})$ to $O(T^{-1/2})$, second by considering convex function for objectives and constraints, and last by providing algorithm which can bound the constraint violations with $O(1/T)$. We compare the algorithms with different related works in Table \ref{tab:algo_comparisons}. In this work, we consider the problem of maximizing concave utility of the expected rewards while also ensuring that a set of convex constraints of the expected rewards are also satisfied. Moreover, we aim to develop algorithms that can also ensure that the constraints are not violated during the training phase as well. We work with tabular MDP with infinite horizon. For such setup, our algorithm updates policies as it learns the system model. Further, our approach also bound the accumulated observed constraint violations as compared to the expected constraint violations. \input{related_table} To achieve this result, we propose \textsc{UC-CURL}\ algorithm which proceeds in epochs $e$. At each epoch, we solve for a policy which considers constraints tighter by $\epsilon_e$ than the true bounds. Further, as the knowledge of the model improves with increased interactions with the environment, we reduce this tightness. This $\epsilon_e$-sequence is critical to our algorithm as, if the sequence decays too fast, the constraints violations cannot be bounded by zero. And, if this sequences decays too slow, the objective regret may not decay fast enough. Further, using the $\epsilon_e$-sequence, we do not require the knowledge of the total time $T$ for which the algorithm runs. We bound our regret by bounding the gap between the optimal policy in the feasible region and the optimal policy for the optimization problem with $\epsilon_e$ tight constraints. We bound this gap with a multiplicative factor of $O(1/\delta)$, where $\delta$ is Slater's parameter. Based on our analysis using the Slater's parameter $\delta$, we consider a case where a lower bound $T_l$ on the time horizon $T$ is known. This knowledge of $T_l$ allows us to relax our assumption on $\delta$. Further, the regret analysis of the proposed \textsc{UC-CURL}\ algorithm is also novel. We define and use Bellman error for infinite horizon setup to bound the difference between the performance of optimistic policy on the optimistic MDP and the true MDP. Compared to analysis of \cite{jaksch2010near}, this allows us to work with stochastic policies. Combining these two tricks, we bound our regret as $\Tilde{O}(\frac{1}{\delta}LdT_MS\sqrt{A/T})$ and constraint violations as $O(1/T)$, where $S$ and $A$ are the number of states and actions respectively, $L$ is the Lipschitz constant of the objective and constraint functions, $d$ is the number of costs the agent is trying to optimize, and $T_M$ is the mixing time of the MDP. We note that ours is the first result with a suitable regret definition, on non-linear objective and constraints, and the result achieves zero-constraint violations. \section{Proof of Lemma \ref{lem:optimality_gap_objective}} \label{app:proof_of_epsilon_gap_objective} \begin{proof} Note that $\rho^P_{\pi^*}$ denotes the stationary distribution of the optimal solution which satisfies \begin{align} g\left(\sum_{s,a}\rho^P_{\pi^*}(s,a)c_1(s,a), \cdots, \sum_{s,a}\rho^P_{\pi^*}(s,a)c_d(s,a)\right) \le C\label{eq:true_constraint_bound_lem_1} \end{align} Further, from Assumption \ref{slaters_conditon}, we have a feasible policy $\pi$ for which \begin{align} g\left(\sum_{s,a}\rho^P_{\pi}(s,a)r_1(s,a), \cdots, \sum_{s,a}\rho^P_{\pi}(s,a)r_K(s,a)\right) \le C - \delta\label{eq:tight_constraint_bound_lem_2} \end{align} We now construct a stationary distribution $\rho^P$ obtain the corresponding $\pi_e'$ as: \begin{align} \rho^P(s,a)= \left(1-\frac{\epsilon_e}{\delta}\right)\rho^P_{\pi^*}(s,a) + \frac{\epsilon_e}{\delta}\rho^P_{\pi}(s,a)\label{eq:avg_stationary_dist}\\ \pi_{e}' = \rho^P(s,a)/\left(\sum_{s,b}\rho^P(s,b)\right) \end{align} For this new policy, for the convex constraint $g$, we observe that, \begin{align} &g\left(\sum_{s,a}\rho^P_{\pi}(s,a)c_1(s,a), \cdots, \sum_{s,a}\rho^P_{\pi}(s,a)c_d(s,a)\right)\\ &= g\left(\sum_{s,a}\right(\left(1-\frac{\epsilon_e}{\delta}\right)\rho^P_{\pi^*} + \frac{\epsilon_e}{\delta}\rho^P_{\pi}\left)(s,a)r_1(s,a), \cdots, \sum_{s,a}\left(\left(1-\frac{\epsilon_e}{\delta}\right)\rho^P_{\pi^*} + \frac{\epsilon_e}{\delta}\rho^P_{\pi}\right)(s,a)r_K(s,a)\right)\\ &\le \left(1-\frac{\epsilon_e}{\delta}\right)g\left(\sum_{s,a}\rho^P_{\pi^*}(s,a)c_1(s,a), \cdots, \sum_{s,a}\rho^P_{\pi^*}(s,a)c_d(s,a)\right)\nonumber\\ &~~~+ \frac{\epsilon_e}{\delta}g\left(\sum_{s,a}\rho^P_{\pi}(s,a)c_1(s,a), \cdots, \sum_{s,a}\rho^P_{\pi}(s,a)c_d(s,a)\right)\label{eq:convex_constraint_lem_1}\\ &\le \left(1-\frac{\epsilon_e}{\delta}\right)C + \frac{\epsilon_e}{\delta}\left(C - \delta\right)\label{eq:constraint_bounds_lem_1}\\ &= C - \delta \le C - \epsilon_e \end{align} where Equation \eqref{eq:convex_constraint_lem_1} follows from the convexity of the constraints. Equation \eqref{eq:constraint_bounds_lem_1} follows from Equation \eqref{eq:true_constraint_bound_lem_1} and Equation \eqref{eq:tight_constraint_bound_lem_2}\\ Now, note that the policy $\pi_e'$ corresponding to stationary distribution constructed in Equation \eqref{eq:avg_stationary_dist} satisfies the $\epsilon_e$-tight constraints. Further, we find $\pi_e^*$ as the optimal solution for the $\epsilon_e$-tight optimization problem. Hence, we have \begin{align} f\left(\sum_{s,a}\rho^P_{\pi^*}(s,a)r(s,a)\right) - f\left( \sum_{s,a}\rho^P_{\pi_e^*}(s,a)r(s,a)\right)&\le f\left(\sum_{s,a}\rho^P_{\pi^*}(s,a)r(s,a)\right) - f\left( \sum_{s,a}\rho^P(s,a)r(s,a)\right)\\ &\le L\Big|\sum_{s,a}\left(\rho^P_{\pi^*}(s,a) - \rho^P(s,a)\right)r(s,a)\Big|\label{eq:Lipschitz_lem_1}\\ &\le L\Big|\sum_{s,a}\left(\rho^P_{\pi^*}(s,a) - \left(1-\frac{\epsilon_e}{\delta}\right)\rho^P_{\pi^*}(s,a) - \frac{\epsilon_e}{\delta}\rho^P_{\pi}(s,a)\right)r_d(s,a)\Big|\\ &\le L\frac{\epsilon_e}{\delta}\Big|\sum_{s,a}\left(\rho^P_{\pi^*}(s,a) - \rho^P_{\pi}(s,a)\right)r(s,a)\Big|\\ &\le L\frac{\epsilon_e}{\delta}\Big|\sum_{s,a}\rho^P_{\pi^*}r(s,a)\Big| + L\frac{\epsilon_e}{\delta}\Big|\sum_{s,a} \rho^P_{\pi}(s,a)r(s,a)\Big|\\ &\le 2L\frac{\epsilon_e}{\delta}\label{eq:r_bounded_by_1} \end{align} where, Equation \eqref{eq:Lipschitz_lem_1} follows from the Lipschitz assumption on the joint objective $f$. Equation \eqref{eq:r_bounded_by_1} follows from the fact that $r_k(s,a) \le 1$ for all $k\in[K]$ and for all $(s,a)\in\mathcal{S}\times\mathcal{A}$. \end{proof} \section{Regret Analysis} After describing \textsc{UC-CURL}\ algorithm, we now perform the regret and constraint violation analysis using Bellman error. We note that the standard analysis for infinite horizon tabular MDPs of UCRL2 \cite{jaksch2010near} cannot be directly applied as the policy $\pi_e$ is possibly stochastic for every epoch. Another peculiar aspect of the analysis of the UCRL2 algorithm is the regret grows linearly with the number of epochs. The analysis still bounds the regret by $\Tilde{O}(DS\sqrt{A/T})$ as the number of epochs are bounded by $O(SA\log T)$. However, the analysis is counter-intuitive as the agent is able to work with a better policy at every time-step not just for an epoch. We also note that the analysis of UCRL-CMDP \cite{singh2020learning} bounds the deviations with value function instead of bias resulting in regret scaling as $O(T^{-1/4})$. Compared to these works, our analysis works with stochastic policies, obtains regret independent to number of epochs, and scales as $\Tilde{O}(1/\sqrt{T})$. Hence, our analysis can be used as a tool to tightly analyze other learning algorithms for tabular infinite horizon MDPs. Before diving into the details, we first define few important variables which are key to our analysis. The first variable is the standard $Q$-value function. We define $Q_\gamma^{\pi, P}$ as the long term expected reward on taking action $a$ in state $s$ and then following policy $\pi$ for the MDP with transition $P$. Mathematically, we have \begin{align} Q_\gamma^{\pi, P}(s,a) = r(s,a) + \gamma\sum_{s'\in\mathcal{S}}P(s'|s,a)V_\gamma^{\pi,P}(s'). \end{align} We also define Bellman error $B^{\pi, \Tilde{P}}(s,a)$ for the infinite horizon MDPs as the difference between the cumulative expected rewards obtained for deviating from the system model with transition $\Tilde{P}$ for one step by taking action $a$ in state $s$ and then following policy $\pi$. We have: \begin{align} B^{\pi, \Tilde{P}}(s,a)&= \lim_{\gamma\to 1}\Big(Q_\gamma^{\pi, \Tilde{P}}(s,a) - r(s,a)- \gamma\sum\nolimits_{s'\in\mathcal{S}}P(s'|s,a)V_\gamma^{\pi, \Tilde{P}}(s,a)\Big) \label{eq:Bellman_error_definition} \end{align} After defining the key variables, we can now jump into bounding the objective regret $R(T)$. Intuitively, the algorithm incurs regret on three accounts. First source is following the conservative policy which we require to limit the constraint violations. Second source of regret is solving for the policy which is optimal for the optimistic MDP. Third source of regret is the stochastic behavior of the system. We also note that the constraints are violated because of the imperfect MDP knowledge and the stochastic behavior. However, the conservative behavior actually allows us to violate the constraints within some limits which we will discuss in the later part of this section. We start by stating our first lemma which relates the regret because we solve for a conservative policy. We define $\epsilon_e$-tight optimization problem as optimization problem for the true MDP with transitions $P$ with $\epsilon=\epsilon_e$. We bound the gap between the value of function $f$ at the long-term expected reward of the policy for $\epsilon_e$-tight optimization problem and the true optimization problem (Equation \eqref{eq:optimization_equation}-\eqref{eq:cmdp_constraints}) in the following lemma. \begin{lemma}\label{lem:optimality_gap_objective} Let $\lambda_{\pi^*}^P$ be the long-term average reward following the optimal feasible policy $\pi^*$ for the true MDP $\mathcal{M}$ and let $\lambda_{\pi_e}^P$ be the long-term average rewards following the optimal policy $\pi_e$ for the $\epsilon_e$ tight optimization problem for the true MDP $\mathcal{M}$, then for $\epsilon_e \le \delta$, we have, \begin{align} &f\left(\lambda_{\pi^*}^P\right) -f\left(\lambda_{\pi_e}^P\right) \le \frac{2L\epsilon_e}{\delta} \end{align} \end{lemma} \begin{proof}[Proof Sketch] We construct a policy for which the steady state distribution is the weighted average of two steady state distributions. First distribution is for the optimal policy for the true optimization problem. Second distribution is for the policy which satisfies Assumption \ref{slaters_conditon}. Now, we show that this constructed policy satisfies the $\epsilon_e$-tight constraints. Now, using Lipschitz continuity, we convert the difference between function value into the difference between the long-term average reward to obtain the required result. The detailed proof is provided in Appendix \ref{app:proof_of_epsilon_gap_objective}. \end{proof} Lemma \ref{lem:optimality_gap_objective} and our construction of $\epsilon_e$ sequence allows us to limit the growth of regret because of conservative policy by $\Tilde{O}(LdT_MS\sqrt{A/T})$. To bound the regret from the second source, we propose a novel Bellman error based analysis. In our next lemma, we show that the difference between the performance of a policy on two different MDPs is bounded by long-term averaged Bellman error. Formally, we have: \begin{lemma}\label{lem:bound_average_by_bellman_main} The difference of long-term average rewards for running the optimistic policy $\pi_e$ on the optimistic MDP, $\lambda_{\pi_e}^{\Tilde{P}_e}$, and the average long-term average rewards for running the optimistic policy $\pi_e$ on the true MDP, $\lambda_{\pi_e}^P$, is the long-term average Bellman error as \begin{align} \lambda_{\pi_e}^{\Tilde{P}_e} - \lambda_{\pi_e}^P = \sum_{s,a}\rho_{\pi_e}^P B^{\pi_e, \Tilde{P}_e}(s,a) \end{align} \end{lemma} \begin{proof}[Proof Sketch] We start by writing $Q_\gamma^{\pi_e, \Tilde{P}_e}$ in terms of the Bellman error. Now, subtracting $V_\gamma^{\pi_e, P}$ from $V_\gamma^{\pi_e, \Tilde{P}_e}$ and using the fact that $\lambda_{\pi_e}^P = \lim_{\gamma\to1}V_\gamma^{\pi,P}$ and $\lambda_{\pi_e}^{\Tilde{P}_e} = \lim_{\gamma\to1}V_\gamma^{\pi,{\Tilde{P}_e}}$ we obtain the required result. A complete proof is provided in Appendix \ref{app:bounding_imperferct_model_regret}. \end{proof} After relating the gap between the long-term average rewards of policy $\pi_e$ on the two MDPs, we now want to bound the sum of Bellman error over an epoch. For this, we first bound the Bellman error for a particular state action pair $s,a$ in the form of following lemma. We have, \begin{lemma}\label{lem:bound_bellman_s_a_main} With probability at least $1- 1/t_e^6$, the Bellman error $B^{\pi_e, \Tilde{P}_e}(s,a)$ for state-action pair $s,a$ in epoch $e$ is upper bounded as \begin{align} B^{\pi_e, \Tilde{P}_e}(s,a) \le \sqrt{\frac{14S\log(2AT)}{1\vee N_e(s,a)}}\Tilde{h}(\cdot) \end{align} \end{lemma} \begin{proof}[Proof Sketch] We start by noting that the Bellman error essentially bounds the impact of the difference in value obtained because of the difference in transition probability to the immediate next state. We bound the difference in transition probability between the optimistic MDP and the true MDP using the result from \cite{weissman2003inequalities}. This approach gives the required result. A complete proof is provided in Appendix \ref{app:bounding_imperferct_model_regret}. \end{proof} To bound the regret because of the imperfect knowledge of the system model, we can now use Lemma \ref{lem:bound_average_by_bellman_main} and Lemma \ref{lem:bound_bellman_s_a_main}. We now bound the expected Bellman error in epoch $e$ starting from state $s_{t_e}$ and action $a_{t_e}$ by constructing a Martingale sequence with filtration $\mathcal{F}_t = \{s_1, a_1, \cdots, s_{t-1}, a_{t-1}\}$ and using Azuma's inequality \cite{bercu2015concentration}. Using the Azuma's inequality, we can also bound the deviations because of the stochasticity of the Markov Decision Process. The result is stated in the following lemma. \begin{lemma} With probability at least $1-T^{-5/4}$, the regret incurred from imperfect model knowledge and process stochastics is bounded by \begin{align} O\left(T_MS\sqrt{A(\log AT)/T} + \frac{CT_MS\log T}{1-\rho}\right) \end{align} \end{lemma} \input{figure_file} The regret analysis framework also prepares us to bound the constraint violations as well. We again start by quantifying the reasons for constraint violations. The major reason the agent violates the constraint is because it is playing with the imperfect knowledge of the MDP and the stochasticity of the MDP which results in the deviation from the average costs. We note that the conservative policy $\pi_e$ for every epoch does not violate the constraints, but instead allows the agent to manage the constraint violations because of the imperfect model knowledge and the system dynamics. We note that the Lipschitz continuity of the constraint function $g$ allows us to convert the function of $d$ averaged costs to the sum of $d$ averaged costs. Further, we note that we can treat the cost similar to rewards \cite{brantley2020constrained}. This property allows us to bound the cost incurred incurred in a way similar to how we bound the gap from the optimal reward by $LdT_MS\sqrt{A(\log AT)/T} + (CT_MS\log T)/(1-\rho)$. We now want that the slackness provided by the conservative policy should allow $LdT_MS\sqrt{A(\log AT)/T} + (CT_MS\log T)/(1-\rho)$ constraint violations\footnote{We thank the authors of \cite{chen2022learning} for pointing out a mistake in the previous version where we erroneously bounded the regret using the diameter of the MDP instead of the mixing time of the MDP. We have fixed that in our updated analysis using Lemma \ref{lem:bounded_bias_span} which bounds the span by following the reward optimal policy for the optimistic MDP in the true MDP till it reaches a target state.}. This is ensured by our chosen $\epsilon_e$ sequence. We formally state that result in the following lemma proven in parts in Appendix \ref{app:regret_bounds} and Appendix \ref{app:constraint_violation_bounds}. \begin{lemma} The cumulative sum of the $\epsilon_e$ sequence is upper and lower bounded as, \begin{align} \sum\nolimits_{e=1}^E(t_{e+1}-t_e)\epsilon_e = \Theta \left(LdT_MS\sqrt{AT\log T}\right) \end{align} \end{lemma} After giving the details on bounds on the possible sources of regret and constraint violations, we can formally state the result in the form of following theorem. \begin{theorem}For all $T$ and $K = \Theta(LdT_MS\sqrt{A})$, the regret $R(T)$ of \textsc{UC-CURL}\ algorithm is bounded by \begin{align} R(T) = O\left(\frac{1}{\delta}LdT_MS\sqrt{A\frac{\log AT}{T}} + \frac{C\log T}{1-\rho}\right) \end{align} and the constraints are bounded as $C(T) = O(1/T)$, with probability at least $1-\frac{1}{T^{5/4}}$. \end{theorem} Our Bellman error based analysis allows us remove the dependency on bounding the number of epochs for infinite-horizon MDPs algorithms. We believe this is an important step to possibly close the gap between the finite-horizon MDP algorithms infinite-horizon MDP algorithms. Further, our decaying conservative parameter $\epsilon_e$ also clears way to reduce dependency on parameter knowledge of $T$ for practical algorithms. The agent solves for the $\epsilon_e$-tight optimization problem for the optimistic MDP at every epoch which may be a computationally inefficient step. Thus, an can still prefer to choose a lesser number of epochs to reduce this computational cost. Thus, an agent can choose a tradeoff between sample efficiency by updating policy frequently and computational efficiency of the logarithmic number of epochs. \section{Objective Regret Bound}\label{app:regret_bounds} To bound the regret $R(T)$, we first consider two cases. First case is where the confidence intervals in Equation \eqref{eq:opt_transition_probability}. For the second case now holds with probability at-least $1-\frac{1}{T^{5/4}}$, we break the regret into multiple components. We can then bound these components individually. \subsection{Regret breakdown} We first break down our regret into multiple parts which will help us bound the regret. \begin{align} R(T) &= f(\lambda_*^{P}) - f\left(\frac{1}{T}\sum_{t=1}^Tr_t(s_t, a_t)\right)\\ &= f(\lambda_*^{P}) - \frac{1}{T}\sum_{e=1}^E T_e f(\lambda_{\pi_e^*}^P) + \frac{1}{T}\sum_{e=1}^E T_e f(\lambda_{\pi_e^*}^P) - f\left(\frac{1}{T}\sum_{t=1}^Tr_t(s_t, a_t)\right)\\ &= \frac{1}{T}\sum_{e=1}^E T_e \left(f(\lambda_*^{P}) - f(\lambda_{\pi_e^*}^P)\right) + \frac{1}{T}\sum_{e=1}^E T_e f(\lambda_{\pi_e^*}^P) - f\left(\frac{1}{T}\sum_{t=1}^Tr_t(s_t, a_t)\right)\\ &\le \frac{1}{T}\sum_{e=1}^E T_e \left(f(\lambda_*^{P}) - f(\lambda_{\pi_e^*}^P)\right) + \frac{1}{T}\sum_{e=1}^E T_e f(\lambda_{\pi_e}^{\Tilde{P}_e}) - f\left(\frac{1}{T}\sum_{t=1}^Tr_t(s_t, a_t)\right)\label{eq:regret_use_optimism}\\ &\le \frac{1}{T}\sum_{e=1}^E T_e \left(f(\lambda_*^{P}) - f(\lambda_{\pi_e^*}^P)\right) + f\left(\frac{1}{T}\sum_{e=1}^E T_e\lambda_{\pi_e}^{\Tilde{P}_e}\right) - f\left(\frac{1}{T}\sum_{t=1}^Tr_t(s_t, a_t)\right)\label{eq:regret_use_concavity}\\ &\le \frac{1}{T}\sum_{e=1}^E T_e \left(f(\lambda_*^{P}) - f(\lambda_{\pi_e^*}^P)\right) + L\Big|\frac{1}{T}\sum_{e=1}^E T_e\lambda_{\pi_e}^{\Tilde{P}_e} - \frac{1}{T}\sum_{t=1}^Tr_t(s_t, a_t)\Big|\label{eq:regret_use_lipschitz}\\ &= \frac{1}{T}\sum_{e=1}^E T_e \left(f(\lambda_*^{P}) - f(\lambda_{\pi_e^*}^P)\right) + L\Big|\frac{1}{T}\sum_{e=1}^E \sum_{t = t_e}^{t_{e+1}-1} \left(\lambda_{\pi_e}^{\Tilde{P}_e} - \lambda_{\pi_e}^{P}+ \lambda_{\pi_e}^{P} - r_t(s_t, a_t)\right)\Big|\\ &\le \frac{1}{T}\sum_{e=1}^E T_e \left(f(\lambda_*^{P}) - f(\lambda_{\pi_e^*}^P)\right) + L\Big|\frac{1}{T}\sum_{e=1}^E \sum_{t = t_e}^{t_{e+1}-1} \left(\lambda_{\pi_e}^{\Tilde{P}_e} - \lambda_{\pi_e}^{P}\right)\Big| + L\Big|\frac{1}{T}\sum_{e=1}^E \sum_{t = t_e}^{t_{e+1}-1} \left(\lambda_{\pi_e}^{P} - r_t(s_t, a_t)\right)\Big|\\ &= R_1(T) + R_2(T) + R_3(T) \label{eq:define_broken_regret} \end{align} where Equation \eqref{eq:regret_use_optimism} comes from the fact that the policy $\pi_e$ is for the optimistic CMDP and provides a higher value of the function $f$. Equation \ref{eq:regret_use_concavity} comes from the concavity of the function $f$, and Equation \ref{eq:regret_use_lipschitz} comes from the Lipschitz continuity of the function $f$. The three terms in Equation \eqref{eq:define_broken_regret} are now defined as: \begin{align} R_1(T) &= \frac{L}{T}\sum_{e=1}^E T_e \left(f(\lambda_*^{P}) - f(\lambda_{\pi_e^*}^P)\right) \end{align} $R_1(T)$ denotes the regret incurred from not playing the optimal policy $\pi^*$ for the true optimization problem in Equation \eqref{eq:optimization_equation} but the optimal policy $\pi_e^*$ for the $\epsilon_e$-tight optimization problem in epoch $e$. \begin{align} R_2(T) &= \frac{L}{T}\Big|\sum_{e=1}^E \sum_{t = t_e}^{t_{e+1}-1} \left(\lambda_{\pi_e}^{\Tilde{P}_e} - \lambda_{\pi_e}^{P}\right)\Big| \end{align} $R_2(T)$ denotes the gap between expected rewards from playing the optimal policy $\pi_e$ for $\epsilon_e$-tight optimization problem on the optimistic MDP instead of the true MDP. We further upper bound the $R_2(T)$ term by choosing an MDP in the confidence interval which maximizes the rewards for $\pi_e$. To reduce notational clutter, we relabel this MDP as $\Tilde{P}_e$ or $$\Tilde{P}_e = \max_{P_e} \lambda_{\pi_e}^{P_e},$$ where $P_e$ are the transition probabilities in the confidence intervals at epoch $e$. Hence, we get, \begin{align} R_2(T) &\le \frac{L}{T}\Big|\sum_{e=1}^E \sum_{t = t_e}^{t_{e+1}-1} \left(\lambda_{\pi_e}^{\Tilde{P}_e} - \lambda_{\pi_e}^{P}\right)\Big| \end{align} \begin{align} R_3(T) &= \frac{L}{T}\Big|\sum_{e=1}^E \sum_{t = t_e}^{t_{e+1}-1} \left(\lambda_{\pi_e}^{P} - r_t(s_t, a_t)\right)\Big| \end{align} $R_3(T)$ denotes the gap between obtained rewards from playing the optimal policy $\pi_e$ for $\epsilon_e$-tight optimization problem the true MDP and the expected per-step reward of playing the optimal policy $\pi_e$ for $\epsilon_e$-tight optimization problem the true MDP. \newpage \subsection{Bounding $R_1(T)$} Bounding $R_1(T)$ requires using Lemma \ref{lem:optimality_gap_objective}. We have the following set of equations: \begin{align} R_1(T) &= \frac{1}{T}\sum_{e=1}^E\sum_{t = t_e}^{t_{e+1}-1}\left(f(\lambda_*^{P}) - f(\lambda_{\pi_e^*}^P)\right)\\ &\le \frac{1}{T}\sum_{e=1}^E \sum_{t = t_e}^{t_{e+1}-1}\frac{2L\epsilon_e}{\delta} \label{eq:using_slater_lemma}\\ &= \frac{2L}{T\delta}\sum_{e=1}^E \sum_{t = t_e}^{t_{e+1}-1}\sqrt{\frac{\log t}{t}}\\ &\le \frac{2L}{T\delta}\sum_{e=1}^E \sum_{s,a}\nu_e(s,a) \sqrt{\frac{\log T}{N_e(s,a)}}\label{eq:bound_log_by_sqrt}\\ &\le \frac{2L\sqrt{\log T}}{T\delta} \sum_{s,a}\sum_{e=1}^E\frac{\nu_e(s,a)}{\sqrt{N_e(s,a)}}\\ &\le (\sqrt{2}+1)\frac{2L\sqrt{\log T}}{T\delta} \sum_{s,a}\sqrt{N(s,a)}\label{eq:use_Jaksch_sum_lemma}\\ &\le (\sqrt{2}+1)\frac{2L\sqrt{\log T}}{T\delta} \sqrt{(\sum_{s,a}1)\sum_{s,a}N(s,a)}\label{eq:use_Cauchy_Schwarz_1}\\ &\le (\sqrt{2}+1)\frac{2L\sqrt{\log T}}{T\delta} \sqrt{SAT} \end{align} where Equation \eqref{eq:bound_log_by_sqrt} follows from the fact that $\log t \le \log T$ for all $t \le T$ and $N_e(s,a) \le t_e \le t$ for all $t$. The bound on summation over $e$ in Equation \eqref{eq:use_Jaksch_sum_lemma} follows from \citep[{Lemma 19}]{jaksch2010near}. Finally, equation \eqref{eq:use_Cauchy_Schwarz_1} follows from the Cauchy-Schwarz inequality. \newpage \subsection{Bounding $R_2(T)$} \label{app:bounding_imperferct_model_regret} We relate the difference between long-term average rewards for running the optimistic policy $\pi_e$ on the optimistic MDP $\lambda_{\pi_e}^{\Tilde{P}_e}$ and the long-term average rewards for running the optimistic policy $\pi_e$ on the true MDP ($\lambda_{\pi_e}^P$) with the Bellman error. Formally, we have the following lemma: \begin{lemma}\label{lem:bound_average_by_bellman} The difference of long-term average rewards for running the optimistic policy $\pi_e$ on the optimistic MDP, $\lambda_{\pi_e}^{\Tilde{P}_e}$, and the average long-term average rewards for running the optimistic policy $\pi_e$ on the true MDP, $\lambda_{\pi_e}^P$, is the long-term average Bellman error as \begin{align} \lambda_{\pi_e}^{\Tilde{P}_e} - \lambda_{\pi_e}^P = \sum_{s,a}\rho_{\pi_e}^P B^{\pi_e, \Tilde{P}_e}(s,a)\label{eq:long_term_average_on_starting_distribution} \end{align} \end{lemma} \begin{proof} Note that for all $s\in\mathcal{S}$, we have: \begin{align} V_\gamma^{\pi_e, \Tilde{P}_e}(s) &= \mathbb{E}_{a\sim\pi_e}\left[Q_\gamma^{\pi_e, \Tilde{P}_e}(s,a)\right]\\ &= \mathbb{E}_{a\sim\pi_e}\left[B^{\pi_e, \Tilde{P}_e}(s,a) + r(s,a) + \gamma\sum_{s'\in\mathcal{S}}P(s'|s,a)V_\gamma^{\pi_e, \Tilde{P}_e}(s')\right]\label{eq:optimistic_MDP_lambda} \end{align} where Equation \eqref{eq:optimistic_MDP_lambda} follows from the definition of the Bellman error for state action pair $s,a$. Similarly, for the true MDP, we have, \begin{align} V_\gamma^{\pi_e, P}(s) &= \mathbb{E}_{a\sim\pi_e}\left[Q_\gamma^{\pi_e, }(s,a)\right]\\ &= \mathbb{E}_{a\sim\pi_e}\left[r(s,a)+ \gamma\sum_{s'\in\mathcal{S}}P(s'|s,a)V_\gamma^{\pi_e, P}(s')\right] \label{eq:true_MDP_lambda} \end{align} Subtracting Equation \eqref{eq:true_MDP_lambda} from Equation \eqref{eq:optimistic_MDP_lambda}, we get: \begin{align} V_\gamma^{\pi_e,\Tilde{P}_e}(s) - V_\gamma^{\pi_e,P}(s) &= \mathbb{E}_{a\sim\pi_e}\left[B^{\pi_e, \Tilde{P}_e}(s,a) + \gamma\sum_{s'\in\mathcal{S}}P(s'|s,a)\left(V_\gamma^{\pi_e, \Tilde{P}_e} - V_\gamma^{\pi_e, \Tilde{P}_e}\right)(s')\right]\\ &= \mathbb{E}_{a\sim\pi_e}\left[B^{\pi_e, \Tilde{P}_e}(s,a)\right] + \gamma\sum_{s'\in\mathcal{S}}P_{\pi_e}\left(V_\gamma^{\pi_e, \Tilde{P}_e} - V_\gamma^{\pi_e, \Tilde{P}_e}\right)(s') \end{align} Using the vector format for the value functions, we have, \begin{align} \Bar{V}_\gamma^{\pi_e,\Tilde{P}_e} - \Bar{V}_\gamma^{\pi_e,P} &= \left(I-\gamma P_{\pi_e}\right)^{-1}\overline{B}_{\pi_e}^{\pi_e, \Tilde{P}_e \end{align} Now, converting the value function to average per-step reward we have, \begin{align} \lambda_{\pi_e}^{\Tilde{P}_e}\bm{1}_S - \lambda_{\pi_e}^P\bm{1}_S &= \lim_{\gamma\to1}(1-\gamma)\left(\Bar{V}_\gamma^{\pi_e,\Tilde{P}_e} - \Bar{V}_\gamma^{\pi_e,P}\right)\\ &= \lim_{\gamma\to1}(1-\gamma)\left(I-\gamma P_{\pi_e}\right)^{-1}\overline{B}_{\pi_e}^{\pi_e, \Tilde{P}_e}\\ &= \left(\sum_{s,a}\rho_{\pi_e}^P B^{\pi_e, \Tilde{P}_e}(s,a)\right)\bm{1}_S \end{align} where the last equation follows from the definition of occupancy measures by \cite{puterman2014markov}. \end{proof} \begin{remark} Note that the Bellman error is not to be confused by Advantage function and policy improvement lemma \cite{langford2002approximately}. The policy improvement lemma relates the performance of two policies on same MDP whereas we bounded the performance of one policy on two different MDPs in Lemma \ref{lem:bound_average_by_bellman} \end{remark} \newpage We now want to bound the Bellman errors to bound the gap between the average per-step reward $\lambda_{\pi_e}^{\Tilde{P}_e}$, and $\lambda_{\pi_e}^{P}$. From the definition of Bellman error and the confidence intervals on the estimated transition probabilities, we obtain the following lemma: \begin{lemma}\label{lem:bound_bellman_s_a} With probability at least $1- 1/t_e^6$, the Bellman error $B^{\pi_e, \Tilde{P}_e}(s,a)$ for state-action pair $s,a$ in epoch $e$ is upper bounded as \begin{align} B^{\pi_e, \Tilde{P}_e}(s,a) \le \sqrt{\frac{14S\log(2AT)}{1\vee N_e(s,a)}}\|\Tilde{h}\|_\infty \end{align} \end{lemma} \begin{proof} Starting with the definition of Bellman error in Equation \eqref{eq:Bellman_error_definition}, we get \begin{align} B^{\pi_e, \Tilde{P}_e}(s,a) &= \lim_{\gamma\to1}\left(Q_\gamma^{\pi_e, \mathcal{P}}(s,a) - \left(r(s,a) +\gamma \sum_{s'\in\mathcal{S}}P(s'|s,a)V_\gamma^{\pi_e, \Tilde{P}_e} \right)\right)\\ &=\lim_{\gamma\to1}\left(\left(r(s,a) + \gamma\sum_{s'\in\mathcal{S}}\Tilde{P}_e(s'|s,a)V_\gamma^{\pi_e,\Tilde{P}_e}(s')\right) - \left(r(s,a) +\gamma \sum_{s'\in\mathcal{S}}P(s'|s,a)V_\gamma^{\pi_e, \Tilde{P}_e}(s') \right)\right)\\ &= \lim_{\gamma\to1}\gamma\sum_{s'\in\mathcal{S}}\left(\Tilde{P}_e(s'|s,a) - P(s'|s,a)\right)V_\gamma^{\pi_e,\Tilde{P}_e}(s')\label{eq:rewards_known}\\ &= \lim_{\gamma\to1}\gamma\left(\sum_{s'\in\mathcal{S}}\left(\Tilde{P}_e(s'|s,a) - P(s'|s,a)\right)V_\gamma^{\pi_e,\Tilde{P}_e}(s') + V_\gamma^{\pi_e,\Tilde{P}_e}(s) - V_\gamma^{\pi_e,\Tilde{P}_e}(s)\right)\\ &= \lim_{\gamma\to1}\gamma\left(\sum_{s'\in\mathcal{S}}\left(\Tilde{P}_e(s'|s,a) - P(s'|s,a)\right)V_\gamma^{\pi_e,\Tilde{P}_e}(s') - \sum_{s'\in\mathcal{S}}\Tilde{P}_e(s'|s,a)V_\gamma^{\pi_e,\Tilde{P}_e}(s) + \sum_{s'\in\mathcal{S}} P(s'|s,a)V_\gamma^{\pi_e,\Tilde{P}_e}(s)\right)\\ &= \lim_{\gamma\to1}\gamma\left(\sum_{s'\in\mathcal{S}}\left(\Tilde{P}_e(s'|s,a) - P(s'|s,a)\right)\left(V_\gamma^{\pi_e,\Tilde{P}_e}(s') - V_\gamma^{\pi_e,\Tilde{P}_e}(s)\right)\right)\\ &= \left(\sum_{s'\in\mathcal{S}}\left(\Tilde{P}_e(s'|s,a) - P(s'|s,a)\right)\lim_{\gamma\to1}\gamma\left(V_\gamma^{\pi_e,\Tilde{P}_e}(s') - V_\gamma^{\pi_e,\Tilde{P}_e}(s)\right)\right)\label{eq:interchange_limit_and_expectation}\\ &= \left(\sum_{s'\in\mathcal{S}}\left(\Tilde{P}_e(s'|s,a) - P(s'|s,a)\right)h(s')\right)\label{eq:value_to_bias}\\ &\le \Big\|\left(\Tilde{P}_e(\cdot|s,a) - P(\cdot|s,a)\right)\Big\|_1\label{eq:reward_holders}\\ &\le 2\sqrt{\frac{14S\log(2At)}{1\vee N_e(s,a)}}\|\Tilde{h}(\cdot)\|_\infty \label{eq:bound_bias_and_l1_prob}\\ &\le 2\sqrt{\frac{14S\log(2AT)}{1\vee N_e(s,a)}}\|\Tilde{h}(\cdot)\|_\infty \end{align} where Equation \eqref{eq:rewards_known} comes from the assumption that the rewards are known to the agent. Equation \eqref{eq:interchange_limit_and_expectation} follows from the fact that the difference between value function at two states is bounded. Equation \eqref{eq:value_to_bias} comes from the definition of bias term \cite{puterman2014markov}. Equation \eqref{eq:reward_holders} follows from H\"{o}lder's inequality. In Equation \eqref{eq:bound_bias_and_l1_prob}. Also, the $\ell_1$ norm of probability vector is bounded using Lemma \ref{lem:deviation_of_probability_estimates} for start time $t_e$ of epoch $e$. \end{proof} Additionally, note that the $\ell_1$ norm in Equation \eqref{eq:reward_holders} is bounded by $2$. Thus the Bellman error is loose upper bounded by $2\|\Tilde{h}(\cdot)\|_\infty$ for all state-action pairs. \newpage We still now need to bound the bias of the optimistic MDP $\|\Tilde{h}(\cdot)\|_\infty$ to problem specific variables to obtain a meaningful bound. For this, note that we $\Tilde{h}(\cdot)$ is the bias of the MDP for which policy $\pi_e$ obtains the maximum average reward in the confidence interval. Based on this observation, we obtain the following lemma: \begin{lemma}\label{lem:bounded_bias_span} For a MDP with rewards $r(s,a)$ and transition probabilities $\Tilde{P}_e$, using policy $\pi_e$, the difference of bias of any two states $s$, and $s'$ is bounded as $\Tilde{h}(s) - \Tilde{h}(s') \leq T_M~ \forall~s,s'\in \mathcal{S}$. \end{lemma} \begin{proof} Note that $\lambda_{\pi_e}^{\Tilde{P}_e} \ge \lambda_{\pi_e}^{P_e}$ for all $P_e$ in the confidence set. Now, consider the following Bellman equation \begin{align*} \Tilde{h}(s) &= r_{\pi_e}(s,a) - \lambda_{\pi_e}^{P_e} + (\Tilde{P}_{\pi_e,e}(\cdot|s))^T \Tilde{h}\\ &:= T\Tilde{h}(s) \end{align*} where $r_{\pi_e}(s) = \sum_{a}\pi_e(a|s)r(s,a)$ and $\Tilde{P}_{\pi_e,e}(s'|s) = \sum_{a}\pi(a|s)\Tilde{P}_e(s'|s,a)$. Consider two states $s, s'\in \mathcal{S}$. Also, let $\tau = \min\{t\geq 1: s_t = s', s_1 = s\}$ be a random variable. With $P_{\pi_e}(\cdot|s)$ $= \sum_{a}\pi_e(a|s)P(s'|s,a)$, we also define another operator, \begin{align*} \bar{T}h(s)&=(\min_{s,a}r(s,a) - \lambda_{\pi_e}^{P_e} + (P_{\pi_e}(\cdot|s))^T h)\mathbf{1}(s\neq s')+ h_{\pi_e}^{P_e}(s')\mathbf{1}(s=s'). \end{align*} Note that $\bar{T}\Tilde{h}(s) \le T\Tilde{h}(s) = \Tilde{h}(s)$ for all $s$ since $P_e$ maximizes the reward $r$ over all the transition probabilities in the confidence set of Equation \eqref{eq:opt_transition_probability} including the true transition probability $P$. Further, for any two vectors $u, v\in\mathbb{R}^S$ with $u(s) \ge v(s)\forall s$, we have $\bar{T}u \ge \bar{T}v$. Hence, we have $\bar{T}^n\Tilde{h}(s) \le \Tilde{h}(s)$ for all $s$. Hence, we have \begin{align*} \Tilde{h}(s) &\ge \bar{T}^n(s) \\ &= \mathbb{E}\big[-(\lambda_{\pi_e}^{P_e} - \min_{s,a}r(s,a))(n\wedge\tau) + \Tilde{h}(s_{n\wedge\tau})\big] \end{align*} Taking $\lim n\to \infty$, we have $\Tilde{h}(s) \ge \Tilde{h}(s') - T_M$, thus completing the proof. \end{proof} Combining Lemma \ref{lem:bounded_bias_span} with Lemma \ref{lem:bound_bellman_s_a}, we get the following result \begin{align} B^{\pi_e, \Tilde{P}_e}(s,a) \le \sqrt{\frac{14S\log(2AT)}{1\vee N_e(s,a)}}\|\Tilde{h}\|_\infty \le \sqrt{\frac{14S\log(2AT)}{1\vee N_e(s,a)}}T_M \end{align} \newpage Note that we have converted the difference of average rewards into the average Bellman error. Also, we have bounded the Bellman error of a state-action pair. We now need to bound the expected value in Equation \eqref{eq:long_term_average_on_starting_distribution}. We bound the average Bellman error of an epoch using the realizations of Bellman error at state-action pairs visited in an epoch. For this, we present the following lemma. \begin{lemma}\label{lem:bound_expected_bellman} With probability at least $1-1/T^6$, the cumulative expected bellman error is bounded as: \begin{align} \sum_{e=1}^E(t_{e+1}-t_e)\mathbb{E}_{\pi_e,P}\left[B^{\pi_e, \Tilde{P}_e}(s,a)\right] \le \sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}B^{\pi_e, \Tilde{P}_e}(s_t,a_t) + 4D\sqrt{6T\log(T)} + \frac{2CT_MES}{1-\rho} \end{align} \end{lemma} \begin{proof} Note that conditioned on filtration $H_{t_e}= \{s_1, a_1, \cdots, s_{t_e}, a_{t_e}\}$ the two expectations $\mathbb{E}_{s,a\sim\pi_e,P}[\cdot]$ and $\mathbb{E}_{s,a\sim\pi_e,P}[\cdot|H_{t_e-1}]$ are not equal as the former is the expected value of the long-term state distribution and the later is the long-term state distribution condition on initial state $s_{t_e-1}$. We now use Assumption 1 to obtain the following set of inequalities. \begin{align} \mathbb{E}_{(s,a)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s,a)] &= \mathbb{E}_{(s,a)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s,a)] \pm \mathbb{E}_{(s_t,a_t)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s_t,a_t)|H_{t_e-1}]\\ &=\mathbb{E}_{(s_t,a_t)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s_t,a_t)|H_{t_e-1}] \nonumber\\ &~~+ \left(\mathbb{E}_{(s,a)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s,a)]- \mathbb{E}_{(s_t,a_t)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s_t,a_t)|H_{t_e-1}]\right)\\ &=\mathbb{E}_{(s_t,a_t)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s_t,a_t)|H_{t_e-1}] \nonumber\\ &~~+ 2T_M\left(\|\pi_e(a|s)d_{\pi_e}(s) - \pi_e(a|s)P_{\pi,s_{t_e-1}}^{t-t_e+1}(s)\|_{TV}\right)\label{eq:change_expectation_to_diff_prob}\\ &=\mathbb{E}_{(s_t,a_t)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s_t,a_t)|H_{t_e-1}] + 2CT_MS\rho^{t-t_e}\label{eq:TV_bounded_by_l1} \end{align} where Equation \ref{eq:change_expectation_to_diff_prob} comes from Assumption 1 for running policy $\pi_e$ starting from state $s_{t_e-1}$ for $t-t_e+1$ steps and from Lemma \ref{lem:bound_bellman_s_a_main}. Equation \eqref{eq:TV_bounded_by_l1} follows from bounding the total-variation distance for all states and from the fact that $\sum_a\pi(a|s) = 1$. Using Equation \eqref{eq:TV_bounded_by_l1} we get, \begin{align} &\sum_{e=1}^E(t_{e+1}-t_e)\mathbb{E}_{\pi_e,P}\left[B^{\pi_e, \Tilde{P}_e}(s,a)\right] \nonumber\\ &= \sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1} \mathbb{E}_{(s_t,a_t)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s_t,a_t)|H_{t_e-1}] + \sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}2CT_MS\rho^{t-t_e}\\ &= \sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1} \mathbb{E}_{(s_t,a_t)\sim\pi_e, P}[B^{\pi_e, \Tilde{P}_e}(s_t,a_t)|H_{t_e-1}] + \frac{2ECT_MS}{1-\rho}\label{eq:bound_gm_sum} \end{align} where Equation \eqref{eq:bound_gm_sum} follows from summation of series $\rho^{t-t_e}$ for $t\to\infty$. We can now construct a Martingale sequence to bound the summation in Equation \eqref{eq:bound_on_restart_deviations}. We construct a Martingale sequence as \begin{align} X_t^e = \mathbb{E}_{(s_t,a_t)\sim\pi_e,P}[\sum_{t=t_e}^{t_{e+1}-1}B_{\pi_e}^{P_e^k,k}(s_t,a_t)|H_{t-1}]; t_e\le t<t_{e+1} \end{align} such that $|X_t^e-X_{t-1}^e| \le 4D$ for all $t,e$. We can now use Azuma-Hoeffding's inequality to bound $\sum_{e=1}^EX_{t_e}^e$ as: \begin{align} \Bigg|\sum_{e=1}^E\left(X_t^e-\sum_{t=t_e}^{t_{e+1}-1}B_{\pi_e}^{P_e^k,k}(s_t,a_t)\right)\Bigg|\le 4T_M\sqrt{6T\log(2T)} \end{align} with probability at least $1-1/T^6$. \end{proof} \newpage We are now ready to bound $R_2(T)$ using Lemma \ref{lem:bound_average_by_bellman}, Lemma \ref{lem:bound_bellman_s_a}, and Lemma \ref{lem:bound_expected_bellman}. We have the following set of equations: \begin{align} R_2(T) &= \frac{L}{T}\Big|\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}\left(\lambda_{\pi_e}^{\Tilde{P}_e} - \lambda_{\pi_e}^{P}\right)\Big|\\ &= \frac{L}{T}\Big|\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}\sum_{s,a}\rho_{\pi_e}^P B^{\pi_e, \Tilde{P}_e}(s,a)\Big|\label{eq:use_reward_to_bellman_lemma}\\ &\le \frac{L}{T}\Big|\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1} B^{\pi_e, \Tilde{P}_e}(s_t,a_t) + 4T_M\sqrt{6T\log(2T)} + \frac{4CET_MS}{1-\rho}\Big|\label{eq:use_expected_bell_man_bound_lemma}\\ &\le \frac{L}{T}\Big|\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1} T_M\sqrt{\frac{14S\log(2AT)}{1\vee N_e(s_t,a_t)}} + 4T_M\sqrt{6T\log(2T)}+\frac{4CET_MS}{1-\rho}\Big|\label{eq:use_realized_bellman_bound_lemma}\\ &\le \frac{L}{T}\Big|\sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1} \sum_{s,a}\bm{1}_{\{s_t = s, a_t=a\}}T_M\sqrt{\frac{14S\log(2AT)}{1\vee N_e(s,a)}} + 4T_M\sqrt{6T\log(2T)}+\frac{4CET_MS}{1-\rho}\Big|\\ &\le \frac{L}{T}\Big|\sum_{e=1}^E\sum_{s,a}\nu_e(s,a)T_M\sqrt{\frac{14S\log(2AT)}{1\vee N_e(s,a)}} + 4T_M\sqrt{6T\log(2T)}+\frac{4CET_MS}{1-\rho}\Big|\\ &\le \frac{L}{T}\Big|\sum_{s,a}T_M\sqrt{14S\log(2AT)}\sum_{e=1}^E\frac{\nu_e(s,a)}{\sqrt{1\vee N_e(s,a)}} + 4T_M\sqrt{6T\log(2T)}+\frac{4CET_MS}{1-\rho}\Big|\\ &\le \frac{L}{T}\Big|\sum_{s,a}T_M(\sqrt{2}+1)\sqrt{14S\log(2AT)}\sqrt{N(s,a)} + 4T_M\sqrt{6T\log(2T)}+\frac{4CET_MS}{1-\rho}\Big|\label{eq:jaksch_root_sum}\\ &\le \frac{L}{T}\Big|T_M(\sqrt{2}+1)\sqrt{14S\log(2AT)}\sqrt{\left(\sum_{s,a} 1\right)\left(\sum_{s,a}N(s,a)\right)} + 4T_M\sqrt{6T\log(2T)}+\frac{4CET_MS}{1-\rho}\Big|\label{eq:cauchy_scharwz_2}\\ &\le \frac{L}{T}\Big|T_M(\sqrt{2}+1)\sqrt{14S\log(2AT)}\sqrt{SAT} + 4T_M\sqrt{6T\log(2T)}+\frac{4CT_MS\log T}{1-\rho}\Big| \end{align} where Equation \eqref{eq:use_reward_to_bellman_lemma} follows from Lemma \ref{lem:bound_average_by_bellman}, Equation \eqref{eq:use_expected_bell_man_bound_lemma} follows from Lemma \ref{lem:bound_expected_bellman}, and Equation \eqref{eq:use_realized_bellman_bound_lemma} follows from Lemma \ref{lem:bound_expected_bellman}. Equation \eqref{eq:jaksch_root_sum} follows from \cite[{Lemma 19}]{jaksch2010near} and Equation \eqref{eq:cauchy_scharwz_2} follows from Cauchy-Schwarz inequality. Further, the value of $E$ is bounded by $\log T$ from \cite[{Proposition 18}]{jaksch2010near}. \newpage \subsection{Bounding $R_3(T)$} Bounding $R_3(T)$ follows mostly similar to Lemma \ref{lem:bound_expected_bellman}. At each epoch, the agent visits states according to the occupancy measure $\rho_{\pi_e}^P$ and obtains the rewards. We bound the deviation of the observed visitations to the expected visitations to each state action pair in each epoch. \begin{lemma}\label{lem:bound_average_observed_reward_gap} With probability at least $1-1/T^6$, the difference between the observed rewards and the expected rewards is bounded as: \begin{align} \Big|\sum_{e=1}^E(t_{e+1}-t_e)\mathbb{E}_{\pi_e,P}\left[r(s,a)\right] - \sum_{e=1}^E\sum_{t=t_e}^{t_{e+1}-1}r(s_t,a_t)\Big| \le 4\sqrt{6T\log(T)} + \frac{4CES}{1-\rho} \end{align} \end{lemma} \section{Related Works} \textbf{Unconstrained RL:} Much work has been done to understand finite time performance of algorithms for the tabular setup. \citet{jaksch2010near} provided epoch based UCRL2 algorithm which achieves a regret bound of $\Tilde{O}(DS\sqrt{A/T})$ for infinite horizon setup using optimism and proved a lower bound of $O(\sqrt{DSA/T}$ for MDPs with diameter $D$. \citet{fruit2018efficient} provided an improved epoch based SCAL algorithm with regret $O(D\sqrt{SA/T})$. The analysis of both UCRL2 and SCAL algorithm have an additional regret which increases linearly in the number of epochs coming from the fact that triggering a new policy takes few steps to converge to the stationary distribution. However, the algorithm bound the number of epochs in logarithmic order of time horizon $T$. \noindent\textbf{Constrained RL:} The work by \citet{altman1999constrained} summarized the requirements for the study of constrained reinforcement learning, along with the formulation for constrained MDPs and algorithms for obtaining policies with known transition models. Similar to the unconstrained setup, recently there is progress towards understanding the convergence properties of the algorithms along with finite time performance. \citep{zheng2020constrained} considered an episodic CMDP and use an optimism based algorithm to bound the constraint violation as $\Tilde{O}(1/T^{0.25})$ with high probability. \citep{kalagarla2020sample} also considered the episodic setup to obtain PAC-style bound for an optimism based algorithm. \citep{ding2021provably} considered the setup of $H$-episode length episodic CMDPs with $d$-dimensional linear function approximation to bound the constraint violations as $\Tilde{O}(d\sqrt{H^5/T})$ by mixing the optimal policy with an exploration policy. \citep{efroni2020exploration} proposes a linear-programming and primal-dual policy optimization algorithm to bound the regret as $O(S\sqrt{H^3/T})$. \citep{qiu2020cmdp} proposed an algorithm which obtains a regret bound of $\Tilde{O}(S\sqrt{AH^2/T})$ for the problem of adversarial stochastic shortest path. \citet{wei2021provably} considered the problem of ensuring zero constraint violations using a model-free algorithm for tabular MDPs with linear rewards and constraints. However, they achieve that result at the expense of an increased regret bound of $O(T^{-1/5})$. Compared to these works, we focus on setting with infinite horizon long-term average constraints. \citet{xu2020primal} consider an infinite horizon discounted setup with constraints and obtain global convergence using policy gradient algorithms. \citet{ding2020natural} also considers an infinite horizon discounted setup. They use a natural policy gradient to update the primal variable and sub-gradient descent to update the dual variable. \citet{singh2020learning} considered the setup of infinite-horizon CMDPs with long-term average constraints with an optimism based algorithm and forced explorations. We consider a similar setting with unichain CMDP and propose an optimism based algorithm to bound the regret as $\Tilde{O}(LdT_{M}S\sqrt{A/T})$ using explorations assisted by the ergodicity of the MDP. Very recently, \citet{gattami2021reinforcement} analyzed the asymptotic performance for Lagrangian based algorithms for infinite-horizon long-term average constraints, however they only show convergence guarantees without explicit convergence rates. \noindent\textbf{Concave Utility RL:} Another major research area related to constrained RL is concave utility RL \cite{hazan2019provably}. Along this direction, \citet{cheung2019regret} considered a concave function of expected per-step vector reward and developed an algorithm using Frank-Wolfe gradient of the concave function for tabular infinite horizon MDPs. \citet{agarwal2019reinforcement} also considered the same setup, but proposed a posterior sampling based algorithm. Recently, \citet{brantley2020constrained} combined concave utility reinforcement learning and constrained reinforcement learning for an episodic setup. \citet{yu2021morl} also considered the case of episodic setup with concave utility RL. However, both \citet{brantley2020constrained} and \citet{yu2021morl} consider the weaker regret definition by \citet{efroni2020exploration}, and \citet{cheung2019regret} and \citet{yu2021morl} do not target the convergence of the policy. Further, these works do not target zero-constraint violations. Compared to prior works, we consider the constrained reinforcement learning with convex constraints and concave objective function. Using infinite-horizon setup, we consider the tightest possible regret definition. Further, we achieve zero constraint violations with objective regret tight in $T$ using an optimization problem with decaying tightness. A quick comparative survey of prior works and our work is also presented in Table \ref{tab:algo_comparisons}. \section{Problem Formulation} We consider a tabular infinite-horizon constrained Markov Decision Process $\mathcal{M} = (\mathcal{S}, \mathcal{A}, r, f, c_1, \cdots, c_d, g, P)$ with bounded diameter $D$. $\mathcal{S}$ is finite set of $S$ states, and $\mathcal{A}$ is a finite set of $A$ actions. $P:\mathcal{S}\times\mathcal{A}\to\Delta(\mathcal{S})$ denotes the transition probability distribution such that on taking action $a\in\mathcal{A}$ in state $s\in\mathcal{S}$, the system moves to state $s'\in\mathcal{S}$ with probability $P(s'|s,a)$. $r:\mathcal{S}\times\mathcal{A}\to[0,1]$ and $c_i:\mathcal{S}\times\mathcal{A}\to[0,1], i\in{1, \cdots, d}$ denotes the average reward obtained and average costs incurred in state action pair $(s,a)\in \mathcal{S}\times\mathcal{A}$. The agent interacts with $\mathcal{M}$ in time-steps $t\in{1, 2, \cdots}$ for a total of $T$ time-steps. We note that $T$ is possibly unknown. At each time $t$, the agent observes state $s_t$, plays action $a_t$. The agent selects an action on observing the state $s$ using a policy $\pi:\mathcal{S}\to\Delta(\mathcal{A})$, where $\Delta(\mathcal{A})$ is the probability simplex on the action space. On following a policy $\pi$, the long-term average reward of the agent is denoted as: \begin{align} \lambda_{\pi}^P &= \lim_{\tau\to\infty}\mathbb{E}_{\pi,P}\left[\frac{1}{\tau}\sum\nolimits_{t=1}^\tau r(s_t,a_t)\right] \end{align} where $\mathbb{E}_{\pi, P}[\cdot]$ denotes the expectation over the state and action trajectory generated from following $\pi$ on transitions $P$. The long-term average reward can also be represented as: \begin{align} \lambda_{\pi}^P &= \lim_{\gamma\to1}(1-\gamma)V_\gamma^{\pi, P}(s)\ \ \ \forall s\in\mathcal{S}\\ &= \sum\nolimits_{s,a}\rho_{\pi}^P(s,a)r(s,a) \end{align} where $V_\gamma^{\pi, P}(s)$ is the discounted cumulative reward on following policy $\pi$, and $\rho_{\pi}^{P}\in\Delta(\mathcal{S}\times\mathcal{A})$ is the steady-state occupancy measure generated from following policy $\pi$ on MDP with transitions $P$ \cite{puterman2014markov}. Similarly, we also define the long-term average costs as follows: \begin{align} \zeta_{\pi}^P(i) &= \lim_{\tau\to\infty}\mathbb{E}_{\pi,P}\left[\frac{1}{\tau}\sum\nolimits_{t=1}^\tau c_i(s_t,a_t)\right]\\ &= \lim_{\gamma\to1}(1-\gamma)V_\gamma^{\pi, P}(s;i)\ \ \ \forall s\in\mathcal{S}\\ &= \sum_{s,a}\rho_{\pi}^P(s,a)c_i(s,a) \end{align} The agent interacting with the CMDP $\mathcal{M}$ aims to maximize a function $f:[0,1]\to\mathbb{R}$ of the average per-step reward. Further, the agent attempts to ensure that a function of average per-step costs $g:[0,1]^d\to\mathbb{R}$ is at most $0$. The goal is represented mathematically as: \begin{align} &\max_\pi f\left(\lambda_\pi^P\right)\\ &s.t.\ g\left(\zeta_{\pi}^P(1), \cdots, \zeta_{\pi}^P(d)\right) \le 0, \end{align} \begin{remark} Note that the model, the proposed algorithm, and the analysis can be easily extended to $M$ convex constraints $g_1\cdots, g_M$ by applying union bounds. \end{remark} We are now ready to introduce our initial assumptions on the MDP $\mathcal{M}$. Let $P^{t}_{\pi, s}$ denote the $t$-step transition probability on following policy $\pi$ in MDP $\mathcal{M}$ starting from state $s$. Also, let $T_{s\to s'}^\pi$ denotes the time taken by the Markov chain induced by the policy $\pi$ to hit state $s'$ starting from state $s$. Building on these variables, $P^t_{\pi, s}$ and $T_{s\to s'}^\pi$, we make our first assumption as follows: \begin{assumption} The MDP $\mathcal{M}$ is ergodic, or \begin{align} \|P^t_{\pi, s} - P_{\pi}\| \le C\rho^t \end{align} where $P_\pi$ is the long-term steady state distribution induced by policy $\pi$, and $C > 0$ and $\rho < 1$ are problem specific constants. Also, we have \begin{align} T_M := \max_\pi \mathbb{E}[T^\pi_{s\to s'}] < \infty \end{align} where $T_M$ is the finite mixing time of the MDP $\mathcal{M}$. \end{assumption} \begin{assumption} \label{known_rewards} The rewards $r(s,a)$, the costs $c_i(s,a); \forall \ i$ and the functions $f$ and $g$ are known to the agent. \end{assumption} We note that in most of the problems, rewards are engineered according to the problem. Hence, Assumption \ref{known_rewards} is justified in many setups. However, the system dynamics are stochastic and typically not known. Our next assumption is on the functions $f$ and $g$. We have \begin{assumption}\label{concave_assumption} The scalarization function $f$ is jointly concave and the constraints $g$ are jointly convex. Hence for any arbitrary distributions $\mathcal{D}_1$ and $\mathcal{D}_2$, the following holds. \begin{align} f\left(\mathbb{E}_{x\sim\mathcal{D}_1}\left[x\right]\right) &\geq \mathbb{E}_{x\sim\mathcal{D}_1}\left[f\left(x\right)\right]\label{eq:concave_utility}\\ g\left(\mathbb{E}_{\mathbf{x}\sim\mathcal{D}_2}\left[\mathbf{x}\right]\right) &\leq \mathbb{E}_{\mathbf{x}\sim\mathcal{D}_2}\left[g\left(\mathbf{x}\right)\right];\ \mathbf{x}\in\mathbb{R}^d\label{eq:convex_constraints} \end{align} \end{assumption} Many practically implemented fairness objectives are concave \citep{kwan2009proportional}, or the agent want to explore all possible state action pairs by maximizing the entropy of the long-term state-action distribution \citep{hazan2019provably}, or the agent may want to minimize divergence with respect to a certain expert policy \citep{ghasemipour2020divergence}. We impose an additional assumption on the functions $f$ and $g$. We assume that the functions are continuous and Lipschitz continuity in particular. We have, \begin{assumption}\label{lipschitz_assumption} The function $f$ and $g$ are assumed to be a $L-$ Lipschitz function, or \begin{align} \left|f\left(x\right) - f\left(y\right)\right| &\leq L|x - y|;\ x,y\in\mathbb{R} \label{eq:Lipschitz}\\ \left|g\left(\mathbf{x}\right) - g\left(\mathbf{y}\right)\right| &\leq L\left\lVert \mathbf{x} - \mathbf{y}\right\rVert_1;\ \mathbf{x}, \mathbf{y}\in\mathbb{R}^d \label{eq:cost_Lipschitz} \end{align} \end{assumption} Lipschitz continuity is a common assumption for optimization literature \citep{bubeck2015convex,jin2017escape,zhang2020variational}. Additionally, in practice this assumption is validated, often by adding some regularization. Next, we assume the following Slater's condition to hold. \begin{assumption} \label{slaters_conditon} There exists a policy $\pi$, and one constant $\delta > LdST_M\sqrt{A}$ such that \begin{align} g\left(\zeta_{\pi}^P(1), \cdots, \zeta_{\pi}^P(d)\right) \le -\delta \end{align} \end{assumption} Further, if the agent has access to a lower bound of time-horizon, $T_l\ge\exp{(1)}$, then we only require $\delta > LdST_M\sqrt{A(\log T_l)/T_l}$. This assumption is again a standard assumption in the constrained RL literature \citep{efroni2020exploration,ding2021provably,ding2020natural,wei2021provably}. $\delta$ is referred as Slater's constant. \citep{ding2021provably} assumes that the Slater's constant $\delta$ is known. \citep{wei2021provably} assumes that the number of iterations of the algorithm is at least $ \Tilde{\Omega}(SAH/\delta)^5$ for episode length $H$. On the contrary, we simply assume the existence of $\delta$ and a lower bound on the value of $\delta$ which can be relaxed as the agent acquires more time to interact with the environment. Any online algorithm starting with no prior knowledge will require to obtain estimates of transition probabilities $P$ and obtain reward $r$ and costs $c_k, \forall\ k\in\{1,\cdots,d\}$ for each state action pair. Initially, when algorithm does not have good estimate of the model, it accumulates a regret as well as violates constraints as it does not know the optimal policy. We define reward regret $R(T)$ as the difference between the average cumulative reward obtained vs the expected rewards from running the optimal policy $\pi^*$ for $T$ steps, or \begin{align} R(T)& = f\left(\lambda_{\pi^*}^P\right) - f\left(\frac{1}{T}\sum\nolimits_{t=1}^Tr(s_t, a_t)\right) \nonumbe \end{align} Additionally, we define constraint regret $C(T)$ as the gap between the constraint function and incurred and constraint bounds, or \begin{align} C(T)& = \left(g\left(\frac{1}{T}\sum_{t=1}^Tc_1(s_t, a_t), \cdots, \frac{1}{T}\sum_{t=1}^Tc_1(s_t, a_t)\right)\right)_+ \nonumbe \end{align} where $(x)_+ = \max(0, x)$. In the following section, we present a model-based algorithm to obtain this policy $\pi^*$, and reward regret and the constraint regret accumulated by the algorithm. \section{Simulation Details} \label{app:sim_details} To validate the performance proposed \textsc{UC-CURL} algorithm and the understanding of our analysis, we run the simulation on the flow and service control in a single-serve queue, which is introduced in \citep{altman1991constrained}. A discrete-time single-server queue with a buffer of finite size $L$ is considered in this case. The number of the customer waiting in the queue is considered as the state in this problem and thus $\vert S\vert=L+1$. Two kinds of the actions, service and flow, are considered in the problem and control the number of customers together. The action space for service is a finite subset $A$ in $[a_{min},a_{max}]$, where $0<a_{min}\leq a_{max}<1$. Given a specific service action $a$, the service a customer is successfully finished with the probability $b$. If the service is successful, the length of the queue will reduce by 1. Similarly, the space for flow is also a finite subsection $B$ in $[b_{min}, b_{max}]$. In contrast to the service action, flow action will increase the queue by $1$ with probability $b$ if the specific flow action $b$ is given. Also, we assume that there is no customer arriving when the queue is full. The overall action space is the Cartesian product of the $A$ and $B$. According to the service and flow probability, the transition probability can be computed and is given in the Table \ref{table:transition}. \begin{table*}[ht] \caption{Transition probability of the queue system} \label{table:transition} \begin{center} \begin{tabular}{|c|c|c|c|} \hline Current State & $P(x_{t+1}=x_t-1)$ & $P(x_{t+1}=x_t)$ & $P(x_{t+1}=x_t+1)$ \\ \hline $1\leq x_t\leq L-1$ & $a(1-b)$ & $ab+(1-a)(1-b)$ & $(1-a)b$ \\ \hline $x_t=L$ & $a$ & $1-a$ & $0$ \\ \hline $x_t=0$ & $0$ & $1-b(1-a)$ & $b(1-a)$ \\ \hline \end{tabular} \end{center} \end{table*} \begin{figure}[t] \centering \begin{subfigure}[b]{0.5\textwidth} \centering \includegraphics[width=1\linewidth]{model-reward.png} \caption{Reward growth \textit{w.r.t.} time} \label{fig:rewards} \end{subfigure} \hfill \begin{subfigure}[b]{0.5\textwidth} \centering \includegraphics[width=1\linewidth]{model-service.png} \caption{Service constraints \textit{w.r.t.} time} \label{fig:service} \end{subfigure} \hfill \begin{subfigure}[b]{0.5\textwidth} \centering \includegraphics[width=1\linewidth]{model-flow.png} \caption{Flow constraints \textit{w.r.t.} time} \label{fig:flow} \end{subfigure} \caption{Performance of the proposed \textsc{UC-CURL}\ algorithm on a flow and service control problem for a single queue with respect to algorithmic parameter $K$ and choice of policy update times.} \label{fig:Learning process of CMDP-PSRL} \end{figure} Define the reward function as $r(s,a, b)$ and the constraints for service and flow as $c^1(s,a, b)$ and $c^2(s,a, b)$, respectively. Define the stationary policy for service and flow as $\pi_a$ and $\pi_b$, respectively. Then, the problem can be defined as \begin{equation} \begin{split} \max_{\pi_a,\pi_b} &\quad \lim\limits_{T\rightarrow\infty}\frac{1}{T}\sum_{t=1}^{T}r(s_t,\pi_a(s_t),\pi_b(s_t))\\ s.t. &\quad \lim\limits_{T\rightarrow\infty}\frac{1}{T}\sum_{t=1}^{T}c^1(s_t,\pi_a(s_t),\pi_b(s_t))\geq 0\\ &\quad \lim\limits_{T\rightarrow\infty}\frac{1}{T}\sum_{t=1}^{T}c^2(s_t,\pi_a(s_t),\pi_b(s_t))\geq 0 \end{split} \end{equation} According to the discussion in \citep{altman1991constrained}, we define the reward function as $r(s,a,b)=5 - s$, which is an decreasing function only dependent on the state. It is reasonable to give higher reward when the number of customer waiting in the queue is small. For the constraint function, we define $c^1(s,a,b)=-10a + 6$ and $c^2 = - 8(1-b)^2+2$, which are dependent only on service and flow action, respectively. Higher constraint value is given if the probability for the service and flow are low and high, respectively. In the simulation, the length of the buffer is set as $L=5$. The service action space is set as $[0.2,0.4,0.6,0.8]$ and the flow action space is set as $[0.5,0.6,0.7,0.8]$. We use the length of horizon $T=10^5$ and run 100 independent simulations of the proposed \textsc{UC-CURL}\ algorithm. The result is shown in the Figure \ref{fig:Learning process}. The average values of the cumulative reward and the constraint functions are shown in the solid lines. Also, we plot the standard deviation around the mean value in the shadow to show the random error. It is found that the cumulative reward convergences to about 4. The service and flow constraints converge to 0 as expected. In order to compare this result to the optimal, we assume that the full information of the transition dynamics is known and then use Linear Programming to solve the problem. The optimal cumulative reward from LP is shown to be 4.08. We note that the reward of the proposed \textsc{UC-CURL}\ algorithm becomes closer the optimal reward as the algorithm proceeds \section{Experimental Studies} We now evaluate the empirical performance of the proposed \textsc{UC-CURL}\ algorithm using the flow and service control in a single-server queue, which is introduced in \citep{altman1991constrained}. We consider a discrete-time queue with a buffer of finite size $L$. The state is the number of customers waiting in the queue with $S = L+1$. The system has two types of actions, service and flow, to control the number of customers. At time $t$, the agent takes action $a_t = (a_t(1), a_t(2))$ from a finite subset of $[0,1]\times[0,1]$, where $a_t(1)$ is the service action and $a_t(2)$ is the flow action. The service action $a_t(1)$ reduces the queue length by $1$ with probability $a_t(1)$, and the flow action increases the queue by $1$ with probability $a_t(2)$. Also, we assume that there is no customer arriving when the queue is full. The precise environment and implementation details are provided in Appendix \ref{app:sim_details}. For $a_t \sim \pi$, the optimization problem is defined as \begin{equation} \begin{split} \max_{\pi} &\quad \lim\limits_{T\rightarrow\infty}\frac{1}{T}\sum\nolimits_{t=1}^{T}(5-s_t)\\ s.t. &\quad \lim\limits_{T\rightarrow\infty}\frac{1}{T}\sum\nolimits_{t=1}^{T}(6-10a_t(1))\geq 0\\ &\quad \lim\limits_{T\rightarrow\infty}\frac{1}{T}\sum\nolimits_{t=1}^{T}(2-8(1-a_t(2))^2)\geq 0 \end{split} \end{equation} We use the length of horizon $T=10^5$ and run 100 independent simulations of the proposed \textsc{UC-CURL}\ algorithm. The result is shown in the Figure \ref{fig:Learning process}. The average values of the long-term averaged reward and the constraint functions are shown in the solid lines, and the shadow region denotes the standard deviation. In order to compare this result to the optimal, we assume that the full information of the transition dynamics is known and then use Linear Programming to solve the problem. The optimal expected reward from LP is $4.08$ for the true MDP. We now make the following observations based on the simulation results. \textbf{Effect of the frequency of policy updates}: We compare the \textsc{UC-CURL}\ algorithm in Algorithm \ref{alg:algorithm} with a modified algorithm which updates the policy after every interaction with the environment. The number of epochs in Algorithm \ref{alg:algorithm} is bounded by $O(SA\log(T))$ \cite[Proposition 18]{jaksch2010near} whereas the number of epochs of the modified algorithm is $T$. Our claim that the proposed regret bounds does not depend on the number epochs, is empirically evident in Figure \ref{fig:reward_regret}. The regret of the doubling epoch based algorithm \ref{alg:algorithm} matches the regret guarantees of the everytime policy update strategy, however it does not match the performance empirically. However, the doubling epoch based algorithm obtains lower constraint violations as the agent plays $\epsilon_e$- conservative policy for longer duration, thus violating constraints less (Figure \ref{fig:flow_const} and Figure \ref{fig:service_const}). Compared to this, the agent which updates the policy after every interaction, plays a lesser conservative policy and this results in empirically increased constraints violations. \textbf{Effect of the parameter $K$ in \textsc{UC-CURL}\ algorithm}: We note that in practice the optimal $K= LdT_MS\sqrt{A}$ may be difficult to precisely calculate. Hence, we evaluate the proposed \textsc{UC-CURL}\ algorithm for various values of $K$. If we choose the multiplication factor $K=0$, we will not be achieving zero constraint violations but still bounding the constraint violations with $\Tilde{O}(LdT_MS\sqrt{A/T})$. Note that as we increase the value of $K$, the constraint violations decrease in Figure \ref{fig:service_const} and Figure \ref{fig:flow_const}. However, this results in a lower reward value as observed in Figure \ref{fig:reward_regret}. In principle, the agent must select $K$ which allows to obtain a feasible policy and reduce the violations.
{'timestamp': '2022-05-11T02:01:00', 'yymm': '2109', 'arxiv_id': '2109.05439', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05439'}
arxiv
\section{Introduction} \label{sec:introduction} \PARstart{F}{ederated} Learning (FL) is transforming many industries including defense, telecommunications, IoT, and transportation \cite{yang2019federated}. This Machine Learning (ML) paradigm addresses issues such as data privacy, security, access rights and access to heterogeneous data by training a global model using distributed data. In FL, a group of nodes called \textit{workers} participate to build a global model under the coordination of one node, the \textit{chief}. After each round of the FL process, the \textit{chief} sends a matrix of weights to the \textit{workers}. Each \textit{worker} then computes its local model update based on their local data. Once the \textit{chief} node gets all the local model updates from the \textit{workers}, it averages the models with an aggregation rule and updates them into a single matrix. The process repeats for several rounds of training until a pre-specified test accuracy is reached or the maximum number of time epochs have elapsed. Although FL enables nodes to construct a model without sharing their private data with others, the fact that the \textit{chief} has no visibility into how the updates are generated represents a vulnerability in the process. Regarding the cybersecurity of FL, attacks aim at exploiting this vulnerability. According to Blanchard et al. \cite{blanchard2017machine}, classical averaging rules are so fragile that even a single malicious \textit{worker} can manipulate the entire learning process by sabotaging prediction accuracy. Many defense mechanisms propose corrections to the FL process to increase system efficiency. They apply statistical methods to correct the aggregation rule implemented at the \textit{chief} \cite{chen2017distributed, mhamdi2018hidden, alistarh2018byzantine}. Rather than correcting, other approaches proposed to detect malicious \textit{workers} by interpreting information of the \textit{workers}’ behaviors in order to eliminate potential malicious \textit{workers}. Kang et al. proposed a reputation-based scheme in order to select reliable and trusted \textit{workers} \cite{kang2020reliable} . Preuveneers et al. proposed to audit the local model updates and the \textit{workers} in the FL process are held accountable \cite{preuveneers2018chained}. As most of the defense strategies are based on malicious \textit{worker} detection, there is an urgency to prepare the federated learning process for monitoring and eventually behavioral pattern analysis. In fact, without timely and dynamic monitoring methods, the \textit{chief} cannot detect and remove the malicious or unreliable \textit{workers} from the system. Moreover, it is hard for the \textit{chief} to monitor the large-scale \textit{worker} behaviors in real-time. Pan et al. scratched the surface by proposing to visualize the behavior of the \textit{workers} \cite{pan2020justinian}. They suggested to visualize the policy sequence of their model in order to understand the temporal patterns of the attacks. This paper proposes to study the information inside the learning process of each \textit{worker} in order to increase the efficiency of the behavior pattern analysis approaches. Precisely, we aim to analyse at what time is it appropriate to start the detection algorithm in order to remove the malicious or unreliable \textit{workers} from the system. The intuition is that \textit{workers} should not be removed from the FL process too early nor too late. There must be an appropriate time window for monitoring after which the detection protocol or the behavior pattern analysis will start declaring that the nodes are malicious. Otherwise, in the early stages of training, this will result in false evaluation of the legitimacy of the nodes. Moreover, in a recent review of the topic, Lyu et al. \cite{lyu2020privacy} highlighted the importance of studying how to optimize the timing of deploying the defense mechanisms. They stressed the fact that when defense mechanisms are deployed to check if any adversary is attacking the FL system, the FL server requires additional computational cost. They also put forward that different types of defense mechanisms may incur different cost against different attacks. Our paper aims at addressing the challenges by proving that there must be a monitoring period during the FL process prior to the deployment of the defenses. In our analysis, we show that the time metric has an impact on the false positive and false negative rates. By studying the context of the federated learning process, the defense mechanisms must compute the time metric as per our analysis in order to provide more accurate and efficient results. We tested our suggested monitoring process and empirical results show a decrease in false positive and false negative rates and consequently, an increase in system efficiency. The key contributions of this paper are: \begin{itemize} \item A monitoring process during the early stages of training in FL for the defense approaches that are based on behavioral pattern analysis to eliminate potential malicious \textit{workers} from the FL process. \item Evaluation of the monitoring period required in order to improve system efficiency in terms of the time cost of the iterations and computation overheads in the beginning of training for the behavioral pattern analysis approaches. \item Implementation of the monitoring process and evaluation of its appropriate time period on a behavioral pattern analysis defense applied to the distributed learning process of different benchmark systems for text and image classification (MNIST, CIFAR-10). \end{itemize} The rest of the paper is organised as follows: in Section~\ref{sec:background} we present a literature review on the cybersecurity of the FL process. In Section~\ref{sec:methodology} is described the methodology. In Sections ~\ref{sec:implementation} and ~\ref{sec:Results}, we describe the implementation details, the simulation and provide experimental results of the monitoring process. The primary conclusions and future work are outlined in Section~\ref{sec:conclusion}. \section{Literature review} \label{sec:background} Typically, the FL process consists of $\mathcal{K}$ \textit{workers} and a \textit{chief} that trains a model \textit{f} with $\textbf{w}_G$ $\in$ $\mathbb{R}^n$ being the global parameter vector, where \textit{n} is the dimension of the parameter space. The resulting global model is obtained by distributed training and aggregation over the $\mathcal{K}$ \textit{workers} holding data samples $\mathcal{D}_i$ locally, where $\mid\mathcal{D}_i\mid = l_i $. The total number of data samples is $ \sum\limits_{i} l_i = l$. Each \textit{worker} keeps its data private, i.e. $\mathcal{D}_i$ = $\{x_1^i, ..., x^i_l\}$ is not shared with the \textit{chief} $\mathcal{S}$ or any other \textit{worker} $i \neq j, \forall j \in \mathcal{K}$ \cite{yang2019federated}. The aim of the training is to generalize beyond a test dataset $\mathcal{D}_{test}$. At each time step \textit{t}, a random subset of \textit{k} \textit{workers} is selected by the \textit{chief}. Every \textit{worker} $ i \in \mid k \mid$ trains a local model to minimize a loss function over its own data $\mathcal{D}_i$. The \textit{worker} starts the local training from the global model $\textbf{w}_G^t$ received from the \textit{chief} and runs an algorithm such as the stochastic gradient descent for a number of $\mathcal{E}$ epochs with a batch size of $\mathcal{B}$. Each \textit{worker} then obtains a local weight vector $\textbf{w}_i$ and then computes its local model update $\delta_i^t$ = $\textbf{w}_i$ - $\textbf{w}_G^t$. The local model update is sent back to the \textit{chief}. To obtain the global model update $\textbf{w}_G$ for the next iteration, an aggregation mechanism is used: $\textbf{w}_G$ = $\textbf{w}_G^t$ + $ \sum\limits_{ i \in \mid k \mid} \alpha_i \delta_i$, where $\alpha_i$ = $l_i/l$ and $ \sum\limits_{i} \alpha_i = 1$. Regarding the cybersecurity of the FL process, some statistical methods aim at correcting the aggregation rule implemented at the chief node. GeoMed computes the geometric median as the proposed estimator, which assumes the Byzantine ratio satisfies n $\geqslant$ 2m + 1 \cite{chen2017distributed}. Krum is another approach that assumes the Byzantine ratio satisfies n $\geqslant$ 2m + 3 \cite{blanchard2017machine}. It first finds the $n - m - 2$ closest vectors in Q for each $V_i$ , and then computes a score for each vector $V_i$. Finally, it proposes the vector $V_i$ with the smallest score as the next update step, i.e. $F(V_1, ..., V_n) = argmin_Vi\in_Q s(V_i)$. Bulyan was originally designed for Byzantine attacks that concentrate on a single coordinate \cite{mhamdi2018hidden}. First, it runs Krum over \textit{Q} without replacement for $n-2m$ time and collect the $n - 2m$ gradients to form a selection set. It then computes \textit{F} coordinate-wise: the i-th coordinate of \textit{F} is equal to the average of the $n-4m$ closest i-th coordinates to the median i-th coordinate of the selection set. Bulyan has the strictest assumption as n $\geqslant$ 4m+3 which significantly limits its practical usage. In \cite{fang2020local}, to defend against local model poisoning attacks, the authors generalize RONI \cite{barreno2010security} and TRIM \cite{jagielski2018manipulating}. Both generalized defenses remove the local models that are potentially malicious before computing the global model in each iteration of federated learning and they start as soon as training starts. One generalized defense removes the local models that have large negative impact on the error rate of the global model (inspired by RONI that removes training examples that have large negative impact on the error rate of the model), while the other defense removes the local models that result in large loss (inspired by TRIM that removes the training examples that have large negative impact on the loss). They do not consider delaying the anomaly detection by leaving a monitoring period before starting the defense. In \cite{cao2019understanding}, the authors propose a filtering mechanism, Sniper, which is conducted by the chief, to remove attackers from the global model aggregation by examining Euclidean distances between local models. Through observing the distance between models, they found models of honest users and attackers are in different cliques. Based on this, they propose a filtering defense mechanism where during every communication, the chief must run it to filter parameters updated by attackers. As a result, Sniper can recognize honest users and drop attack success rate significantly even when multiple attackers are in the federated learning system. The chief runs Sniper during every updating rather than only at the beginning of training. This can prevent attackers upload contaminated parameters at a few epochs or after a few benign sharing. Again, they do not account for a monitoring period before starting the anomaly detection. We argue that monitoring period results in a better detection performance. In \cite{fung2018mitigating}, they evaluate the vulnerability of federated learning to sybil-based poisoning attacks. They propose FoolsGold, a defense that identifies poisoning sybils based on the diversity of client updates in the distributed learning process. FoolsGold changes the federated learning algorithm, relies on standard techniques such as cosine similarity, and does not require prior knowledge of the expected number of sybils. FoolsGold uses client contribution similarity and starts the defense without leaving a monitoring period. An increasing number of approaches propose to detect malicious workers by interpreting information of the workers’ behaviors in order to eliminate them from the FL process. By eliminating potential malicious workers, the techniques constitute further mitigation and help accelerate the learning process. Pan et al. propose a reinforcement learning method based on a gradient aggregation agent \cite{pan2020justinian}. The method utilize the historical interactions with the workers as experience to generate reward signals for policy learning. They start the detection which they defined as a classification task with no monitoring period and report their results after a fixed number of iterations of distributed learning. Xie et al. use the loss decrease at the current iteration on the training set to rank the workers’ credibility \cite{xie2019zeno}. Afterwards, the algorithm aggregates the candidates with highest scores. The score roughly indicates the level of trust in each candidate. They start their suspicion-based aggregation rule without a monitoring period and eliminate malicious workers from the process by taking the gradient estimators with the highest scores only. We want to better analyse the convergence of the FL process with regards to time when the defenses are applied in order to account for more effective and accurate malicious \textit{worker} detection and behavior pattern analysis. To the best of our knowledge, no previous work tried to leave a monitoring period in order to evaluate if it results in a better detection performance. \section{Methodology} \label{sec:methodology} Defense mechanisms that are implemented at the \textit{chief} node try to learn from the interactions with the \textit{workers} and leverage the information received to protect the FL process in adversarial settings. The defense restores robustness by detecting malicious \textit{workers} and eliminating them from the FL process. In the current state of information technology security practice, detection and response come only after effective monitoring. This will allow to adequately identify malicious \textit{workers} and take appropriate response actions. \subsection{Security settings} Figure~\ref{fig:cycle} shows the security decision loop enabling adequate decision-making in terms of detection, prioritization and response to attacks. We stress the fact that to maintain an adequate security posture, the monitoring period is required especially in FL where early detection will necessary get a significant number of false positives and false negatives in the beginning of training. Monitoring has to be done for a certain period of time after which the cycle continues with the detect, decide and respond actions as per the figure. \begin{figure}[h] \centering \includegraphics[width=1\columnwidth]{cycle.png} \caption{Security decision loop - The cycle of security defense can be described in terms of a loop with the functions of Monitor, Detect, Decide and Respond.} \label{fig:cycle} \end{figure} This work aims at studying the appropriate initial monitoring period of time $\Delta$ to consider in each context of FL. We study how long do we need to monitor before starting to detect. Instead of a random value of $\Delta$ after which evaluating the performance of the defense methods, we put forward a strategy to compute this value. If we are able to estimate the value of $\Delta$, we will improve the efficiency of FL in adversarial settings especially in terms of time efficiency where the running time of different defenses will improve. Precisely, the time cost of the iterations in the beginning of training will be greatly improved because only monitoring will be done during a period of $\Delta$. After this period, the defense algorithm may start to detect malicious workers and this would have brought computation overheads to lower levels. This approach is even more appreciated in a decentralized federated learning setting or in IoT networks, such as wearable devices, or smart homes where the edge device has limited resources or connectivity. In these settings, federated learning methods must be optimized to operate and train models that efficiently adapt to changes in these systems. Improving the efficiency of FL in adversarial settings especially in terms of time efficiency and computation overhead contributes to this achievement. The value of the initial monitoring period of time $\Delta$ varies depending on many factors: the federated learning process under study (underlying case study for the training of the machine learning model), attacking patterns and defense strategy deployed. In fact, different FL processes for training deep neural networks have learning curves that follow different distributions. Moreover, different attack patterns tend to cause instability in the learning curves of the FL process. Finally, depending on the defense strategy deployed, some may perform better than others that tend to yield accuracy that distribute in a slightly wider range. \subsubsection{Attack patterns} In our threat model, malicious \textit{workers} create malicious local model updates by submitting random values sampled from a multi-dimensional Gaussian $\mathcal{N}(\mu,\,\sigma^{2})$. We take $\mu$ = [0.5,...,0.5] $\in$ $R^d$ and $\sigma$ = $2x10^6$. This attack represents an untargeted poisoning on the FL process. Moreover, we investigate different attacking patterns. Firstly, in a static attack, a fixed number of \textit{workers} are compromised and perform continuous attacks during the entire learning process. Another attack pattern consists of a fixed number of \textit{workers} pretending to be benign in the first fixed number of rounds and start the attack afterwards. We call this attack the pretence attack. In a randomized attack, each compromised \textit{worker} is assigned with its role by the adversary. During the learning process, the \textit{worker} changes its role with a certain probability. \subsubsection{Defense strategy} We implement one of the defense strategies proposed in Mallah et al. \cite{mallah2021untargeted} for untargeted poisoning attack detection in federated learning via behavior attestation. The strategy assumes that the \textit{chief} node has a small validation dataset. Then, the \textit{chief} tests how the local models sent by the \textit{worker} predict on the same validation dataset iteration after iteration in order to assess if the \textit{worker} is reliable. The \textit{worker}'s performance in terms of error rate compared to their own previous performance on that validation dataset will highlight if the node appears to be learning. The strategy removes the local models that have large negative impact on the error rate. The error is expected to be smaller over time when the node is not malicious. However, if the error doesn't improve nor decrease over time, then the node is considered unreliable. At iteration $t$, for each \textit{worker} $j$, we compute the error, $E_j^{t+1}$ of the current local model $LM_j^{t+1}$ on the validation dataset. We then compare it to the error at the previous iteration, $E_j^{t}$ as follows: \begin{equation} E_j^{t+1} - E_j^{t}= E_j^{t+1}(LM_j^{t+1}) - E_j^{t}(LM_j^{t}) \end{equation} \subsection{Analytical formulation} In this section, we will provide a mathematical formulation of the monitoring period. In fact, the value of the monitoring period of time $\Delta_T$ varies depending on many factors. It may vary depending on the federated learning process under study, the attack patterns and the defense strategies. \begin{equation} \Delta_T = \min(\alpha_F, \beta_A, \gamma_D) \end{equation} \begin{align*} \alpha_F &= \lfloor f(s, m, a) \rfloor\\ \beta_A &= \lfloor g(A_i) \rfloor\\ \gamma_D &= \lfloor h(D_j) \rfloor \end{align*} $\alpha_F$ is a function of the federated learning process under study \textit{f(s, m, a)}, the underlying case study for the training of the machine learning model because different FL processes for training deep neural networks have learning curves that follow different distributions. The FL process is characterized by the size of the training set \textit{s}, the type of model \textit{m}, (supervised, semi-supervised or unsupervised), and the architecture \textit{a}, (convolutional neural networks, auto-encoders, recurrent neural networks). $\beta_A$ is a function of \textit{$g(A_i)$} and corresponds to the different attack patterns (\textit{i}= static, pretence, randomized attacks), because different patterns tend to cause instability in the learning curves of the FL process. $\gamma_D$ is a function of \textit{$h(D_j)$} and corresponds to the defense strategy deployed. Some defenses may perform better than others that tend to yield accuracy that distribute in a slightly wider range (\textit{j}= KRUM, GeoMed, attestedFL). The monitoring period $\Delta_T$ corresponds to the minimum number of iterations required before the performance accuracy of the model diverges from the global optima. The minimum value corresponds to the minimum of the $\alpha_F$, $\beta_A$, $\gamma_D$ metrics. Training of a neural network stops when the error, i.e., the difference between the desired output and the expected output is below some threshold value or the number of iterations or epochs is above some threshold value. Thus, the value of $\Delta_T$ ranges from 0 to the threshold value implemented. $\Delta_T$ is equal to $\alpha_F$ if the attack is benign and the defense is robust. This means that if an attack has a small impact on the FL process and the defense was able to neutralize it very quickly, the monitoring period required would be in line with the baseline behavior. $\Delta_T$ will be equal to $\beta_A$ if the attack is more powerful than the defense. Thus, $\beta_A$ becomes the limiting factor and the monitoring period of time advised should enable the defense to start eliminating earlier the malicious nodes from the aggregation. Finally, depending on the type of defense, $\Delta_T$ can be equal to $\gamma_D$, thus enabling a larger monitoring period before any anomaly detection can take effect. We developed a search process that will provide an empirical validation of the analytical results. Different datasets are used to demonstrate experimentally, under different scenarios, the monitoring period in terms of delay. \section{Implementation details} \label{sec:implementation} We implement two use cases of federated learning with Torch, a framework for deep learning \cite{collobert2002torch}. The first use case consist in training a fully connected neural network for the hand-written digital classification task on the MNIST dataset, with 10 workers. This public dataset contains 60,000 28×28 images of 10 digits for training and 10000 for testing. The model consists of 784 inputs, 10 outputs with soft-max activation and one hidden layer with 30 ReLu units. The dimension of parameters is 25,450. The second use case is training a ResNet-18 model for the image classification on the CIFAR-10 dataset with 10 workers. This dataset contains 60,000 28×28×3 images of 10 classes of objects for training and 10000 for testing. The standard model ResNet-18 has 18 end-to-end layers and 11173962 learnable parameters in total. In all use cases, each \textit{worker} shares a copy of the training set. We simulate the federated learning setting by sequential computation of gradients on randomly sampled mini-batches. Although any other dataset could have been chosen to validate our approach, MNIST and CIFAR-10 are used as a worldwide machine learning benchmark. Because MNIST is a labeled dataset that pairs images of hand-written numerals with the name of the respective numeral, it can be used in supervised learning to train classifiers. CIFAR-10 is an established computer-vision dataset used for object recognition. Both datasets are publicly available and are the most widely used datasets for machine learning research. Their simplicity and ease of use are what make them so widely used and deeply understood. To evaluate the performance of the FL process during the first iterations of training, we need to conduct experiments where the FL process is under normal conditions (i.e. under no attack) and report the accuracy the global model attains iteration after iteration. We will do so for the two use cases under study. Also, we need to conduct experiments where each FL process is under different attacking patterns (i.e static, pretence and randomized attacks). Finally, we conduct experiments when the defense is applied. In this case, we will also report the precision and recall of the detection mechanisms during the first iterations of the learning process and that, for different values of $\Delta$. \subsection{Analysis process} We present a process to investigate all possible combination of experiments to ensure a complete understanding of the FL performance during the first iterations of the learning process. The process is based on a One at A Time (OAT) analysis of the different factors affecting the accuracy of the model. In fact, the value of the initial monitoring period of time $\Delta$ depends on three factors: the federated learning process under study, attacking patterns and defense strategy deployed. In a OAT analysis, the effect of each factor on the accuracy is investigated. To do so, factors are investigated separately and one at a time analysis of each factor have to be conducted by varying one factor at a time and keeping all other factors fixed. Thus we first conduct the experiments where the FL is under no attacks. The performance of FL in each use case will serve as a baseline for the comparison with the other experiments. We then do the experiments where there are attacks and no defenses. They serve as the upper bound for the evaluation of $\Delta$. Afterwards we apply the defense on the three different attacks at three different values of $\Delta$. The OAT analysis will result in a total of 26 experiments (i.e. 18 + 2 + 6 = 26). For the experiments when defenses are applied, we present the precision and recall of the methods at each iteration. Because we are experimenting with three different values of $\Delta$, precision and recall will help estimate the appropriate value of $\Delta$ to be considered for each use case. \section{Experimental Results} \label{sec:Results} The performance of malicious \textit{workers} detection methods may be reported in terms of precision and recall as for any pattern recognition, information retrieval and classification in machine learning methods. Precision, which represents the positive predictive value, is the fraction of relevant instances among the retrieved instances. Recall, which represents the sensitivity, is the fraction of the total amount of relevant instances that were actually retrieved. In Figure~\ref{fig:pr}, we see a detection algorithm identifying 8 malicious \textit{workers} in an FL process containing 10 benign and 12 malicious \textit{workers} (the relevant elements). Of the 8 identified malicious \textit{workers}, 5 actually are malicious (True Positives, TP), while the other 3 are benign (False Positives, FP). 7 malicious \textit{workers} were missed (False Negatives, FN), and 7 benign were correctly excluded (True Negatives, TN). The detection’s precision is 5/8 (true positives / all positives) and represents how valid the results are. While its recall is 5/12 (true positives / relevant elements) and represents how complete the results are. \begin{figure} \begin{center} \includegraphics[width=1\linewidth]{TPFP.png} \caption{Components of precision and recall.} \label{fig:pr} \end{center} \end{figure} In the context of FL, a detection technique that ensures high recall but reduces precision is better than one that increases precision but reduces recall. Greater recall increases the chances of removing benign \textit{workers} and increases the chances of removing all malicious workers. Greater precision decreases the chances of removing benign workers but also decreases the chances of removing all malicious \textit{workers}. In sum, it is not that bad if you remove some benign \textit{workers} from the FL process however it is bad if you don’t remove almost all malicious \textit{workers} because of the aggregation rule. Among the strategies to evaluate the performance of the detection techniques, accuracy can be a misleading metric in the context of low ratio of malicious \textit{workers}. On the other hand, the F-measure considers precision and recall scores. In general, it is the harmonic mean, which, for the case of two numbers, coincides with the square of the geometric mean divided by the arithmetic mean. Particularly, the $F_1$ measure corresponds to a recall and precision that are evenly weighted and represents a special case of $\beta$ =1 in the general $F_\beta$ measure (for non-negative real values of $\beta$): \begin{equation} F_\beta = (1+ \beta^2) \bullet \frac{precision\bullet recall}{\beta^2 \bullet precision +recall} \end{equation} $F_\beta$ corresponds to the effectiveness of defense strategy with respect to a \textit{chief} who attaches $\beta$ times more importance to recall than precision". In our study, we use $\beta$=2 where the $F_2$ measure weights recall higher than precision. \subsection{Empirical validation} We run the two use cases (MNIST, CIFAR-10) with the defense starting at different monitoring periods of time $\Delta$ under different attacks. We show in Figures~\ref{fig:MNIST_1}, ~\ref{fig:MNIST_2}, and ~\ref{fig:MNIST_3}, the accuracy of the global model during the MNIST FL process under different attacks. We notice from the figures that under a static attack on MNIST, the model's accuracy decreased to 0.75 at iteration 58. The pretence attack on MNIST resulted in an accuracy of 0.89 at iteration 58 and the randomized attack has an accuracy of 0.15 at the epoch. In this use case, we notice that the attack that has the biggest impact is the randomized attack where any \textit{worker} can be compromised with a certain probability by the adversary at every iteration. When the defense is applied to protect against the static, pretence and randomized attack, we notice in all the figures that the accuracy of the model improves. When the defense starts at $\Delta$ = 0, in case of a static attack on MNIST, the model's accuracy is 0.72 at iteration 58. In Figure~\ref{fig:MNIST_2}, for the pretence attack, the accuracy improved of 0.07 at iteration 58 when $\Delta$ = 0 compared to when no defense is applied. Similarly for the randomized attack on MNIST in Figure~\ref{fig:MNIST_3}, the accuracy also improved of 0.07 at iteration 58 when $\Delta$ = 0. This is due to the robustness of the federated learning that is different under fixed or variable ratios of malicious \textit{workers}. The ratio can be fixed (static attack) or variable (pretence, randomized attacks). After \textit{t} steps of gradient descent when the ratio is fixed, the algorithm asymptotically converge to the global optimum. This is due to the fact that when the ratio is fixed over time, the defense helps the underlying system attain a sub-optimal parameter with a certain error in a predictable number of steps. The convergence of the learning process has the optimal rate O(1/t) in Byzantium-free learning case (baseline curves on the figures). Figure~\ref{fig:MNIST_1} shows an empirical validation of the analytical result for the MNIST dataset when the ratio of malicious \textit{workers} is fixed. However, when the ratio of malicious \textit{workers} varies over time as in Figures~\ref{fig:MNIST_2} and ~\ref{fig:MNIST_3}, the defense detects different rates from iteration to iteration so the error is not predictable, thus the accuracy is not stable over the training period. On another hand, we notice that for the same attack, when the defense is applied at different periods of time $\Delta$=10 and $\Delta$=40, the accuracy of the model is different. In Figure~\ref{fig:MNIST_1} for the static attack, at $\Delta$=0, the accuracy reaches 0.72 at iteration 58. However, when the defense starts at $\Delta$=10, the accuracy is 0.82 and at $\Delta$=40, the accuracy is 0.78. For this attack, we realize that between $\Delta$=0 and $\Delta$=10, the accuracy increased. This means that even if we start the defense 10 iterations later, it will not have a bad impact but it would rather improve the accuracy of the model. For the pretence attack, between $\Delta$=0 and $\Delta$=10, the accuracy increased of 0.01 and for the randomized attack, it increased of of 0.14. This shows that the best protection against attacks does not need to start right at the beginning of training but can start later and even performs better. There is an optimum amount of time where if the defense starts, the federated learning process can still be protected against attacks in an efficient way. We call this period of time, a monitoring period of duration $\Delta$. However, we notice that for all attacks, if the defense was to be applied later, at $\Delta$=40, the accuracy decreases significantly compared to when it is applied at $\Delta$=10. For the static attack on MNIST, the accuracy decreased of 4\% for the defense at $\Delta$=40 compared to when it was started at $\Delta$=10. Similarly for the pretence attack and the randomized attack on MNIST where the accuracy decreased of 7\% and 14\% respectively between $\Delta$=10 and $\Delta$=40 at iteration 58 in Figures~\ref{fig:MNIST_2}, ~\ref{fig:MNIST_3}. This indicates that the defense must not start too late otherwise the training is impacted by the attacks. This result was expected because the attackers had lots of time to sabotage the system. The defense that came later was not able to increase the model's accuracy in comparison to the defense that was applied earlier and was already eliminating malicious nodes from the FL process. We notice that for this use case, the randomized attack is the most impacted by a delay before a defense is applied. \begin{figure}[!h] \begin{center} \includegraphics[width=1\linewidth]{fig3.png} \caption{MNIST - Accuracy of the global model when under a static attack with the defense starting at different $\Delta$ periods.} \label{fig:MNIST_1} \end{center} \end{figure} \begin{figure}[!h] \begin{center} \includegraphics[width=1\linewidth]{fig4.png} \caption{MNIST - Accuracy of the global model when under a pretence attack with the defense starting at different $\Delta$ periods.} \label{fig:MNIST_2} \end{center} \end{figure} \begin{figure}[!h] \begin{center} \includegraphics[width=1\linewidth]{fig5.png} \caption{MNIST - Accuracy of the global model when under a randomized attack with the defense starting at different $\Delta$ periods.} \label{fig:MNIST_3} \end{center} \end{figure} Figures~\ref{fig:CIFAR_1}, ~\ref{fig:CIFAR_2}, and ~\ref{fig:CIFAR_3} show the accuracy of the global model for the CIFAR-10 use case under the static, pretence and randomized attacks with the defense starting at different $\Delta$ periods. When the defense is applied to protect against the attacks, we notice in all the figures that the accuracy of the model improves. Similar to MNIST, when the defense starts at $\Delta$=10 in Figure~\ref{fig:CIFAR_1}, the model's accuracy increases of 0.13 at iteration 58 in comparison to when the defense starts at $\Delta$=0. This means that even if we start the defense 10 iterations later, it will not have a bad impact but it would rather improve the accuracy of the model. In Figure~\ref{fig:CIFAR_2}, for the pretence attack on CIFAR, the accuracy improved of 0.08 at iteration 58 when the defense started at $\Delta$ = 10 compared to when it started at $\Delta$=0. For the randomized attack in Figure~\ref{fig:CIFAR_3}, the accuracy remained the same at iteration 58. Also, we found a similar result for CIFAR as for MNIST regarding the case when the defense is applied later, at $\Delta$=40. The defense must not start too late because the accuracy decreases compared to when it is applied at $\Delta$=10. For the static attack on CIFAR in Figure~\ref{fig:CIFAR_1}, the accuracy decreased of 10\% for the defense at $\Delta$=40 compared to when it was started at $\Delta$=10. For the pretence attack in Figure~\ref{fig:MNIST_2}, the accuracy increased of 2\%. For the randomized attack in Figure~\ref{fig:MNIST_3}, the accuracy decreased of 3\% between $\Delta$=10 and $\Delta$=40 at iteration 58. For this use case, the static attack is the most impacted by a delay before a defense is applied. \begin{figure}[h] \begin{center} \includegraphics[width=1\linewidth]{fig6.png} \caption{CIFAR - Accuracy of the global model when under a static attack with the defense starting at different $\Delta$ periods.} \label{fig:CIFAR_1} \end{center} \end{figure} \begin{figure}[h] \begin{center} \includegraphics[width=1\linewidth]{fig7.png} \caption{CIFAR - Accuracy of the global model when under a pretence attack with the defense starting at different $\Delta$ periods.} \label{fig:CIFAR_2} \end{center} \end{figure} \begin{figure}[h] \begin{center} \includegraphics[width=1\linewidth]{fig8.png} \caption{CIFAR - Accuracy of the global model when under a randomized attack with the defense starting at different $\Delta$ periods.} \label{fig:CIFAR_3} \end{center} \end{figure} During a randomized attack on CIFAR where the accuracy remained the same, this is still an important result in terms of improvement of system efficiency as related to time cost and computation overheads. The conclusion from the results obtained from the evaluation of the two datasets is that anomaly detection in federated learning can be delayed while the same or even better performance in terms of accuracy can be achieved. On the other hand, in terms of system performance, the monitoring period will undoubtedly decrease computation overhead and time cost. To understand the reason behind the variation in the accuracy of the global model when the defense starts at different periods of time, we must look into the precision and recall scores of the detection mechanism during the first iterations of training. This will also enable us to validate the need of a monitoring period when defending the FL process against attacks. In Figures~\ref{fig:MNIST_precisionrecall1} and \ref{fig:MNIST_precisionrecall2}, we show the precision and recall in terms of percentage and the values are reported for the defense against the static attack on MNIST applied at different $\Delta$ periods of time. We do not show the figures of the similar analysis for the pretence and randomized attacks because they show a similar behavior. When $\Delta$ = 0, we notice from Figure~\ref{fig:MNIST_precisionrecall1} that the value of precision is almost always higher than recall at every iteration. However, when $\Delta$ = 10, which corresponded in Figure~\ref{fig:MNIST_1} to the monitoring period enabling the best global model accuracy when protecting against a static attack, the values of recall are higher than precision at almost every iteration. When $\Delta$ = 40, we notice from Figure~\ref{fig:MNIST_precisionrecall2} that the value of precision is almost always higher than recall at every iteration. Thus, this does not represent a good indication that this must be the appropriate value of $\Delta$. This validates the fact that in the context of FL, a detection technique that ensures high recall but reduces precision is better than one that increases precision but reduces recall. The appropriate monitoring period can be found by looking at the values of recall and precision for a subset of \textit{workers} of the FL process. Afterwards, this period can be implemented on the the rest of the nodes of the network in order to defend against attacks in an efficient way. Similarly, Figure~\ref{fig:CIFAR_precisionrecall} shows the precision and recall in terms of percentage for the defense against the static attack on CIFAR applied at different $\Delta$ periods of time. The monitoring period that ensures high recall but reduces precision during training is considered the best. From the Figure, $\Delta$=10 can be distinguished by the high values of recall compared to the precision throughout the training interval considered. Precisely, estimating the appropriate value of $\Delta$ must consider both precision and recall scores. We present in Figure~\ref{fig:MNIST_F_beta}, the $F_2$ values at every iteration as a measure of the performance of the defense for different $\Delta$ periods. The $F_2$ measure weights recall higher than precision. Similarly, Figure~\ref{fig:CIFAR_F_beta} presents the $F_2$ values for the CIFAR use case and they measure the effectiveness of detection with respect to a \textit{chief} who attaches more importance to recall than precision. In both use cases, low values of F-score are associated to $\Delta$ =40. This monitoring period is thus not the most appropriate for the models under study. In CIFAR, the highest values of F-score are associated to a monitoring period of $\Delta$ =10. In fact, this monitoring period is the most efficient for the CIFAR FL process. For MNIST, F-score values of $\Delta$ =10 are very close to the values attained when $\Delta$ =0, so even if the defense starts at a later time, the scores are not impacted a lot by this delay in protection against attacks. \begin{figure*}[!ht] \begin{center} \includegraphics[width=0.73\linewidth]{fig9.png} \caption{MNIST - Precision and recall of the defense applied at different $\Delta$ periods of time against a static attack for the first 40 iterations.} \label{fig:MNIST_precisionrecall1} \end{center} \end{figure*} \begin{figure*}[!h] \begin{center} \includegraphics[width=0.73\linewidth]{fig10.png} \caption{MNIST - Precision and recall of the defense applied at different $\Delta$ periods of time against a static attack between iterations 40-80.} \label{fig:MNIST_precisionrecall2} \end{center} \end{figure*} \begin{figure*}[!h] \begin{center} \includegraphics[width=0.73\linewidth]{fig11.png} \caption{CIFAR - Precision and recall of the defense applied at different $\Delta$ periods of time against a static attack.} \label{fig:CIFAR_precisionrecall} \end{center} \end{figure*} \begin{figure}[!h] \begin{center} \includegraphics[width=1\linewidth]{F2_mnist.pdf} \caption{MNIST - $F_2$ values as a measure of the performance of the detection for different $\Delta$ periods.} \label{fig:MNIST_F_beta} \end{center} \end{figure} \begin{figure}[!h] \begin{center} \includegraphics[width=1\linewidth]{F2_cifar.pdf} \caption{CIFAR - $F_2$ values as a measure of the performance of the detection for different $\Delta$ periods.} \label{fig:CIFAR_F_beta} \end{center} \end{figure} Finally, there is an inverse relationship between the monitoring period and the accuracy, where it is possible to increase one at the cost of reducing the other. However, as the results imply at $\Delta$=10, compared to when $\Delta$=0 and $\Delta$=40, adapting the monitoring period will bring time cost and consequently computation overheads down for the defense for both the MNIST and CIFAR use cases. \newpage \section{Conclusion} \label{sec:conclusion} In this paper, we studied how to optimize the timing of deploying the defense mechanisms against poisoning attacks in federated learning. In fact, we proposed that a monitoring period must be accounted for particularly in defense approaches that are based on behavioral pattern analysis to eliminate potential malicious \textit{workers} from the FL process. We showed it by conducting a comparative analysis of training traces of benign and malicious \textit{workers} during the early stages of training. We evaluated the monitoring period required in order to improve system efficiency in terms of the time cost and computation overheads in the beginning of training for different benchmark systems for text and image classification (MNIST, CIFAR-10). Empirical results suggest in most cases, the correction lowers the false positives and false negatives and helps the distributed learning system achieve better performance in the early stage of training. To fine-tune the appropriate monitoring period throughout the distributed learning process, game theoretic research holds promise in addressing this challenge. \bibliographystyle{elsarticle-num} \bibliographystyle{IEEEtran}
{'timestamp': '2021-11-30T02:25:31', 'yymm': '2109', 'arxiv_id': '2109.05385', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05385'}
arxiv
\section{Introduction} While humans can cope with new situations quite easily, even state-of-the-art algorithms struggle with new situations that they haven't been trained on. Unfortunately, when it comes to autonomous vehicles the results may be devastating. One example for an uncommon, yet important scenario for autonomous vehicles is the problem of a single track road. In this problem two vehicles in opposite directions must cross a narrow road, which is not wide enough to allow both vehicles to pass at the same time. Therefore, one vehicle must deviate from the road and let the other vehicle cross. However, if both vehicles deviate to the margins, they might both return to the road, and may either end-up deviating to the margins again or even colliding with each-other. Despite only a small portion of the roads being single track roads, autonomous vehicles must be able to function properly in these types of roads. Furthermore, some more common situations resemble the single track road problem, for example, if cars park where they shouldn't and block one of the lanes or if one lane is blocked for any other reason (e.g., a falling tree), the traffic in both ways must operate with a single lane. In this paper we model the single track road problem as a sequential two player game on a two row grid (see Figure \ref{fig:game}). The upper row represents a road that allows both players to advance. However, the lower row can only be used for allowing the other player to pass, as the players cannot advance when placed in the lower row. We find several equilibria of the game, which should determine how a perfectly rational agent should behave in such a game. However, people tend to deviate from what is considered rational behavior, since they are influenced by different effects including anchoring, inconsistency of utility and a lack of understanding of other agent's behavior~\cite{tversky81,ArielyAnchor,camerer03}. Indeed, as we later show, while some people tend to follow the game theoretic solution, many others do not follow it, and behave unexpectedly. Due to non-perfectly rational behavior of humans, algorithmic approaches that assume rational behavior tend to perform poorly with humans~\cite{bitan2013social,azaria2015strategic,nay2016predicting}. \begin{figure}[t] \label{fig:game} \centering \includegraphics[width=4in]{board.png} \caption{The initial state of the single road game board. The red circle is controlled by the human player and the blue circle is controlled by the autonomous agent. Both players must reach the opposite side of the board without colliding. The players may travel freely on the upper row, but they cannot advance when located on the lower row.} \end{figure} Therefore, a common approach for developing an agent that can proficiently interact with humans is composed of several stages \cite{azaria2011giving,nguyen2013analyzing,rosenfeld2015adaptive}. The first stage includes the collection of a data-set of humans interacting in the environment. Next, based on the collected data-set a human behavior model is developed, usually by applying machine-learning techniques. Finally, the human model is used by the agent to determine the actions that are the most beneficial for it. In this paper we attempt to follow this common practice for the single track road game. Therefore, we collect human data in this game and use it to compose a human model. Then, we model the agent's problem as a reinforcement learning environment by an MDP with the human model being a part of the environment. Finally, we use value iteration, a dynamic programming based method, to find the supposedly optimal action for the agent. We note that the solution provided by value iteration is guaranteed to be optimal under the assumption that the MDP models the environment perfectly, which includes the human model. However, composing a human behavior model based on a relatively small data-set may be inaccurate, as people are many times unpredictable and different humans tend to behave very differently from one another, despite a game being relatively simple \cite{shvartzon2016personalized,azaria2016autonomous}. Therefore, we introduce a novel method for solving an MDP that is based on a non-perfect human behavior model. Namely, instead of solving the MDP with an attempt to maximize the agent's outcome, we propose to maximize a linear combination of the agent's outcome and the human's outcome. We expect that optimizing toward a linear combination will be beneficial for the agent, since the humans are likely to try and optimize their own utility function, so they are likely to deviate from the human model in a way that will indeed maximize their utility function. By optimizing toward a linear combination, the agent acts as if it already accounts for these deviations and is therefore more likely to adapt to them. We provide a formula for determining the proposed linear combination, which is based on the similarity of the agents' utility functions. We introduce our Socially Aware Reinforcement Learning agent (SARL\xspace), an agent that attempts to maximize the linear combination of the two utility functions, using our proposed formula. We show that SARL\xspace significantly outperforms all other baselines in the single track road game when interacting with humans, in terms of the agent's final outcome. Somewhat less surprisingly, humans interacting with SARL\xspace also achieve the highest outcome. Therefore, SARL\xspace not only perform better with respect to its own outcome, but also with respect to social welfare. To summarize, the contributions of this paper are three-fold: \begin{enumerate} \item We present the single track road problem, model it as a sequential game, and present the equilibria of the game. We show that people do not follow strategies that are in equilibrium. \item We model the problem as an MDP in which the human's actions are modeled as a part of the environment. The model uses data from humans interacting with simple agents to determine the probability of the human taking each action at a given state. \item We present SARL\xspace, a socially aware reinforcement learner, that uses a linear combination of the rewards of both agents. We provide a formula for finding the parameter to be used in this linear combination. Finally, we show that our method significantly outperforms all other baselines. \end{enumerate} \section{Related Work} Trajectory prediction of surrounding vehicles and pedestrians is very important for the development of autonomous vehicles, as such knowledge can prevent accidents. Indeed, trajectory prediction is challenging due to the unexpected nature of human behavior. Therefore, many works attempt to find a sufficient solution to overcome this challenge \cite{leon2021review}. According to Houenou et al. \cite{AP} trajectory prediction can be based on a deterministic method that selects the current maneuver from a predefined set using kinematic measurements and road geometry detection. The authors state that their model cannot be applied to very low speed scenarios and therefore is not applicable to our scenario. Deo and Trivedi \cite{DT} estimate a probability distribution of future positions of a vehicle conditioned on its track history and the track histories of vehicles around it, at a certain time. Using this information, they select one of six possible maneuvers that have been defined. They use the publicly available NGSIM US-101 and I-80 highway data-sets for their experiments. Their model relies purely on vehicle tracks to infer maneuver classes and ignores the lanes and the map. Ding at al. \cite{DC} use a {\it recurrent neural network} for composing an observation encoding. Based on this encoding, they propose a {\it Vehicle Behavior Interaction Network} (VBIN) to capture the social effect of another agent on the prediction target, based on their maneuver features and relative dynamics (e.g., relative positions and velocities). VBIN is an end-to-end trainable framework and is suitable for dynamic driving scenarios where the dynamics of the agents affect their importance in social interactions. They use data collected from highways US-101 and I-80 as used in other work \cite{DT}; since it deals only with highway roads with a large number of agents, it is not applicable for our setting. Kim et al. \cite{KM} propose a deep learning approach for trajectory prediction based on a {\it Long Short Term Memory} (LSTM). Their model is used to analyze the temporal behavior and predict the future coordinates of the surrounding vehicles. Based on the coordinates and velocities of the surrounding vehicles, the vehicle’s future location is produced after a certain short amount of time. However, the experiments were conducted using data collected from highway driving, which is again not suitable to our case. Chandra at al. \cite{CG} present an approach for trajectory prediction in urban traffic scenarios using a two-stream graph-LSTM network. The first stream predicts the trajectories, while the second stream predicts the behavior (i.e. overspeeding, underspeeding, or neutral) of road-agents. It is based on the vehicle coordinates and a weighted dynamic geometric graph (DGG) that represents the relative proximity among road agents. They also present a rule-based behavior prediction algorithm to forecast whether a road agent is overspeeding (aggressive), underspeeding (conservative), or neutral, based on the traffic behavior classification from the psychology literature. They evaluate their approach on the Argoverse, Lyft, Apolloscape, and NGSIM datasets and highlight the benefits over prior trajectory prediction methods. Elhenawy at al. \cite{EM} introduce a real time game-theory-based algorithm that is inspired by the {\it chicken-game} for controlling autonomous vehicle movements at uncontrolled intersections. They assume that all vehicles communicate to a central management center in the intersection to report their speed, location and direction. The intersection management center uses the information from all vehicles approaching the intersection and decides which action each vehicle will take. They further assume that vehicles obey the {\it Nash-equilibrium} solution of the game and will take the action received from the management center. Unfortunately, these assumptions are very strong and cannot be applied to our setting. Camara at al. \cite{CF} suggest a more realistic game-theory model based on the {\it sequential chicken-game}. The model assumes both agents share the same parameters $U_{crash}$ and $U_{time}$, both know this is the case, and both play optimally from their state. It assumes that no lateral motion is permitted, and that there is no communication between the agents other than seeing each other’s positions. The sequential chicken-game can be viewed as a sequence of one-shot (sub-)games, which can be solved similarly. The sub-game at time $t$ can be written as a standard game theory matrix, which can be solved using recursion, game theory, and equilibrium selection to give values and optimal strategies at every state. While they handle the case of a junction by finding a Nash equilibrium and assuming that humans obey it, we deal with the single track road and give not only a game-theory analysis but also provide a novel Reinforcement Learning solution that does not require assumptions about humans and Nash equilibria. There have been several previous works attempting to model human behavior in normal form games \cite{wright2010beyond,wright2014level}. Wright and Leyton-Brown \cite{wright2010beyond} collected the results of multiple experiments from normal form games studied in the literature, and showed how the human action distribution can be modeled with high accuracy. However, our problem is clearly more complex and cannot be modeled as a simple normal form game. Azaria el al. \cite{azaria2012strategic,azaria2016strategic} introduce SAP, a social agent for advice provision. They show that humans tend to ignore advice provided by a selfish agent. Therefore, they suggest using some linear combination of the user's and the agent's preferences. The exact ratio is determined by simulating human behavior and selecting the ratio that achieve the highest performance for the agent in simulation. Therefore, both SAP and our work attempt to maximize agent performance and consider a linear combination of both the user and the agent, however, the environment and settings are completely different, as SAP is an agent for advice provision, and we use a grid environment. In addition, the purpose of the linear combination used by SAP is to address the issue of human trust, while in our work, it is used to mitigate the uncertainty we have in our human model. Furthermore, we propose a formula for obtaining our proposed ratio, rather than running a simulation for obtaining that value. \section{The Single Track Road Game} We now provide a formal definition for the single track road game, which is the main focus of this paper. Two agents $A$ and $B$ are placed on a $2 \times n$ grid at both ends on the upper row, where agent $A$ is positioned at the upper right corner, with coordinates $(1,n)$, and agent $B$ is positioned at the upper left corner, with coordinates $(1,1)$, each agent's goal is to maximize $u(W)$, their future outcome where $W$ refers to the agent. Each agent's goal is to reach the other side in a minimal number of steps, and without colliding with the other agent. The set of actions available for each agent depends on its location. In the upper row each agent can perform the following actions: \begin{itemize} \item {\it Advance}: move toward the other side. \item {\it Stay}: remain in current position. \item {\it Down}, move to the bottom row. \end{itemize} In the bottom row each agent can perform one of the following actions: \begin{itemize} \item {\it Stay}: remain in current position. \item {\it Up}: return to the top row. \end{itemize} Both agents take actions synchronously, and do not observe the other's action before they take their own action. We define the reward function as follows: \begin{itemize} \item {\it Collusion}: if both agents collide, each agent loses 100 points, and the game ends. \item {\it Arrived at destination}: an agent that arrives at its destination receives a reward of 30 points. The game ends only for the agent that has reached its destination, i.e., the second agent continues to play until it reaches its destination, in which case it will receive a reward of 30 points as well. \item {\it Time loss}: any agent that is still in the game (did not reach its destination or collided with the other agent) loses 1 point each time-step. \end{itemize} \section{Game Theoretical Analysis} \label{sec:gameTheory} In this section we present the game-theory analysis for the single track road problem. Let $x(W)$ be the $x$ coordinate (column) of agent $W$ and let $y(W)$ bet its $y$ coordinate (row). Let $d(A,B) = x(A) - x(B)$. Note that if agent $B$ has passed agent $A$, $d(A,B)$ will be negative. \begin{theorem} \label{thr:eq} For two agents $A,B$ in the $2 \times n$ grid of the single track road game. The following strategies are in a sub-game perfect Nash equilibrium: \begin{itemize} \item Agent $A$ uses the following strategy: \begin{itemize} \item If $y(A)=1$ (it is in the upper row) it takes action {\it Advance}. \item If $y(A)=2$ (it is in the lower row) it takes action {\it Up}. \end{itemize} \item Agent $B$ uses the following strategy: \begin{itemize} \item If $y(B)=1$ (the agent is in the upper row): \begin{itemize} \item If $d(A,B) \geq 3$ or $d(A,B) < 0$, it takes action {\it Advance}. \item If $y(A)=1$ and $d(A,B) = 1$ it takes action {\it Down}. \item If $y(A)=1$ and $d(A,B) = 2$, it may either take action {\it Stay} or {\it Down} (or any mixed strategy of the two). \end{itemize} \item If $y(B)=2$ (the agent is in the lower row): \begin{itemize} \item If $d(A,B) \leq 0$ it takes action {\it Up}. \item If $y(A)=1$ and $d(A,B) = 1$ it takes action {\it Stay}. \item If $y(A)=1$ and $d(A,B) \geq 4$ it takes action {\it Up}. \item If $y(A)=2$ and $d(A,B) \geq 3$ it takes action {\it Up}. \item Otherwise, it may either take action {\it Stay} or {\it Up} (or any mixed strategy of the two). \end{itemize} \end{itemize} \end{itemize} \end{theorem} \begin{proof} The proof handles each of the agents separately and shows that no agent should deviate from its determined strategy under the assumption that the other agent remains with its strategy. This is true also for any sub-game. Given agent $B$'s strategy, agent $A$ should not deviate, as deviation will either cause it longer to reach its destination (resulting in a lower reward), or to collide with agent $B$ (if it decides to take action {\it Down} when agent $B$ is directly below it), resulting in a much lower reward. Similarly, given agent $A$'s strategy, agent $B$ should not deviate, due to the following: \begin{itemize} \item If $y(B) = 1$ (the agent is in the upper row): \begin{itemize} \item If $y(A) = 1$ and $d(A,B) = 1$, under the assumption that $A$ would {\it Advance}, taking an action other than {\it Down} would lead to a collision, which will result in a very low reward. \item If $d(A,B) \geq 3$ or $d(A,B) < 0$, so either agent $A$ is very far or it has already passed agent $B$. Therefore, there is no risk of collision, and deviating and taking action {\it Down} or {\it Stay} will result in arriving later at the destination, which will result at a lower reward. \item If $y(A) = 1$ and $d(A,B) = 2$, deviating and taking action {\it Advance} would result in a collision. Therefore, agent $B$ should take either action {\it Down} or {\it Stay} (or any mixed strategy of the two). \end{itemize} \item If $y(B) = 2$ (the agent is in the lower row): \begin{itemize} \item If $d(A,B) < 0$, there is no risk of a collision since agent $A$ already passed agent $B$. Therefore, deviating and playing {\it Stay} delays $B$'s arrival at the destination. \item If $y(A) = 1$ and $d(A,B) = 1$, playing action {\it Up} (instead of {\it Stay}) will lead to a collision, resulting in a lower reward. \item If $y(A) = 1$ and $d(A,B) \geq 4$, since there is no risk of collision, taking action {\it Up} will yield the greatest reward, and any other action will cause it to reach the destination later. \item If $y(A) = 2$ and $d(A,B) \geq 3$, similarly, any action other than {\it Up} will cause a delay in arriving at the destination. \item Otherwise, agent $B$ can choose whether to take action {\it Stay} or {\it Up} because there is no risk of a collision and it will not affect the arrival time. We note that if it takes action {\it Up} and agent $A$ follows its strategy, agent $B$'s next action will be {\it Down}. \end{itemize} \end{itemize} \end{proof} Clearly, due to the symmetry of the game, agents $A$ and $B$ may switch policies and the resulting set of strategies will be in equilibrium. However, since both sets of policies and equilibria are symmetrical, we cannot predetermine which equilibrium to select. Furthermore, as we will show in the experiments, human agents, in most cases, do not follow any of the above strategies (see section \ref{sec:R}). \section{Socially Aware Reinforcement Learning (SARL\xspace)} To solve the single track road problem, we introduce the Socially Aware Reinforcement Learning agent (SARL\xspace). For SARL\xspace, we model the problem as an MDP, in which the human is a part of the environment. A state is composed of the current location of both agents, as well as the location of both agents in the previous timestep, which serves as a model of the velocity. In order to model human behavior, we use a data-set of humans interacting in the single track road problem, and for each state we compute the fraction of humans that were in that state and took each of the possible actions. We apply the Laplace rule of succession \cite{zabell1989rule}. Given state $s$, let $$A_s = \{a \in A: a \text{permitted from} s\}$$ where $A$ is the set of all actions. For $a \in A_s$ let $|a_s|$ be the number of times in the dataset that action $a$ was performed from state $s$ and let $n_s = \sum_{a \in A_s} |a_s|$ be the total number of actions performed from $s$. We assume that the probability that the human will take action $a$ at state $s$ is $$\mathds{P}(a | s) = \frac{|a| + 1}{n_s + |A_s|}.$$ We use value iteration, an MDP planning algorithm, which is based on dynamic programming, for solving the MDP \cite{sutton2018reinforcement}. The value iteration guarantees to find the optimal policy, under the assumption that the MDP model, which includes the human model, is accurate. Clearly, policy iteration would have yield the same policy, and model free reinforcement learning methods, such as q-learning (using a simulation), should also converge to the same policy, if allowed enough running time. However, since our human model is inaccurate, instead of using the common approach for solving the MDP by trying to maximize the agent's outcome directly, SARL\xspace uses a linear combination of its own outcome and the human's outcome. It is important to note that SARL\xspace is still selfish, it considers the human's outcome only because this is its way to maximize its own outcome. It is interesting to note that it has been shown in the field of psychology that people who consider other people's goals and show empathy, feel better with themselves and are more likely to reach their own goals \cite{carey2021deconstructing}. However, since our human model is based on a limited data-set size, we propose to incorporate our knowledge related to the human reward function into the optimization problem. Yet, instead of trying to use the human reward function as a part of the human model or the transition function of the MDP, we propose to add it to the objective function of the agent. To that end, we define the parameter $\beta$, a value between $0$ and $1$, that quantifies the degree to which the agent considers its own outcome and the human's outcome. Namely, the agent, $A$, instead of optimizing towards $u(A)$, optimizes towards $\beta u(A) + (1-\beta)u(B)$. We note that when $\beta = 1$ the agent optimizes towards its own outcome. A $\beta$ value of $0.5$ denotes that the agent tries to optimize the social outcome (i.e., $0.5 u(A) + 0.5 u(B)$, which is identical to optimizing simply towards $u(A) + u(B)$), and when $\beta = 0$ the agent only considers the human's utility function. In general, for a two player game, in which one of the players is human, and given a data-set we propose a formula for computing the $\beta$ value as follows. Let the vectors $R_A$ and $R_B$, of length $n$, denote the final outcomes in the data-set for players A and B, respectively for each episode. The following formula provides the proposed $\beta$ value to be used by SARL\xspace: $$\beta = \frac{1 - correl(R_A,R_B)}{2}.$$ $correl(R_A,R_B)$ is the correlation between $R_A$ and $R_B$, which is computed by: $$correl(X, Y) = \frac{\sum \limits_{x_i\in X, y_i\in Y} (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum \limits_{x_i \in X}(x_i - \bar{x})^2\sum \limits_{y_i \in Y}(y_i - \bar{y})^2}}.$$ For example, in a zero-sum game, the correlation between the rewards of both players is $-1$; therefore, the agent will ignore the human's outcome and only maximize its own. On the other hand, when the rewards of both players are independent, the correlation will be $0$. Therefore, $\beta$ will be $0.5$, that is, the agent will consider both rewards equally. In a game that is more cooperative the human's utility function is not as different from the agent's, and therefore the value of $\beta$ is lower. \section{Problem Specification} \label{sec:ED} We use a $2 \times 6$ grid to model the single-road game problem, and the reward functions described in Section \ref{sec:gameTheory} (see Figure \ref{fig:game}). We set the discount factor, $\gamma$, to $0.999$, so that the overall return is very close to the sum of the rewards. We define a state as a pair $(i,j)$ in which $i$ is a position of the autonomous agent, and $j$ is a position of the human agent. We refer to this state representation as a state \emph{without} velocity. We also use a more complex representation of a state by considering also the previous locations of both players; this representation is referred to as a state with velocity. That is, a state is a tuple of two pairs $((i,j),(l,k))$, where the first coordinate of each pair corresponds to the position on the board of the autonomous agent, and the second coordinate corresponds to the position of a human agent. The first pair, $(i,j)$, is the current state of the two agents, and the second pair, $(l,k)$, is their previous state. Accounting for both players' velocity allows the composition of a more accurate human model, which is a part of the transition function. Since the game ends only when both players reach their destination (or collide with each other), in order to model the problem as an MDP with an objective function that also considers the human's reward function we had to slightly modify the reward function. This is because a standard MDP only considers the agent's point of view while the human is considered a part of the environment. Given $\beta$ and a state $s$, let $remainingSteps(s,X)$ be the number of remaining steps from state $s$ for agent $X$, where $X$ is either the autonomous agent or human player. \begin{itemize} \item If the two agents collide, the reward is $$\beta \cdot (-100) + (1-\beta) \cdot (-100).$$ \item If the autonomous agent has not yet reached the destination but the human agent has, the reward is $$\beta \cdot (30 - remainingSteps(s, autonomous)) + (1-\beta) \cdot 30.$$ \item If the autonomous agent has reached the destination and the human agent has not, the reward is $$\beta \cdot 30 + (1-\beta) \cdot (30 - remainingSteps(s, human)).$$ \item For any other step, the reward is $$\beta \cdot (-1) + (1-\beta) \cdot (-1).$$ \end{itemize} \section{Experimental Design} In order to compose the data-set and evaluate SARL\xspace's performance, we recruited $470$ participants from Mechanical Turk \cite{paolacci2010running} to play the single road game. The participants first read the game instructions and were then required to answer three short and simple questions, to ensure that they had read and understood the instructions. The participants then played the game only once. Upon completion (either by reaching the other side, or if colliding with the other agent), the participants provided demographic information including whether they have a valid driving license, an expired driving license or no driving license. In addition, the participants were asked to state how much they agreed with each of the following five statements: \begin{enumerate} \item The agent played aggressively. \item The agent played generously. \item The agent played wisely. \item The agent was predictable. \item I felt the agent was a computer. \end{enumerate} We used a seven point Likert-like scale \cite{joshi2015likert} for these statements, ranging from strongly disagree ($1$) to strongly agree ($7$). $446$ participants completed the game and answered the survey. Their demographic information can be found in Table \ref{tbl:participants}. \begin{table} \centering \caption{Participants details} \begin{tabular}{|c|c|c|} \hline \multirow{2}{*}{\textbf{Gender}} & Male & 267 \\ & Female & 179 \\ \hline \multirow{4}{*}{\textbf{Education level}} & High school & 128\\ & BA & 265 \\ & M.Sc & 45 \\ & Ph.D & 7 \\ & None & 1 \\ \hline \multirow{2}{*}{\textbf{Driving License}} & Valid & 411 \\ & Expired & 13 \\ & None & 22 \\ \hline \textbf{Average age} & & 38.6 \\ \hline \end{tabular} \label{tbl:participants} \end{table} We used the following 4 different baseline agents for the data gathering phase. \begin{enumerate} \item {\it Careful:} an agent that adheres to the strategy of agent $B$ in Theorem \ref{thr:eq}. That is, it tries to move left, but tries to avoid colliding with the other agent as well, so if moving left may risk colliding with the other agent it stays in place. If staying in place also risks colliding with the other agent, it moves down. \item {\it Aggressive:} an agent that adheres to the strategy of agent $A$ in Theorem \ref{thr:eq}. That is, the agent always moves left. \item {\it Semi-aggressive:} an agent that moves left unless the other agent is already there, in which case it stays in place until the other agent moves out of its way. \item {\it Random:} an agent that moves randomly. \end{enumerate} \section{Results} \label{sec:R} In this section we present a comparison of all agents mentioned above and show that SARL\xspace significantly outperforms all other agents. In addition, we consider the following agents: \begin{enumerate} \item {\it Non-Velocity VI}: runs a value iteration on the MDP without velocity using the appropriate human model. \item {\it Velocity VI}: runs a value iteration on the MDP with velocity using the appropriate human model. \item {\it Equal Social VI}: uses value iteration to maximize the sum of the agent's and the human's utilities (i.e., used a $\beta$ value of $0.5$). \end{enumerate} The agent's score is calculated by averaging all its scores in each game it plays. We begin by comparing the performance of each of the agents. Figure \ref{fig:AS} presents a comparison between the performance of all baseline agents, Velocity and Non-Velocity Value Iteration ($\beta = 1$), Equal Social Value Iteration ($\beta = 0.5$) and SARL\xspace ($\beta = 0.13$). \begin{figure}[!h] \centering \includegraphics[width=4in]{agents_scores.pdf} \caption{A comparison between the performance of all baseline agents, Velocity and Non-Velocity Value Iteration ($\beta = 1$), Equal Social Value Iteration ($\beta = 0.5$) and SARL\xspace ($\beta = 0.13$).} \label{fig:AS} \end{figure} As depicted by Figure \ref{fig:AS}, SARL\xspace significantly outperforms all other agents ($p < 0.01$) in terms of the agent's performance. Furthermore, it is the only agent that achieved a positive average reward. We also note that the agent that uses the state representation with velocity obtained slightly better results than the agent that used the non-velocity state representation, though these differences are not statistically significant. We now turn to evaluate the human's score when playing with each of the agents. Although the agents are designed to be selfish, clearly, it is more beneficial if also the human player would result with a better score. Table \ref{tbl:scores} presents the performance of each of the agents along with the performance of the humans playing against them. \begin{table}[!h] \centering \caption{A comparison between the performance of each of the agents along with the human player who played against each of them.} \begin{tabular}{| l | p{1.6cm} | p{1.7cm} | p{1.7cm}|} \hline \textbf{} & \textbf{Avg. agent's score} & \textbf{Avg. human's score} & \textbf{Avg. social welfare} \\ \hline \textbf{Careful} & -2.29 & -0.86 & -3.15\\ \hline \textbf{Aggressive} & -16.27 & -18.40 & -34.67\\ \hline \textbf{Semi-aggressive} & -60.97 & -62.11 & -123.08\\ \hline \textbf{Random} & -59.40 & -57.62 & -117.02 \\ \hline \textbf{Non-Velocity VI} & -6.34 & -9.03 & -15.37\\ \hline \textbf{Velocity VI} & -5.33 & -6.03 & -11.36\\ \hline \textbf{Eq. Social VI} & -2.35 & -4.09 & -6.44\\ \hline \textbf{SARL\xspace} & \textbf{15.87} & \textbf{17.12} & \textbf{32.99} \\ \hline \end{tabular} \label{tbl:scores} \end{table} As shown in Table \ref{tbl:scores}, SARL\xspace also significantly outperforms all other agents ($p < 0.01$) in terms of the human's performance. In addition, we tested the performance of a velocity value iteration agent with the $\beta$ value set to $0$. That is, an agent that only considers the human reward. Interestingly, such an agent simply moves down and remains there forever. This is because this way it does not disturb the human. Unfortunately, such an agent achieves a final outcome of $-\infty$ (or $-\frac{1}{1-\gamma}$) because it can never reach its destination, since the when the human's reaches her goal, the agent is directly beneath her. Next, we evaluate the prediction of the {\it policy evaluation} algorithm, using both forms of state representations (i.e., with and without velocity). Table \ref{tbl:predictions} presents the prediction compared with the actual score of every agent. As can be seen in the table, the prediction that uses a state representation with velocity outperforms the prediction that uses a state representation without velocity. However, both predictions performed badly, and imply that our human model is not accurate, as an accurate human model would have resulted with an accurate prediction. This demonstrates that it is not enough to rely on the dataset, and strengthens the need for the socially aware approach, which also considers the human's rewards. \begin{table}[!h] \centering \caption{The accuracy of the prediction of a policy evaluation algorithm using a model with velocity and a model without velocity.} \begin{tabular}{| l | p{1.3cm} | p{1.7cm} | p{1.7cm} | } \hline \textbf{} & \textbf{True score} & \textbf{Prediction with velocity (error)} & \textbf{Prediction without velocity (error)}\\ \hline \textbf{Careful} & -2.29 & -14.41 (12.12) & -4.86 (2.57) \\ \hline \textbf{Aggressive} & -16.27 & -6.21 (10.6) & 1.14 (17.41) \\ \hline \textbf{Semi-aggressive} & -60.97 & -56.47 (4.5) & -47.81 (13.16) \\ \hline \textbf{Non-Velocity VI} & -6.34 & 0.51 (6.85) & \textbf{13.63} (19.97)\\ \hline \textbf{Velocity VI} & -5.33 & \textbf{14.47} (20.02) & N/A \\ \hline \textbf{Eq.Social VI} & -2.35 & 12.34 (14.69) & N/A\\ \hline \textbf{SARL\xspace} & \textbf{15.87} & 7.55 (8.32) & N/A \\ \hline \end{tabular} \label{tbl:predictions} \end{table} We now turn to analyze the survey results for each agent (see Table \ref{tbl:survey_results}). Each value in the table is the average of all the scores of the measured values: Aggressively, Computer, Generously, Wisely and Predictable. \begin{table*} \centering \caption{Survey results of all agents} \begin{tabular}{| p{2.6cm} | p{1.4cm} | p{1.4cm} | p{1.4cm} | p{1.4cm} | p{1.4cm} | } \hline \textbf{} & \textbf{Aggressively} & \textbf{Computer} & \textbf{Generously} & \textbf{Wisely} & \textbf{Predictable} \\ \hline \textbf{Careful} & 3.94 & 5.70 & 4.23 & 4.92 & 4.28 \\ \hline \textbf{Aggressive} & 5.04 & 5.83 & 3.28 & 4.59 & 4.97\\ \hline \textbf{Semi-aggressive} & 4.57 & 5.73 & 3.21 & 4.33 & 4.52\\ \hline \textbf{Random} & 3.51 & 5.64 & 4.01 & 3.72 & 3.57\\ \hline \textbf{Non-Velocity VI} & 4.88 & 6.20 & 3.27 & 4.65 & 4.82\\ \hline \textbf{Velocity VI} & 4.82 & 6.01 & 4.20 & 4.72 & 4.76\\ \hline \textbf{Eq. Social VI} & 4.78 & 5.60 & 3.69 & 4.92 & \textbf{4.98}\\ \hline \textbf{SARL\xspace} & \textbf{3.30} & \textbf{5.58} & \textbf{5.14} & \textbf{5.01} & 4.00 \\ \hline \end{tabular} \label{tbl:survey_results} \end{table*} Note that the lower the `Aggressively' and `Computer' parameters, the better the performance. On the other hand, the higher the `Generously', `Wisely' and `Predictable' parameters, the better the performance. As can be seen in Table \ref{tbl:survey_results}, SARL\xspace obtained the best results compared to the other agents among all parameters except its score on Predictable. These results entail that SARL\xspace demonstrates a clear improvement over all the other agents. Next, we compare the performance of the humans according to their demographic information. We did not find any significant differences between male and female players, with female participants obtaining an average of $-25.98$ and male participants an average of $-25.66$. Similarly, education level did not seem to have any impact on the performance of the participants. Most interestingly, participants with a driving license that has expired obtained a much lower average score ($-60.15$) than those with a valid driving license ($-24.77$) and those without a driving license. Although these differences appear to be statistically significant using a one-tail t-test ($p<0.05$), this result requires deeper investigation, as the number of participants whose driving license has expired is only $13$. Furthermore, an ANOVA test \cite{rogan1977anova} does not show that these differences are statistically significant. Finally, we present the number of human participants who followed a strategy that could be in a Nash equilibrium. As can seen in Figure \ref{fig:NE}, only a small portion of the participants followed one of the two strategies that could be in equilibrium: the `Careful' strategy or the `Aggressive' strategy. Clearly, most of the participants did not follow a strategy that could be in a Nash equilibrium. \begin{figure}[!h] \centering \includegraphics[width=4in]{bar_NE.pdf} \caption{The number and percentage of human participants who followed a strategy that could be in a Nash equilibrium as well as the number and percentage of them who did not follow any strategy in equilibrium. The error bars present the 95\% confidence interval.} \label{fig:NE} \end{figure} \section{Conclusions and Future Work} In this paper we present the single track road problem. In this problem two agents face each-other at opposite positions of a road that can only have one agent pass at a time. We focused on the scenario in which one agent is human, while the other is an autonomous agent. We ran experiments with human subjects in a simple grid domain, which simulates the single track road problem. We showed that when data is limited, building an accurate human model is very challenging, and that a reinforcement learning agent, which was based on this data, did not perform well in practice. However, we showed that a social agent, i.e., an agent that tried to maximize a linear combination of the human's utility and its own utility, achieved a high score, and significantly outperformed other baselines, including an agent that tried to maximize only its own utility. We provided a formula to compute what we believe to be a good choice for the $\beta$ parameter, i.e., the ratio between the human's and the agent's utility when attempting to maximize the agent's utility. In addition, we showed that the human achieved highest utility when interacting with SARL\xspace, a value that was significantly higher than when interacting with any other baseline agent. Furthermore, SARL\xspace was perceived by humans as less aggressive, more generous and wiser than all other baselines. In future work we intend to show that SARL\xspace performs well also when considering other, possibly very different, settings. One option for such a setting is a setting with a continuous state space as well as a continuous action space. We further intend to utilise the idea of using a social agent approach, learned in the grid game environment, and to adapt SARL\xspace to a simulated autonomous vehicle environment with human drivers controlling simulated vehicles. Once we perform well in the simulated environment, we expect to run SARL\xspace in a real single-track-road scenario, with an autonomous vehicle and human drivers. We hope to show that SARL\xspace will perform well in the real-word environment, and that a social agent approach will be useful in practice. Another direction for future work is to focus on situations in which the human reward function is not available apriori. Such a situation would challenge the use of SARL\xspace, as it uses the human reward function for computing its objective function. One appealing option may be to use inverse reinforcement learning \cite{ng2000algorithms} to first learn the human's reward function, and then, to use this function to compute the optimal policy for SARL\xspace. \section*{Acknowledgment} This research was supported in part by the Ministry of Science, Technology \& Space, Israel. \bibliographystyle{abbrv}
{'timestamp': '2021-11-04T01:03:06', 'yymm': '2109', 'arxiv_id': '2109.05486', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05486'}
arxiv
\section{News Data Collection Methods} \label{sec:news_data_collection} Each news article search was made as a request to the Google search API using the following form \begin{lstlisting} https://www.google.com/search?q=q&num=30&hl=en \end{lstlisting} The query string \texttt{q} was structured in the following way. We included high-precision \textit{officer} and \textit{shooting} keywords, as well as the victim's full name string (which may contain a middle name or initial), with \texttt{\textbf{first\_name}, \textbf{last\_name}}), the first and last space separated word in the full name field respectively. We restricted the search to recent articles within one month following \texttt{\textbf{date}}, or the the day of the shooting event. We also included articles published on \texttt{\textbf{day}-days(1)} to account for possible time zone misalignment or imprecision. \texttt{q = (\textbf{full\_name} OR \textbf{first\_name} OR \textbf{last\_name}) AND (shooting OR shot OR killed OR died OR fight OR gun) AND (police OR officer OR officers OR law OR enforcement OR cop OR cops OR sheriff OR patrol) after: \textbf{date}\texttt{-days(1)} before:\textbf{date} \texttt{+days(30)}} The query returns up to 30 articles, which is equivalent to the first page of Google search results in a browser. We found this sample size of 30 to be large enough to contain a sufficient degree of diversity representing both liberal and conservative articles. A larger sample size could introduce additional noise or false positives in this data collection process. \paragraph{Potential Confounds} \label{appdx:confounds} We are aware of some potential confounds in our data collection that could impact results. Firstly, some sources may not mention victim's name, and these articles will not be represented in our dataset. Articles that omit the victim's name may be particularly pro-police. Second, liberal and conservative sources could differ in their rate of publishing editorials, opinion pieces, or other content that is not strictly news-related. To investigate, one annotator labeled 100 randomly selected articles, 50 from the left and 50 from the right, indicating whether the article was news, opinion, or other. With simple binomial test, however, we just fail to reject the null hypothesis that the proportion of opinion pieces is statistically different between liberal and conservative sources (0.18 lib. vs. 0.06 cons., p=0.0.0648). \section{Frame Extraction} \label{sec:frame_extraction_methods} Here we detail our frame extraction methods which come in two varieties. The first variety includes document-level regular expressions, and the second variety involves conditional string matching algorithms that rely on a partitioning of the all entity-related tokens into \textsc{victim} and \textsc{officer} sets. These extractive methods were ``debugged'' in minor ways after investigating their behavior on a development set, correcting for unexpected false positives and false negatives, but we did not iteratively refine regexes or extraction procedures to maximize precision and recall. Because our methods all extract spans of text, we were also able to verify that these rules were capturing different underlying segments of text. When we compute, for each pair of frames, the proportion of articles in which the difference between respective frame indices was within 25 tokens, we find the highest overlap between \textsl{legal language} and \textsl{criminal record} (25.5\%). However, only 10/91 pairs have >10\% overlap. \subsection{Victim and Officer Partitioning} First, we append to each set any tokens matching a \textit{victim} or \textit{officer} regex respectively. The victim regex matches the known name, race, and gender of the victim in the \adata dataset. For example, for the hispanic female victim named Ronette Morales, we would match tokens in the set \begin{lstlisting} {`daughter', `female', `girl', `hispanic', `immigrant', `latina', `latino', `mexican', `mexican-american', `morales', `mother', `ronette', `sister', `woman'} \end{lstlisting} The officer regex, on the other hand, is given by \begin{lstlisting} police|officer|\blaw\b|\benforcement\b|\bcop(?:s)?\b|sheriff|\bpatrol(?:s)?\b|\bforce(?:s)?\b|\btrooper(?:s)?\b|\bmarshal(?:s)?\b|\bcaptain(?:s)?\b|\blieutenant(?:s)?\b|\bsergeant(?:s)?\b|\bPD\b|\bgestapo\b|\bdeput(?:y|ies)\b|\bmount(?:s)?\b|\btraffic\b|\bconstabular(?:y|ies)\b|\bauthorit(?:y|ies)\b|\bpower(?:s)?\b|\buniform(?:s)?\b|\bunit(?:s)?\b|\bdepartment(?:s)?\b|agenc(?:y|ies)\b|\bbadge(?:s)?\b|\bchazzer(?:s)?\b|\bcobbler(?:s)?\b|\bfuzz\b|\bpig\b|\bk-9\b|\bnarc\b|\bSWAT\b|\bFBI\b|\bcoppa\b|\bfive-o\b|\b5-0\b|\b12\b|\btwelve\b \end{lstlisting} Second, we run the huggingface \texttt{neuralcoref} 4.0 pipeline for coreference resolution, and append all tokens from spans with coreference to the \textsc{victim} or \textsc{officer} set respectively. As an additional plausibility check, we ensure that at least one token in the span is recognized as being \textit{human}. By human, we mean either a proper noun, pronoun, a token with \texttt{spaCy} entity type PERSON, or a token belonging to the set of ``People-Related'' nouns extracted in \citet{lucy2020content} using WordNet hyponym relations. \subsection{Document-Level Regular Expressions} For the following categories, we used regular expression methods, returning the index of the first regex match, which we later sort for our final frame ranking. For categories with a dedicated lexicon, we used an exact string matching regex over these words `\texttt{\textbackslash bword1\textbackslash b|\textbackslash bword2\textbackslash b|...}' to match \texttt{word1}, \texttt{word2}, and all words in that lexicon. If no match was found, that framing category was said to be absent, and the frame rank was set to \texttt{inf}. \subsubsection{Legal language} We compiled a lexicon of legal terms from the Administrative Office of the U.S. Courts \citeyear{uscourts},\footnote{https://www.uscourts.gov/glossary} supplemented with the Law \& Order terms listed in an online word list source.\footnote{http://www.eflnet.com/vocab/wordlists/law\_and\_order} We then hand-filtered any polysemous or otherwise ambiguous words like \textit{answer, assume,} and \textit{bench}, which could lead to false positives in a general setting. Finally, we employed an exact string matching regex over the words in the lexicon. \subsubsection{Mental illness.} To create a lexicon of terms related to mental illness, we used the Empath tool \cite{fast2016empath} to generate the words most similar to the token \texttt{mental\_illness} in an embedding space derived from contemporary New York Times data. We hand-filtered this set to remove generic illnesses and any words not related to mental health. We then employed an exact string matching regex over the words in the lexicon. \subsubsection{Criminal record.} We again used Empath to create a lexicon of terms related to known crimes. We seeded the NYT similarity search with the terms \texttt{abuse}, \texttt{arson}, \texttt{crime}, \texttt{steal}, \texttt{trafficking}, and \texttt{warrant}. We then expanded this set using unambiguous crime names from the Wikipedia Category:Crimes page,\footnote{https://en.wikipedia.org/wiki/Category:Crimes} and finally hand-filtered so that the set included only crimes (e.g. \textit{theft}) or criminal substances (e.g. \textit{cocaine}). We then employed an exact string matching regex over the words in the lexicon. \subsubsection{Fleeing.} To capture reports of a fleeing suspect, we use the following regular expression \texttt{(\textbackslash bflee(:?ing)?\textbackslash b|\textbackslash bfled\textbackslash b|\textbackslash bspe (?:e)?d(?:ing)?(?:off|away|toward| towards)|(took|take(:?n)?)off| desert|(?:get|getting|got|run| running|ran)away|pursu(?:it|ed))}. In this way, we identify fleeing both on foot (e.g. Minnesota 609.487, Subd. 6, \citeyear{mnlaw}) and via motor vehicle (e.g. California 2800.1 VC, \citeyear{calaw}). These are the forms of evasion that are explicitly enumerated by law. We include \texttt{pursu(?:it|ed)} to account for an evasion that is framed from the officer's perspective, which is a pursuit. \subsubsection{Video.} We identify reports of body or dash camera footage using the simple regex \texttt{(body(?: )?cam|dash(?: )?cam)}. We do not use any other related lemmas like \texttt{video}, \texttt{film}, \texttt{record} because we found these to be highly associated with false positives, especially in web text where embedded videos are common. Similarly, we did not match on the word \texttt{camera} alone because of false-positives (e.g. ``family members declined on-camera interviews''). \subsubsection{Age.} According to the Associated Press Style Guide \cite{froke2019associated}, journalists should always report ages numerically. To avoid false positives, we do not match their spelled-out forms. We identify mention of age with an exact string match on the known numerical age of the victim, separated by \texttt{\textbackslash b} word boundaries. \subsubsection{Gender.} Unlike \citet{sap2017connotation}), we are not interested in simply identifying the gender of the victim, but rather, whether there was specific mention of the victim's gender where a non-gendered alternative was available. For example, to avoid gendering a female victim, one could replace titles like \textit{mother} with \textit{parent}, \textit{daughter} with \textit{child}, \textit{sister} with \textit{sibling}, and \textit{female}, \textit{woman} or \textit{girl} with \textit{person} or simply with the name of the victim. Thus if the victim is female, we match \texttt{\textbackslash b(woman|girl|daughter|mother| sister|female)\textbackslash b} and if the victim is male we match \texttt{\textbackslash b(man|boy|son|father| brother|male)\textbackslash b}. We do not match non-binary genders because we do not have ground truth labels for any non-binary targets. \subsubsection{Unarmed} We identify mentions of an unarmed victim with the regex \texttt{unarm(?:ed|ing|s)?}. Manual inspection of news articles reveals that this simple modifier is the standard adjective to describe unarmed victims, so it is sufficient in most cases. Unfortunately, it cannot capture other more subtle context clues (e.g. the victim was \textit{sleeping}, the victim's hands were in the air) or forms of circumlocuation. \subsubsection{Armed} We match individual tokens to the \texttt{\^{} arm(ed|ing|s)?} regex and only return the matching span for tokens that do not have a NOUN Part of Speech tag. This is necessary to disambiguate the verb \textit{arm} from the noun \textit{arm}. We can be confident that when an article mentions \textit{armed}, it is referring to the victim since an armed officer is not newsworthy. On the other hand, we do not match specific weapons because we cannot immediately infer that discussion about a weapon implies the \textit{victim} was armed (it could be an officer's weapon). We resolve this ambiguity when we extract \textsc{attack} frames, ensuring that the \textsc{victim} is the agent who is wielding a weapon object dependency. \subsection{Matching Partitioned Tokens} After partitioning the entity-related tokens into \textsc{victim} and \textsc{officer} sets, we extract the following frames for each document $\mathcal{D}$. In all of the following, we define the set \textsc{object} = \{\textit{dobj}, \textit{iobj}, \textit{obj}, \textit{obl}, \textit{advcl}, \textit{pobj}\} to indicate object dependencies. \subsubsection{Race} We are determined to prune false positives from our \textit{race} frame detection. We only match \textit{race} where the \textit{race} term is given as an attributive or predicative modifier of the known victim. To do so, we scan, for each token $t_k \in \textsc{victim}$, all children of the head of $t_k$ in the dependency parse. This set of children would include predicate adjectives of a copular head verb. If the child matched with any member of the lexicon corresponding to the victim's race, we return the initial index of $t_k$. We also expect to capture adjective modifiers in this way because the \textsc{victim} tokens derive from entity spans that include modifiers. \subsubsection{Attack.} Intuitively, we infer an article has mentioned an attack from the victim if we find the victim has acted in violence or has wielded an object that matches their known weapon or if the officer has been acted upon by a violent vehicular attack. More specifically, for a given document, if we find an \textsc{victim} \textit{nsubj} token in that document having a verbal head in the \textsc{attack} set \{\textit{attack}, \textit{confront}, \textit{fire}, \textit{harm}, \textit{injure}, \textit{lunge}, \textit{shoot}, \textit{stab}, \textit{strike}\} or having a child with \textsc{object} dependency that matches the victim's known weapon type (e.g. \textit{gun}, \textit{knife}, etc.) then we return the token's index as an \textbf{attack} mention. To capture vehicular attacks, we also match tokens whose verbal head is in \{\textit{accelerate}, \textit{advance}, \textit{drive}\} and whose object is in the \textsc{officer} set. This process is detailed in Algorithm~\ref{alg:mentions_attack}, with a helper function in Algorithm~\ref{alg:verbs_with_obj}. \begin{algorithm} \SetAlgoLined \KwIn{Dependency parsed document $\mathcal{D}$, and tokens $\mathcal{W}$ used to describe the victim's weapon (may be empty)} \KwOut{Document string index $i$ of the token used to identify an attack from the victim} \textsc{attack} $\leftarrow$ \{\textit{attack}, \textit{confront}, \textit{fire}, \textit{harm}, \textit{injure}, \textit{lunge}, \textit{shoot}, \textit{stab}, \textit{strike}\} \; \textsc{advance} $\leftarrow$ \textit{accelerate}, \textit{advance}, \{\textit{drive}\} \; \textsc{officer}, \textsc{victim} $\leftarrow$ \text{partition}$(\mathcal{D})$ \; \For{$t_j \in \mathcal{D}$}{ \If{dep$(t_j)=$ \textit{nsubj}}{ \For{$(v, o) \in$ verbs\_with\_objs$(t_j, [\:])$}{ \If{$(\text{lemma}(v) \in \textsc{attack})$ \textbf{and} $[(t_j \in \textsc{victim}) \: \textbf{or} \: (o \in \textsc{officer} \cup \mathcal{W}) ]$ }{ \Return{index$(v, \mathcal{D})$}\; } \If{$v \in \textsc{advance}$ \: \textbf{and} \: $o \in \textsc{officer}$}{ \Return{index$(v, \mathcal{D})$}\; } } } } \Return{\texttt{inf}}\; \caption{attack$(\mathcal{D}, \mathcal{W})$} \label{alg:mentions_attack} \end{algorithm} \begin{algorithm} \SetAlgoLined \KwIn{Verb $v$ from dependency parsed document, recursively generated list $\mathcal{L}$ of (verb, object) tuples (initially empty) } \KwOut{$\mathcal{L}$} \For{$c \in \text{children}(v)$}{ \If{$c \in \textsc{object}$}{ append$((v,c), \mathcal{L})$\; } \ElseIf{dep$(c)$ = prep}{ append$((v, \text{get\_pobj}(c)), \mathcal{L})$\; } \ElseIf{dep$(c) \in$ \{ \textit{conj}, \textit{xcomp}\}}{ $\mathcal{L} \leftarrow$ verbs\_with\_objs$(c, \mathcal{L})$\; } } \Return{$\mathcal{L}$}\; \caption{verbs\_with\_objs$(v, \mathcal{L})$} \label{alg:verbs_with_obj} \end{algorithm} \subsubsection{Official Source \space / \space Unofficial Source.} We use the same high-level method both to identify interviews from Official Sources (e.g. police), and to determine if the article includes quotations or summarizes the perspective of an Unofficial Source (a bystander or civilian other than the victim). To do so, we consider two basic and representative phrasal forms: (1) $<$\textit{SOURCE}$>$ $<$\textit{VERB}$>$ $<$\textit{CLAUSE}$>$, and (2) \textit{according to} $<$\textit{SOURCE}$>$, $<$\textit{CLAUSE}$>$. To extract Phrase Type 1, we identify tokens of entity type PERSON or part of speech PRON such that the token is an \textit{nsubj} or \textit{nsubjpass} whose head lemma belongs to the verb set \{\textit{answer}, \textit{claim}, \textit{confirm}, \textit{declare}, \textit{explain}, \textit{reply}, \textit{report}, \textit{say}, \textit{state}, \textit{tell}\}. To extract Phrase Type 2, we identify tokens in a dependency relation\footnote{In spaCy 2.1, we need to consider two-hop relations: \\ \textit{According} (\texttt{prep}) $\rightarrow$ \textit{to} \space (\texttt{pobj}) \space $\rightarrow$ \space $<\textit{$SOURCE$}>$} with the word \textit{according}. If such a token is found in either case and it is \textit{outside} the \textsc{victim} token set, then we return that token's index as an \textbf{Unofficial Source} match. If the token is found in the \textsc{officer} set or has a lemma in \{\textit{authority}, \textit{investigator}, \textit{official}, \textit{source}\}, then we return the token's index as an \textbf{Official Source} match. \subsubsection{Systemic claims.} This category is arguably the most variable, and as a result, possibly the most difficult to identify reliably. Systemic claims are used to frame police shootings as a product of structural or institutional racism. To identify this frame, we look for sentences that (1) mention \textit{other} police shooting incidents or (2) use certain keywords related to the national or global scope of the problem. We decide (2) using \texttt{(nation(?:[ -])?wide|wide(?:[ -])?spread|police~violence|police shootings|police~killings|racism| racial|systemic|reform|no(?:[ -])?knock)} as our regular expression. Here, \textit{nation-wide} and \textit{widespread} indicate scope, \textit{police violence, police shootings,} and \textit{police killings} describe the persistent issue, while \textit{racism, racial, systemic} indicate the root of the issue, and \textit{reform} the solution. We also include \textit{no-knock} since there have been over 20k no-knock raids per year since the start of our data collection, and the failures of this policy have been used heavily as evidence in support of police reform \cite{lind2015cops}. To identify (1), we match tokens $t_k$ of entity type PERSON with thematic relation PATIENT (a dependency relation in \{\textit{nsubjpass}, \textit{dobj}, \textit{iobj}, \textit{obj}\}) such that $t_k \not \in \textsc{victim}$ and $t_k \not \in \textsc{officer}$ and $t_k$ is not the object of a \textsc{victim} \textit{nsubj}. If lemma$(t_k)$ belongs to the set \{\textit{kill}, \textit{murder}, \textit{shoot}\}, we return the index of $t_k$ as a match for systemic framing. This process is detailed in Algorithm~\ref{alg:systemic}, with a helper function in Algorithm~\ref{alg:has_victim_subj}. \begin{algorithm}[] \caption{systemic$(\mathcal{D})$} \SetAlgoLined \KwIn{Dependency parsed document $\mathcal{D}$} \KwOut{Document string index $i$ of the token used to identify locus of systemic framing} \textsc{shooting} $\leftarrow$ \{\textit{shoot}, \textit{kill}, \textit{murder}\} \; \textsc{officer}, \textsc{victim} $\leftarrow$ \text{partition}$(\mathcal{D})$ \; \For{$t_j \in \mathcal{D}$}{ \If{$($dep$(t_j) \in $ \{\textit{nsubjpass}, \textit{dobj}, \textit{iobj}, \textit{obj}\}$)$ \textbf{and} $($lemma$($head$(t_j)) \in$ \{\textit{shoot}, \textit{kill}, \textit{murder}\}$)$ \textbf{and} $(t_j \not \in \textsc{victim})$ \textbf{and} $(t_j \not \in \textsc{officer})$ \textbf{and} $($ent\_type$(t_j)$ = PERSON$)$ \textbf{and not} has\_victim\_subject$(t_j)$}{ \Return{index$($head$(t_j), \mathcal{D})$}\; } } \Return{\texttt{inf}}\; \label{alg:systemic} \end{algorithm} \begin{algorithm}[] \caption{has\_victim\_subject$(o)$} \SetAlgoLined \KwIn{Object token $o$ from dependency parsed document} \KwOut{\texttt{boolean}} \For{$c \in \text{children}(\text{head}(o))$}{ \If{$c \in \textsc{victim}$ \textbf{and} dep$(c)$ = \textit{nsubj}}{ \Return{\texttt{true}}\; } } \Return{\texttt{false}}\; \label{alg:has_victim_subj} \end{algorithm} \section{Validating Frame Extraction Methods} \label{appdx:validation} We report the accuracy, precision, and recall of our system in Table~\ref{tab:extraction_performance}. Ground truth is the binary presence of the frame in the 50 annotated articles above. We observe high precision and recall scores generally above 70\%, with only \textit{race} and \textit{unofficial sources} at 66\% and 65\% precision. \begin{table}[] \centering \small \resizebox{\columnwidth}{!}{ \begin{tabular}{lrrr} \toprule \textbf{Frame} & \textbf{Acc} & \textbf{Prec} & \textbf{Recall} \\ \midrule Age & 86\% & 100\% & 84\% \\ Armed & 76\% & 76\% & 76\% \\ Attack & 72\% & 73\% & 73\% \\ Criminal record & 84\% & 77\% & 96\% \\ Fleeing & 96\% & 89\% & 100\% \\ Gender & 88\% & 91\% & 91\% \\ Legal language & 88\% & 86\% & 100\% \\ Mental illness & 100\% & 100\% & 100\% \\ Official sources & 92\% & 95\% & 95\% \\ Race & 92\% & 66\% & 100\% \\ Systemic & 88\% & 86\% & 100\% \\ Unarmed & 96\% & 88\% & 88\% \\ Unofficial sources & 70\% & 65\% & 88\% \\ Video & 90\% & 93\% & 78\% \\ \bottomrule \end{tabular} } \caption{Frame extraction performance on 50 hand-labeled news articles} \label{tab:extraction_performance} \end{table} \section{Framing vs. Agenda Setting} \label{appdx:supp_framing_analysis} \begin{table}[] \centering \small \resizebox{\columnwidth}{!}{ \begin{tabular}{lrrrr} \toprule \textbf{Victim Variable} & \textbf{Lib.} & \textbf{Cons.} & \textbf{Cohen's \textsl{d}}\\ \midrule Mental illness & 0.206 & 0.194 & -0.030 \\ Fleeing & 0.246 & 0.235 & -0.027 \\ Video & 0.136 & 0.155 & 0.054 \\ Armed ** & 0.580 & 0.648 & 0.140 \\ Attack *** & 0.351 & 0.486 & 0.276 \\ \bottomrule \\ \end{tabular} } \caption{\textbf{Agenda setting}. Proportion of liberal and conservative articles that report on killings where \textit{Victim Variable} is true (e.g. the victim really was Fleeing). We see that conservative sources report more on cases where the victim is armed and attacking} \label{tab:agenda_setting} \end{table} One potential confound is \textsl{agenda setting}, or ideological differences in the amount of coverage that is devoted to different events \cite{mccombs2002agenda}. In Table~\ref{tab:agenda_setting}, we see that conservative sources were significantly more likely to cover cases in which the victim was \textsl{armed} (.648 vs. .580, $+12\%$) and \textsl{attacking} (.486 vs. .351, $+38\%$) overall. However, we find that the differences in partisan frame alignment are \textbf{magnified} when we consider only news sources where the ground truth metadata reflects the framing category. That is, we observed larger effect sizes (Cohen's $d$) in Table~\ref{tab:conditional_partisan_framing} than we did for the observed differences in Table~\ref{tab:partisan_framing}. Furthermore, when conditioning on ground truth \textsl{race}, these frames are universally more prevalent when the victim is Black as opposed to when the victim is white. News reports on white victims thus appear more episodic \cite{lawrence2000politics}, while reports on Black victims appear to be more polarizing in terms of the given framing devices. Policing continues to be a highly racialized issue \cite{muhammad2019condemnation}. \begin{table}[t] \centering \small \resizebox{\columnwidth}{!}{ \begin{tabular}{lrrrr} \toprule \textbf{Framing Device} & \textbf{Lib.} & \textbf{Cons.} & \textbf{Cohen's \textsl{d}}\\ \midrule Armed (T) *** & 0.590 & \textbf{0.701} & 0.233 \\ Armed (T, black) ** & 0.639 & \textbf{0.762} & 0.270 \\ Armed (T, white) ** & 0.552 & \textbf{0.693} & 0.293 \\ \midrule Attack (T) *** & 0.381 & \textbf{0.575} & 0.395 \\ Attack (T, black) *** & 0.407 & \textbf{0.585} & 0.359 \\ Attack (T, white) *** & 0.378 & \textbf{0.573} & 0.396 \\ \midrule Fleeing (T) *** & 0.381 & \textbf{0.604} & 0.458 \\ Fleeing (T, black) * & 0.424 & \textbf{0.589} & 0.334 \\ Fleeing (T, white) *** & 0.250 & \textbf{0.542} & 0.618 \\ \midrule Mental illness (T) * & \textbf{0.433} & 0.320 & 0.235 \\ Mental illness (T, black) * & \textbf{0.480} & 0.291 & 0.387 \\ Mental illness (T, white) & \textbf{0.430} & 0.347 & 0.171 \\ \midrule Race (black) *** & \textbf{0.612} & 0.373 & 0.492 \\ Race (white) & \textbf{0.197} & 0.146 & 0.139 \\ \midrule Unarmed (T) *** & \textbf{0.365} & 0.218 & 0.324 \\ Unarmed (T, black) & \textbf{0.441} & 0.337 & 0.212 \\ Unarmed (T, white) ** & \textbf{0.261} & 0.118 & 0.380 \\ \midrule Video (T) * & 0.486 & \textbf{0.626} & 0.282 \\ Video (T, black) & 0.529 & \textbf{0.639} & 0.223 \\ Video (T,white) & 0.394 & \textbf{0.577} & 0.368 \\ \bottomrule \\ \end{tabular} } \caption{\textbf{Frame alignment is magnified when conditioned on ground truth}. The proportion of liberal and conservative news articles that include framing device conditioned on articles where ground truth reflects the framing category (T) and the victim's race is given (black, white).} \label{tab:conditional_partisan_framing} \end{table} \section{Introduction} The normative standard in American journalism is for the news to be neutral and objective, especially regarding politically charged events \cite{schudson2001objectivity}. Despite this expectation, journalists are unable to report on all of an event's details simultaneously. By choosing to include or exclude details, or by highlighting salient details in a particular order, journalists unavoidably induce a preferred interpretation among readers \cite{iyengar1990framing}. This selective presentation is called \textbf{framing} \cite{entman2007framing}. Framing influences the way people think by ``telling them what to think about'' \cite{entman2010media}. In this way, frames impact both public opinion \cite{chong2007framing,iyengar1990framing,mccombs2002agenda,price2005framing,rugg1941experiments,schuldt2011global} and policy decisions \cite{baumgartner2008decline,dardis2008media}. \begin{figure} \centering \includegraphics[width=\columnwidth]{img/frame_examples.pdf} \caption{\small \textbf{Framing the murder of Jordan Edwards.} Our system automatically identifies key details or \textsl{frames} that shape a reader's understanding of the shooting. Importantly, we can distinguish the victim's attributes from the descriptions of the officer, like \textsl{killer} in ``killer cop.'' Only the left-leaning article uses this morally-weighted term, \textsl{killer}, and also takes care to mention the victim's \textsl{race}. While the left-leaning article highlights a quote from the Edwards' pastor, an \textsl{unofficial source}, the right-center article cites only \textsl{official sources} (namely the Chief of Police). Both mention the victim's \textsl{age} and \textsl{unarmed} status. }\label{fig:frame_example} \end{figure} Prior work has revealed an abundance of politically effective framing devices \cite{bryan2011motivating,gentzkow2010drives,price2005framing,rugg1941experiments,schuldt2011global}, some of which have been operationalized and measured at scale using methods from NLP \cite{card2015media,demszky2019analyzing,field2018framing,greene2009more,recasens2013linguistic,tsur2015frame}. While these works extensively cover \textsl{issue} frames in broad topics of political debate (e.g. \textsl{immigration}), they overlook a wide array of \textsl{entity} frames (how an individual is represented; e.g. a particular undocumented worker described as lazy), and these can have huge policy implications for target populations \cite{schneider1993social}. In this paper, we introduce an NLP framework to understand \textsl{entity framing} and its relation to \textsl{issue framing} in political news. As a case study, we consider news coverage of police violence. Though we choose this domain for the stark contrast between two readily-discernible entities (police and victim), our framing measures can also be applied to other major social issues \cite{luodetecting,mendelsohn2021modeling}, and salient entities involved in these events, like protesters, politicians, migrants, etc. We make several novel contributions. First, we introduce the \data{} that contains 82k news articles on over 7k police shooting incidents. See Figure~\ref{fig:frame_example} for example articles with annotated frames. Next, we build a set of syntax-aware methods for extracting 15 issue and entity frames, implemented using entity co-reference and the syntactic dependency parse. Unlike bag-of-words methods (e.g. topic modeling) our \textbf{entity-centric methods} can distinguish between a white \textsl{man} and a white \textsl{car}. In this example, we identify race frames by scanning the attributive and predicative adjectives of any \textsc{victim} tokens. Such distinctions can be crucial, especially in a domain where \textsl{officer} aggression will have different ramifications than aggression from a \textsl{suspected criminal}. By exact string-matching, we can also extract, for the first time, differences in the \textbf{\textsl{order} that frames appear} within each document. We find that liberal sources discuss \textsl{race} and \textsl{systemic racism} much earlier, which can prime readers to interpret all other frames through the lens of injustice. Furthermore, we quantify and statistically confirm what smaller-scale content analyses in the social sciences have previously shown \cite{drakulich2020race,fridkin2017race,lawrence2000politics}, that conservative sources highlight law-and-order and focus on the victim's criminal record or their harm or resistance towards the officer, which could justify police conduct. Finally, we rigorously examine the broader interactions between media framing and offline events. We find that high-profile shootings are correlated with an increase in \textsl{systemic} and \textsl{racial} framing, and that increased protest activity \textsl{Granger-causes} or precedes media attention towards the victim's race and unarmed status. \section{Related Work} A large body of related work in NLP focuses on detecting stance, ideology, or political leaning \cite{baly2020we,bamman2015open,iyyer2014political,johnson2017ideological,preoctiuc2017beyond,luo2020desmog,stefanov2020predicting}. While we show a relationship between framing and political leaning, we argue that frames are often more subtle than overt expressions of stance, and cognitively more salient than other stylistic differences in the language of political actors, thus more challenging to be measured. \begin{figure*}[t] \centering \includegraphics[width=0.85\textwidth]{img/data_collection_diagram.png} \caption{\small Construction process of \data{}. } \label{fig:pipeline} \end{figure*} Specifically, we distinguish between \textsl{issue} frames \cite{iyengar1990framing} and \textsl{entity} frames \cite{van2020doctor}. Entity frames are descriptions of individuals that can shape a reader’s ideas about a broader issue. The entity frames of interest here are the victim’s age, gender, race, criminality, mental illness, and attacking/fleeing/unarmed status. One related work found a \textsl{shooter identity} cluster in their topic model that contained broad descriptors like ``crazy'' \cite{demszky2019analyzing}. However, their bag-of-words method would not differentiate a crazy \textsl{shooter} from a crazy \textsl{situation}. To follow up, there is need for a \textsl{syntax-aware} analysis. In a systematic study of issue framing, \citet{card2015media} applied the Policy Frames Codebook of \citet{boydstun2013identifying} to build the Media Frames Corpus (MFC). They annotated spans of text from discussions on tobacco, same-sex marriage, and immigration policy with broad meta-topic framing labels like \textsl{health and safety}. \citet{field2018framing} built lexicons from the MFC annotations to classify issue frames in Russian news, and \citet{roy2020weakly} extended this work with subframe lexicons to refine the broad categories of the MFC. Some have considered the way Moral Foundations \cite{haidt2007morality} can serve as issue frames \cite{kwak2020frameaxis,mokhberian2020moral,priniski2021mapping}, and others have built issue-specific typologies \cite{mendelsohn2021modeling}. While issue framing has been well-studied \cite{ajjour2019modeling,baumer2015testing}, entity framing remains \emph{under-examined} in NLP with a few exceptions. One line of work used an unsupervised approach to identify \textsl{personas} or clusters of co-occurring verbs and adjective modifiers \cite{card2016analyzing,bamman2013learning,iyyer2016feuding,joseph2017girls}. Another line of work combined psychology lexicons with distributional methods to measure implicit differences in power, sentiment, and agency attributed to male and female entities in news and film \cite{sap2017connotation,field2019entity,field2019contextual}. Social scientists have experimentally manipulated framing devices related to police violence, including \textsl{law and order}, \textsl{police brutality}, or \textsl{racial stereotypes}, revealing dramatic effects on participants' perceptions of police shootings \cite{fridell2017explaining,dukes2017black,porter2018public}. Criminologists have trained coders to manually annotate on the order of 100 news articles for framing devices relevant to police use of force \cite{hirschfield2010legitimating,ash2019framing}. While these studies provide great theoretical insight, their manual coding schemes and small corpora are not suited for large scale real-time analysis of news reports nationwide. While many recent works in NLP have started to detect police shootings \cite{nguyen2018killed,keith2017identifying} and other gun violence \cite{pavlick2016gun}, we are the first to model entity-centric framing around police violence. \section{\data{}} \begin{table*} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{rrrrrrrrr} \toprule \textbf{Leaning} & \textbf{Articles} (\#) & \textbf{Events} (\#) & \textbf{Sources} (\#) & \textbf{Armed} (\%) & \textbf{Attack} (\%) & \textbf{Fleeing} (\%) & \textbf{Mental Illness} (\%) & \textbf{Video} (\%) \\ \midrule Left & 1,090 & 6730 & 90 & 58.0 & 35.1 & 24.6 & 20.6 & 13.6 \\ Left Center & 9,761 & 3,794 & 233 & 66.1 & 45.9 & 23.8 & 18.0 & 11.1 \\ Least Biased & 5,214 & 3,428 & 164 & 73.3 & 53.7 & 26.2 & 19.3 & 8.8 \\ Right Center & 3,993 & 2,631 & 105 & 71.1 & 50.9 & 24.9 & 18.0 & 9.9 \\ Right & 1,009 & 782 & 40 & 64.8 & 48.7 & 23.3 & 19.3 & 15.5 \\ None & 59,739 & 7,300 & 12,931 & 71.0 & 52.3 & 24.9 & 18.4 & 8.9 \\ \hline Total & 80,806 & 7,647 & 13,563 & 70.3 & 51.3 & 24.8 & 18.4 & 9.4 \\ \bottomrule \end{tabular} } \caption{\small \data{} statistics. The number of articles and the breakdown of events by whether the victim was \textit{Armed, Attacking, Fleeing}, had \textit{Mental Illness} or was filmed on \textit{Video} according to Mapping Police Violence data. \textit{Leaning} is decided via Media Bias Fact Check in Section~\ref{susbsec:assigning_media_slant_labels}.} \label{tab:dataset_statistics} \end{table*} To study media framing of police violence, we introduce \data{} (\adata) which contains over 82,000 news reports of police shooting events. We now describe the corpus construction as it is shown in Figure \ref{fig:pipeline}. \subsection{Identifying Shooting Events} We first use Mapping Police Violence \cite{mpv2021} to identify shooting events. It is a representative, reliable, and detailed record, as it cross-references the three most complete databases available: Fatal Encounters \cite{fatalEncounters}, the U.S. Police Shootings Database \cite{policeShootingsDatabase}, and Killed by Police, all of which have been validated by the Bureau of Justice Statistics \cite{banks2016arrest}. Prior works in sociology and criminology \cite{gray2020race} use it as an alternative to official police reports because local police departments significantly underreport shootings \cite{williams2019limitations}. At the time of our retrieval, the Mapping Police Violence dataset identified 8,169 named victims of police shootings between January 1, 2013 and September 4, 2020 and provided the victim's age, gender, and race, whether they fled or attacked the officer, and whether the victim had a known mental illness or was armed (and with what weapon), as well as the location and date of the shooting, the agency responsible, and whether the incident was recorded on video. \subsection{Collecting News Reports} For each named police shooting or violent encounter in Mapping Police Violence, we query the Google search API for up to 30 news articles relevant to that event. We found this sample size is large enough to represent both sides without introducing too much noise. Our query string includes officer keywords, the victim's name, and a time window restricted to within one month of the event (see Appendix~\ref{sec:news_data_collection} for details and design choices). Next, we extracted article publication dates using the \texttt{Webhose} extractor \cite{geva_2018}, and as a preprocessing step, we used the \texttt{Dragnet} library \cite{peters2013content} to automatically filter and remove ads, navigation items, or other irrelevant content from the raw HTML. In the end, the \data{} contained 82,100 articles across 7,679 events. The per-ideology statistics of reported events are given in Table~\ref{tab:dataset_statistics}. The racial and ethnic distribution is: White (43.0\%), Black (29.7\%), Hispanic (15.3\%), Asian (1.5\%), Native American (1.3\%), and Pacific Islander (0.5\%), while the other 8.7\% of articles report on a victim of unknown race/ethnicity. \subsection{Assigning Media Slant Labels} \label{susbsec:assigning_media_slant_labels} We associated each news source with a political leaning by matching its URL domain name with the \citet{mbfc2020} record. With more than 1,500 records, the MBFC contains the largest available collection of crowdsourced media slant labels, and it has been used as ground truth in other recent work on news bias \cite{dinkov2019predicting,baly2018predicting,baly2019multi,nadeem2019fakta,stefanov2020predicting}. The MBFC labels are \textsl{extreme left}, \textsl{left}, \textsl{left-center}, \textsl{least biased}, \textsl{right-center}, \textsl{right}, and \textsl{extreme right}. For our political framing analysis (Section~\ref{sec:partisan_framing_analysis}), we consider a source liberal if its MBFC slant label is \textsl{left} or \textsl{extreme left}, and we consider the source conservative if its label is \textsl{right} or \textsl{extreme right}. We manually filter this polarized subset to ensure that all articles are on-topic. This led to 1,090 liberal articles and 1,002 conservative articles. \section{Media Frames Extraction} \label{sec:extracting} We are interested in both the issue and entity frames that structure public narratives on police violence. We will now present our computational framework for extracting both from news text. Throughout this section, we cite numerous prior works from criminology and sociology to motivate our taxonomy, but we are the first to measure these frames computationally. As a preview of the system, Figure~\ref{fig:frame_example} shows the key frames extracted from two articles on the murder of 15-year-old Jordan Edwards. Notably, only the left-leaning article mentions the victim's \textsl{race}. Most importantly, our system distinguishes the victim's attributes from descriptions of the officer. Here, it is the \textsl{officer} who is described as a ``killer,'' and not the victim. \subsection{Entity-Centric Frames} \label{sec:entity_frames} Our entity-centric analysis and lexicons are a key contribution in this work. We distinguish the victim's attributes like \textsl{race} and \textsl{armed} status from that of the officer or some other entity, and so we move beyond generic and global \textsl{issue} frames to understand how the target population is portrayed. These methods require a partitioning of entity tokens into \textsc{victim} and \textsc{officer} sets. To do so, we first append to each set any tokens matching a \textsl{victim} or \textsl{officer} regex. The officer regex is general, but the victim regex matches the known name, race, and gender of the victim in \adata, like \textit{Ronette Morales, Hispanic, woman} (See Appendix~\ref{sec:frame_extraction_methods}). Second, we use the huggingface \texttt{neuralcoref} for coreference resolution based on \citet{clark2016deep}, and append all tokens from spans that corefer to the \textsc{victim} or \textsc{officer} set respectively. \textbf{Age, Gender, and Race.} Following \citet{ash2019framing}, we consider the age, gender and race of the victim, which are central to an intersectional understanding of unjust police conduct \cite{dottolo2008don}. We extract age and gender frames by string matching on the gender modifier or the numeric age. We extract race frames by searching the attributive or predicative adjectives and predicate nouns of \textsc{victim} tokens and matching these with the victim's known race. \textbf{Armed or Unarmed.} Knowing whether the victim was armed or unarmed is a crucial variable for measuring structural racism in policing \cite{mesic2018relationship}. We identify mentions of an unarmed victim with the regex \texttt{unarm(?:ed|ing|s)?}, and mentions of an armed victim with \texttt{arm(ed|ing|s)?}, excluding tokens with noun part-of-speech. \textbf{Attacking or Fleeing.} Since \textsl{Tennessee v. Garner} (1985), the lower courts have ruled that police use of deadly force is justified against felons in flight only when the felon is dangerous \cite{harmon2008police}. Since \textsl{Plumhoff v. Rickard} (2014), deadly force is justified by the risk of the fleeing suspect. Thus whether the victim fled or attacked the officer can inform the officer's judgment on the appropriateness of deadly force. We propose an entity-specific string-matching method to extract attack frames, where a \textsc{victim} token must be the head of a verb like \textit{injure}, and we and use expressions like \texttt{\textbackslash bflee(:?ing)} to extract fleeing mentions. \textbf{Criminality.} Whether the article frames the victim as someone who has engaged in criminal activity may serve to justify police conduct \cite{hirschfield2010legitimating}. To capture this frame, we used Empath \cite{fast2016empath} to build a novel lexicon of unambiguously criminal behaviors (e.g. \textsl{cocaine}, \textsl{robbed}), and searched for these terms. \textbf{Mental Illness.} Police are often the first responders in mental health emergencies \cite{patch1999police}, but there is growing concern that the police are not sufficiently trained to de-escalate crisis situations involving persons with mental illness \cite{kerr2010police}. Mentioning a victim's mental illness may also highlight evidence of this structural shortcoming. We again used Empath to build a custom lexicon for known mental illnesses and their correlates (e.g. \textsl{alcoholic}, \textsl{bipolar}, \textsl{schizophrenia}). As for \textit{Criminality}, this is not an exhaustive list; we balance precision and recall by ensuring that terms are unambiguous in the context of police violence. Still, we may not capture other signs of mental illness, like descriptions of erratic behaviors. \subsection{Issue Frames} \label{sec:issue_frames} \hspace{\parindent}\textbf{Legal Language.} Similar to \citet{ash2019framing}, we investigate frames which emphasize legal outcomes for police conduct. To capture this frame, we used a public lexicon of legal terms from the Administrative Office of the U.S. Courts \citeyear{uscourts}. \textbf{Official and Unofficial Sources.} Many news accounts favor official reports which frame police violence as the state-authorized response to dangerous criminal activity \cite{hirschfield2010legitimating,lawrence2000politics}. Others may include unofficial sources like interviews with first-hand witnesses. We identify official and unofficial sources with the following Hearst-like patterns: $<$source$>$ $<$verb$>$ $<$clause$>$ or \textit{according to} $<$source$>$, $<$clause$>$. Our unique entity-centric approach lets us exclude the victim's quotes and focus on witness testimony. \textbf{Systemic.} While the news has historically favored episodic \cite{iyengar1990framing} fragmented \cite{bennett2016news}, or decontextualized narratives \cite{lawrence2000politics}, there has been an increase in systemic framing since the 1999 shooting of Amadou Diallo \cite{hirschfield2010legitimating}. Such articles identify police shootings as the product of structural or institutional racism. To extract this frame, we look for sentences that (1) mention \textsl{other} police shooting incidents or (2) use keywords related to the national or global scope of the problem. \textbf{Video.} Video evidence was a catalyst for the Rodney King protests \cite{lawrence2000politics}. Psychology studies have found that subjects who witnessed a police shooting on video were significantly more likely to consider the shooting unjustified compared with those who observed through news text or audio \cite{mccamman2017police}. We identify reports of body or dash camera footage using the simple regex \texttt{(body(?: )?cam|dash(?: )?cam)} \subsection{Moral Foundations} Moral Foundations Theory \cite{haidt2007morality} (MFT) is a framework for understanding universal values that underlie human judgments of right and wrong. These values form five dichotomous pairs: care/harm, fairness/cheating, loyalty/betrayal, authority/subversion, and purity/degradation. While MFT is rooted in psychology, it has since been applied in political science to differentiate liberal and conservative thought \citet{graham2009liberals}. We quantify the moral foundations that media invoke to frame the virtues or vices of the officer and the victim in a given report using the extended MFT dictionary of \citet{rezapour2019enhancing}. \subsection{Linguistic Style} To supplement our understanding of overtly topical \textsl{entity} and \textsl{issue} frames, we investigate two relevant linguistic structures: passive verbs and modals. \textbf{Passive Constructions.} Prior works identify framing effects that arise from passive phrases in narratives of police violence \cite{hirschfield2010legitimating,ash2019framing}. In this work, we distinguish \textsl{agentive} passives (e.g. ``He was killed \textsl{by} police.'') from \textsl{agentless} passives (e.g. ``He was killed.''). While both deprive actors of agency \cite{richardson2006analysing}, only the latter obscures the actor entirely, effectively removing any blame from them \cite{greene2009more}. We specifically contrast liberal and conservative use of \textsc{victim}-headed agentless passives (passive verbs whose patient belongs to the \textsc{victim} set). \textbf{Modal Verbs.} Modals are used \textsl{deontically} to express necessity and possibility, and in this way, they are often used to make moral arguments, suggest solutions, or assign blame \cite{portner2009modality}. Following \citet{demszky2019analyzing}, we count the document-level frequency of tokens belonging to four modal categories: MUST, SHOULD (\textit{should / shouldn't / should've}), NEED and HAVE TO. \section{Validating Frame Extraction Methods} \label{sec:validation} One coder labeled 50 randomly-sampled news articles with indices to mark the order of frames present. Against this ground truth, our binary frame extraction system achieves high precision and recall scores above 70\%, with only \textsl{race} and \textsl{unofficial sources} at 66\% and 65\% precision. Accuracy is no less than 70\% for any frame (see Table~\ref{tab:extraction_performance} in Appendix~\ref{appdx:validation}). One advantage of our system is that it is not a black box -- it gives us the precise location of each frame in the document. When we sort the indices of the predicted frame locations, we find that our system achieves a 0.752 Spearman correlation with the ground truth frame ordering. Finally, the annotator gave us a rank order of the officer and victim moral foundations most exemplified in the document. When we sort, for each document, the foundations by score, our system achieves 0.66 mAP for the officer and 0.40 mAP for the victim. \section{Political Framing of Police Violence} \label{sec:partisan_framing_analysis} \subsection{Frame Inclusion Aligns with Slant} \label{subsec:cat_freq} As shown in Table~\ref{tab:partisan_framing} (\textit{Left}), we find that liberal sources frame the issue of police violence as more of a systemic issue, using \textsl{race}, \textsl{unarmed}, and \textsl{mental illness} entity frames, while conservative sources frame police conduct as justified with regard to an uncooperative victim. Specifically, conservative sources more often mention a victim is \textsl{armed} (.588 vs. .439, $+34\%$), \textsl{attacking} ($+46\%$), and \textsl{fleeing} ($+47\%$). These strategies serve to justify police conduct since \textsl{Tennessee v. Garner} (1985) affirmed the use of deadly force on dangerous suspects in flight \cite{harmon2008police}, and this narrative is furthered by \textsl{official sources} ($+38\%$), \textsl{legal language} ($+5\%$), and the victim's \textsl{criminal record} ($+7\%$). Liberal news instead emphasizes the victim's \textsl{race} ($+100\%$), \textsl{mental illness} ($+25\%$), and that the victim was \textsl{unarmed} ($+25\%$). Cumulatively, these details reinforce the prominent \textsl{systemic racism} narrative that appears $47\%$ more often in liberal media. The victim's mental illness may signal police failure to handle mental health emergencies \cite{kerr2010police}, and the police killing of an unarmed Black victim provides evidence of institutional racism in law enforcement \cite{aymer2016can,tolliver2016police}. Together with gender and age, the victim's race informs an intersectional account of police discrimination \cite{dottolo2008don}. Surprisingly, we find that liberal sources mention age and gender significantly \textsl{less} often than do conservative sources. We find no significant differences in the mention of video evidence, possibly because this detail is broadly newsworthy. \textbf{Controlling for confounds amplifies ideological differences.} One potential confound is \textsl{agenda setting}, or ideological differences in the amount of coverage that is devoted to different events \cite{mccombs2002agenda}. In fact, conservative sources were significantly more likely to cover cases in which the victim was \textsl{armed} and \textsl{attacking} overall. However, our findings in this section are actually \textbf{magnified} when we level these differences and consider only news sources where the ground truth metadata reflects the framing category (see Appendix~\ref{appdx:supp_framing_analysis}). \textbf{Framing decisions are a \textit{function} of slant.} Finally, we expect that news sources will differ not only diametrically at the political poles, but also linearly in the degree of their polarization. To examine this, we collected an integer score ranging from -35 (extreme left) to +35 (extreme right), which we scraped from the MBFC using an open source tool \cite{carey2021}. We aggregated articles by their political leaning scores and found the proportion of articles in each bin that express the frame. Linear regressions in Figure~\ref{fig:reg} reveal a statistically significant negative correlation between conservatism and the \textsl{criminal record} (r=-0.319), \textsl{unarmed} (r=-0.303), \textsl{race} (r=-0.667) and \textsl{systemic} frames (r=-0.283). \begin{table} \centering \resizebox{\columnwidth}{!}{ \begin{tabular}{lllccllc} \toprule & \multicolumn{3}{c}{\textbf{Inclusion}} & \phantom{a} & \multicolumn{3}{c}{\textbf{Ordering}} \\ \cmidrule{2-4} \cmidrule{6-8} \\ \textbf{Framing Device} & \textbf{Lib.} & \textbf{Cons.} & $p$ & & \textbf{Lib.} & \textbf{Cons.} & $p$ \\ \midrule Age & 0.472 & \textbf{0.764} & $^{***}$ & & \textbf{0.480} & 0.467 & \\ Armed & 0.439 & \textbf{0.588} & $^{***}$ & & 0.313 & \textbf{0.358} & $^*$\\ Attack & 0.369 & \textbf{0.539} & $^{***}$ & & 0.267 & \textbf{0.306} & \\ Criminal record & 0.613 & \textbf{0.655} & $^{*}$ & & \textbf{0.294} & 0.278 & $^{**}$ \\ Fleeing & 0.228 & \textbf{0.336} & $^{***}$ & & \textbf{0.246} & 0.217 &\\ Gender & 0.610 & \textbf{0.620} & $^{***}$ & & 0.611 & \textbf{0.622} & \\ Legal language & 0.875 & \textbf{0.919} & $^{***}$ & & \textbf{0.523} & 0.419 & $^{***}$ \\ Mental illness & \textbf{0.181} & 0.145 & $^{*}$ & & 0.301 & 0.296 & \\ Official sources & 0.586 & \textbf{0.808} & $^{***}$ & & \textbf{0.194} & 0.163 & $^{***}$ \\ Race & \textbf{0.428} & 0.214 & $^{***}$ & & \textbf{0.296} & 0.233 & $^{***}$ \\ Systemic & \textbf{0.428} & 0.291 & $^{***}$ & & \textbf{0.410} & 0.283 & $^{***}$ \\ Unarmed & \textbf{0.195} & 0.110 & $^{***}$ & & 0.408 & \textbf{0.470} & \\ Unofficial sources & 0.708 & \textbf{0.780} & $^{**}$ & & \textbf{0.184} & 0.163 & $^{***}$\\ Video & 0.164 & \textbf{0.191} & & & 0.283 & \textbf{0.436} & $^{***}$\\ \bottomrule \end{tabular} } \caption{\small (\textit{Left}) \textbf{Frame inclusion aligns with political slant.} The proportion of liberal and conservative news articles that include the given framing device. (\textit{Right}) \textbf{Frame ordering aligns with media slant.} The average inverse document frame order in liberal and conservative news articles where the \textsl{frame is present}. Significance given by Mann-Whitney rank test: * ($p<0.05$), ** ($p<0.01$), *** ($p<0.001$)} \label{tab:partisan_framing} \end{table} \begin{figure*} \centering \includegraphics[width=0.9\textwidth]{img/regressions_CROPPED.pdf} \caption{\small \textbf{Framing as a function of political leaning.} The MBFC political leaning score vs. the document frame proportion. }\label{fig:reg} \end{figure*} \subsection{Frame Ordering Aligns with Slant} \label{subsec:frame_ordering} The Inverted Pyramid, one of the most popular styles of journalism, dictates that the most important information in an article should come first \cite{po2003news,upadhyay2016making}. We hypothesize that the ordering of frames will reflect the author's judgment on which details are most important, so we should observe ideological differences in frame ordering. In Table~\ref{tab:partisan_framing} (\textit{Right}) we compare, for each frame, its average inverse document rank in liberal and conservative news articles in which the frame was \textsl{already present}. We find that conservative sources highlight that the victim is armed and attacking by placing these details earlier in the report when they are mentioned (avg. inverse rank .358 vs. .313 for \textsl{armed}, and .306 vs. .267 for \textsl{attacking ). By prioritizing these details early in the article, conservative sources further highlight the need for law and order \cite{drakulich2020race,fridkin2017race}. Although in Section~\ref{subsec:cat_freq} we found conservative sources favored police reports, we now observe a liberal bias favoring early quotations from these \textsl{official sources} (.194 vs. .163 avg. inverse rank ). At the same time, liberal sources highlight \textsl{unofficial sources} like eyewitnesses who may identify police brutality as a ``pervasive and endemic problem'' \cite{lawrence2000politics}. Most notably, liberal sources prioritize \textsl{legal language} (0.523 vs. 0.419) and \textsl{systemic} framing (0.410 vs. 0.283). Liberal sources place these frames, on average, \textsl{second} in the total frame ordering (inverse rank $\approx 1/2$), which primes readers to interpret almost all other remaining frames through the lens of injustice and structural racism. This confirms prior work \cite{graham2009liberals,hirschfield2010legitimating}. \begin{figure*} \centering \includegraphics[width=1.0\textwidth]{img/moral_foundations_COUNTS_cropped.pdf} \caption{\small \textbf{Differences in moral foundation frames.} The average moral framing proportions in liberal and conservative articles. } \label{fig:mft_results} \end{figure*} \subsection{Moral Framing Differences} \label{subsec:moral_framing_differences} Prior work \cite{graham2013moral,haidt2007morality} suggests that liberals emphasize the care/harm and fairness/cheating dimensions, especially as vice in the officer \cite{lawrence2000politics}, while conservatives might defend the foundations more equally, especially as virtue in the officer or vice in the victim \cite{drakulich2020race}. We test this by computing, for each moral foundation and for each entity (victim, officer), the proportion of liberal and conservative articles in which either a modifier or agentive verb from the \citet{rezapour2019enhancing} moral foundation dictionary is used to describe that entity. Figure~\ref{fig:mft_results} shows that conservative sources unsurprisingly place more emphasis on the victim's \textsl{harm}ful behaviors ($+48\%$ ). Only liberal sources mention the officer's unfairness or \textsl{cheating}. Liberal articles also include more mentions of officer \textsl{subversion} ($+130\%$ ) and, surprisingly, \textsl{fairness} ($+135\%$ ). These results are all significant with $p<0.05$; no other ideological differences are significant. \subsection{The Politics of Linguistic Style} Liberal politicians largely support Black Lives Matter and its calls for police reform \cite{hill2018crime}, while conservative politicians have historically opposed the Black Lives Matter movement or any anti-police sentiment \cite{drakulich2020race}. We hypothesize that there will be significant differences in the use of agentless passive constructions and modal verbs of necessity \cite{greene2009more,portner2009modality} between conservative and liberal sources. When we compare the average document-level frequency for each framing device, normalized by the length of the document in words, we find these hypotheses supported in Table~\ref{tab:linguistic_style}. Liberal sources use modal verbs of necessity like SHOULD and HAVE TO more frequently. Conservative sources use agentless passive constructions 61\% more than liberal sources (2.55$\times 10^{-3}$ vs. 1.58$\times 10^{-3}$), and \textsl{violent} passives\footnote{To indicate violence, we check that the lemma is in \{`attack', `confront', `fire', `harm', `injure', `kill', `lunge', `murder', `shoot', `stab', `strike'\}} 31\% more. However, we also find that conservative sources discuss the victim more overall ($+34\% ). To remove this confound, we re-normalize the \textsl{Passive} and \textsl{Violent Passive} counts by the number of victim tokens instead, and the results still hold: $+39\%$ and $+22\%$ respectively. \section{The Broader Scope of Media Framing} \begin{figure*} \centering \includegraphics[width=0.9\linewidth]{img/temporal_alt_cropped.png} \caption{\small \textbf{Peaks near high-profile shootings.} Per-day proportion of articles with \textsl{race, unarmed,} and \textsl{systemic} frames included across time, excluding articles for the high-profile police shootings listed. This reveals local spikes near 15 high-profile incidents. For example, on the \textit{Left} we see \textsl{race} framing spikes after the death of Michael Brown. } \label{fig:temporal_analysis} \end{figure*} Prior works have algorithmically tracked collective attention in the news cycle \cite{leskovec2009meme}, and measured the correlation between media attention and offline political action \cite{de2016social,holt2013age,mooijman2018moralization}. This section examines the broader scope of media framing via two studies. \subsection{Peaks Near High-Profile Killings} \label{sec:temporal_peaks} Do news framing strategies co-evolve across time? We expect to see coordinated peaks in the prevalence of \textsl{race}, \textsl{unarmed}, and \textsl{systemic} frames across U.S. news media, especially near high-profile killings of unarmed Black American citizens. To investigate this hypothesis, we took, for each salient frame, the proportion of articles that mention that frame out of the 82,000 news articles in our dataset, \textsl{excluding} any articles that report one of the 15 high-profile police killings listed in Figure~\ref{fig:temporal_analysis}. Then we found the Pearson correlation between each of the time series in a pairwise manner: 0.49 systemic/unarmed, 0.56 race/unarmed, and 0.70 race/systemic; all statistically significant with $p<2.0\times 10^{-167}$. \begin{table}[t] \centering \small \resizebox{\columnwidth}{!}{ \begin{tabular}{L{2.2cm}rrrr} \toprule \textbf{Framing Device} & \textbf{Lib.} & \textbf{Cons.} & \textbf{Cohen's \textsl{d}} \\ \midrule MUST ** & \textbf{2.09e-4} & 1.03e-5 & 0.132 \\ \midrule SHOULD *** & \textbf{4.44e-4} & 2.04e-4 & 0.262 \\ \midrule NEED *** & \textbf{2.64e-4} & 1.15e-4 & 0.190 \\ \midrule HAVE TO *** & \textbf{4.09e-4} & 1.75e-4 & 0.196 \\ \midrule Passive *** & 1.58e-3 & \textbf{2.55e-3} & 0.367 \\ \midrule Passive \newline Violence *** & 6.21e-4 & \textbf{8.13e-4} & 0.121\\ \bottomrule \end{tabular} } \caption{\small \textbf{Politics and linguistic styles.} The average document frequency of linguistic structures, normalized by the length of the document. $^{***}$ $p<0.001$ } \label{tab:linguistic_style} \end{table} The time series in Figure~\ref{fig:temporal_analysis}, smoothed over a 15-day rolling window, reveal local spikes near each of the high-profile killings, with the largest surge in racial and systemic framing near the shootings of \textsc{Alton Sterling} and \textsc{Philando Castile}. Two of the earliest surges appear near the killing of \textsc{Eric Garner} and \textsc{Michael Brown}, which largely ignited the Black Lives Matter movement \cite{carney2016all}. Recent spikes also appear near the killing of \textsc{Breonna Taylor} and \textsc{George Floyd}, which sparked record-setting protests in 2020 \cite{buchanan2020black}. We quantify this with an intervention test \cite{toda1995statistical} on each time series $X = (X_1, X_2, ..., X_t, ...)$ by fitting an AR(1) model defined by \begin{equation*} X_t = \beta_0 X_{t-1} + \beta_1 P(t) + c + \epsilon_t \end{equation*} with parameters $\beta$, constant $c$, error $\epsilon_t$, and a pulse function $P(t)$ to indicate the intervention \begin{equation*} P(t) = \begin{cases} 1, & \text{there was a high-profile shooting at $t$} \\ 0, & \text{else} \end{cases} \end{equation*} The AR(1) is an auto-regressive model where only the previous term $X_{t-1}$ influences the prediction for $X_t$, and the intervention $P(t)$ allows us to test the null hypothesis that a high-profile killing does not impact framing proportions ($\beta_1 = 0$). We find the coefficient on the intervention $\beta_1$ is positive for each frame, and significant only in the \textsl{unarmed} regression ($\beta_1=2.03$, $p<0.01$). Given this and the high correlation between the three framing categories, we conclude that high-profile killings influence media decisions to frame other killings. \subsection{Political Action Precedes Media Framing} \label{sec:predicting_political_action} We predict that protest volume will positively correlate with media attention on the race and unarmed status of recent victims and the underlying systemic injustice of police killings. Using the CountLove \cite{leung_perkins_2021} protest volume estimates from January 15, 2017 through December 1, 2020, we aligned the per-day national volume with the \textsl{race}, \textsl{unarmed}, and \textsl{systemic} time series (Figure~\ref{fig:temporal_analysis}) and found low but positive Pearson correlations of 0.098, 0.073, and 0.088 respectively, each statistically significant. These correlations were directed, with protest volume \textsl{Granger-causing} an increase in these framing strategies. For two aligned time series $X$ and $Y$, we say $X$ \textsl{Granger-causes} $Y$ if past values $X_{t-\ell} \in X$ lead to better predictions of the current $Y_t \in Y$ than do the past values $Y_{t-\ell} \in Y$ alone \cite{granger1980testing}. Here, $\ell$ is called the lag. We considered a lag of 1 and a lag of 2 days. The rightmost column of Figure~\ref{fig:temporal_analysis} shows that, with $\ell=2$, protest volume Granger-causes \textsl{race} and \textsl{unarmed} framing with statistical significance $(p<0.05)$ by the SSR F-test. The reverse direction is \textsl{not} statistically significant. This reveals that offline protest behaviors \textsl{precede} these important media framing decisions, not the other way around. This echoes similar findings on media shifts after the Ferguson protests \cite{arora2019framing} and social media engagement after protests like Arab Spring \cite{wolfsfeld2013social}. \begin{table} \centering \small \resizebox{\columnwidth}{!}{ \begin{tabular}{L{1.2cm}L{1.5cm}|R{1.5cm}R{1.5cm}} \toprule \textbf{Frame} & Pearson $r$ & Granger \newline 1-lag $p$ & Granger \newline 2-lag $p$ \\ \midrule Race & 0.098 & 0.0185 & 0.0381 \\ Unarmed & 0.073 & 0.1646 & 0.0024 \\ Systemic & 0.088 & 0.0801 & 0.0600\\ \bottomrule \end{tabular} } \caption{\small{\textbf{Media Framing and Political Action.} Correlation and $p$ values for political protests \textit{Granger-causing} media attention towards the race, unarmed, and systemic frames.}} \label{tab:granger_causality} \end{table} \section{Discussion and Conclusion} In this work, we present new tools for measuring entity-centric media framing, introduce the \data{}, and use them to understand media coverage on police violence in the United States. Our work uncovers 15 domain-relevant framing devices and reveals significant differences in the way liberal and conservative news sources frame both the \textsl{issue} of police violence and the \textsl{entities} involved. We also show that framing strategies co-evolve, and that protest activity precedes or anticipates crucial media framing decisions. We should carefully consider the limitations of this work and the potential for bias. Since we matched age, gender and race directly with the MPV, we expect minimal bias, but acknowledge that our exact string-matching methods will miss context clues (e.g. drinking age), imprecise referents (e.g. ``teenager''), and circumlocution. We also rely on lexicons derived from expert sources (e.g. U.S. Courts \citeyear{uscourts}) or from data (Empath), both of which are inherently incomplete. Even the most straightforward keywords (e.g. armed, fleeing) are prone to error. However, biases could also appear in discriminative text classifiers. The advantage of our approach is that it is interpretable and extractive, allowing us to identify matched spans of text and quantify differences in frame ordering. Furthermore, it is grounded heavy in the social science literature. Similar methods could be applied to other major issues such as climate change \cite{luo2020desmog} and immigration \cite{mendelsohn2021modeling}, where entities include politicians, protesters, and minorities, and where race, mental illness, and unarmed status may all be salient framing devices (e.g. describing the perpetrator or victim of anti-Asian abuse or violence; \citealt{gover2020anti, chiang2020anti, ziems2020racism, vidgen2020detecting}). \section*{Acknowledgments} The authors would like to thank the members of SALT lab and the anonymous reviewers for their thoughtful feedback. \section*{Ethical Considerations} To respect copyright law and the intellectual property, we withhold full news text from the public data repository. Outside of the victim metadata, \data{} does not contain private or sensitive information. We do not anticipate any significant risks of deployment. However, we caution that our extraction methods are fallible (see Section~\ref{sec:validation}). \bibliographystyle{acl_natbib}
{'timestamp': '2021-09-14T02:15:01', 'yymm': '2109', 'arxiv_id': '2109.05325', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05325'}
arxiv
\section{Introduction} There are many industrial application in which the detection of anomalies and their corresponding characterization is vital to achieve operational continuity. This approach is advantageous when the failure conditions are not known in advance. In these cases, the classification system cannot be trained before entering the production stage. Some examples of these scenarios are: machine fail detection over unknown operational environments \cite{kuang2018stable}, new object recognition over hyper-spectral imagery \cite{REF5}, and the treatment of unknown cybersecurity threats \cite{garcia2009anomaly, ahn2014big, narayanan2018early}. Different machine learning approaches have been applied to the problem of detection and characterization of anomalies. Heuristic approaches to infer the type of anomalies \cite{REF1}, flow-based statistical analysis \cite{REF2}, wavelet transformation based \cite{REF3}, cluster approaches \cite{REF4}, generative adversarial networks \cite{REF6}, and different proposals grouped in the family of Artificial Immune Systems based algorithms (AIS) \cite{fernandes2017applications}. AIS presents inherent capabilities for the treatment of the anomaly detection and characterization problem implementing diverse strategies and algorithms based on the Biological Immune System of the mammals (BIS) \cite{gorriz2020artificial}. One of the most popular AIS algorithm is the Negative Selection Algorithm (NSA), proposed by Forrest (\citet{1}), which is based on the immune cells selection process developed in the thymus. Another important algorithm is the Clonal Selection (CSA), proposed by Burnet (\citet{22}). The most known implementation of CSA is CLONALG (\citet{55}), it is a pattern recognition proposal, based on mutation for diversification of the best detectors, and the removal of the less representatives. A fundamental, and relatively new algorithm, in the field of immunology is the Danger Theory Algorithm (DT), proposed by Matzinger (\citet{20,66}). DT removes the need to model the self-behavior --normal behavior--, but it requires the definition of environmental signals associated with the anomalies. In this work, we consider a different perspective on immunity. We understand the system to be protected as a dynamic one, whose state is structurally adjusted, continuously and plastically, during its operation adding new elements and removing the old ones. The addition and removal of the elements is controlled by its internal dynamics of the system. This behavior is associated with the concept of \textbf{endogenous double plasticity} (\citet{EDP}) and may be achieved through simple heuristics such as the compensation of weak elements, the preservation of diversity, and the elimination of the redundancy, i.e., the establishment of a balance using ecological mechanism. Immunity is understood as the dynamic interaction of a population of agents. In this context we deal with the modeling task, using the \textbf{Agent-Based Modeling} (ABM) approach. A previous work entitled \textbf{Artificial Bioindicators System} (ABS) (\citet{AB-EIA}) shows the evidence of the usefulness of the population of agents for the detection of anomalies in the context of computer security. Our proposal is centered on achieving other advantage associated with BIS, by exploiting the \textbf{characterization-memorization} of threats and the possibility of a quick \textbf{secondary immune response}. For this purpose, we incorporate the DT concept, allowing the control of the relationship between the original agent's population and a new kind of reactive agents. These new agents are deployed for the implementation of the secondary immune response of the system.\\ The objective of this article is to report the progress of the development of the \textbf{Reactive Artificial Bioindicators System} (R-ABS), with a significant improvement of the capacities of the ABS (\citet{AB-EIA}). The original model proposes an IDS inspired by an ecological approach to BIS, evolving a population of agents learning to survive in their environment. Thus the adaptation process allows the transformation of the agent population into bioindicators which are capable of detecting system anomalies. We use this work as a base, and we propose an extension for achieving the characterization of the threats and improving the overall response time of the system. \\ In this work, we report four contributions; the first one is the simplification the original ABS model. The second contribution is the extension of the model for achieving threat characterization skills over the system. The third one provides a mechanism for protecting the self-knowledge of the system, avoiding profile contamination. The fourth improvement is the overall reduction of the time for detecting threats to which the system was previously exposed. \\ The paper is structured as follows. After this introduction, the second section presents the ABS model and its characteristics. Then, section three describes the R-ABS proposal, and section four describes the experiments developed followed by the results and the conclusion in the last two sections of the article. \section{The ABS Model} The ABS (\citet{AB-EIA}) was built under an ecological point of view, from the BIS and tested in a cybersecurity scenario. In this context, ABS deals with the problem of \textbf{network intrusion detection}. Consequently, the system agents adapt to a normal behavior of the network data. This allows the detection of an attack in the same way the natural bioindicators do, because these agents are not adapted to the hostile environment. ABS uses a population of agents very sensitive to detection anomalies. For this reason, these agents are called \textbf{Artificial Bioindicators (AB)}. The system is represented as a 2-dimensional world with two entities: {\em agents} and {\em particles}. Agents act like bioindicators. Changes in the environment disturb these agents. The environment corresponds to the traffic over the network data. The particles represent the characteristics of the real network traffic, on the two-dimensional world. Agents are static entities initially created at random; these agents undergo an evolutionary processes that allow them to adapt and ensure that only the most suitable survive. Each agent has two key parameters associated with it: \begin{itemize} \item \textbf{Energy} ($E_{x}$): Indicates the amount of energy that the agent possesses, this energy is used to keep the agent's metabolism activated and for reproduction purposes. \item \textbf{Genetic code} ($\theta$): It is a vector that determines the agent's qualities, in other words, the agent's ability to survive some characteristic of the environment. Each $i \in \theta$ represents a single gene, and each gene represents one of the characteristics observed in the network traffic. \end{itemize} Agents require a certain level of energy ($E_{r}$) to reproduce, which is a parameter. Agents reproduce asexually, activating a mutation operator on their genetic code, which consists of a random exchange of two elements in their genome, this small variation determines the affinity of the child with the environment.\\ \textbf{Particles} are created by the system when a specific characteristic is found in network packets. The system adds the particles on one side of the world (according to the definition of its topology). The particles are then moved, one step at a time, to the other side, until there are no more particles left on the first chosen side. Particles have two key characteristics: {\em type} and {\em capacity}. The type describes the characteristic of the traffic represented by the particle, and the capacity represents the number of agents capable of absorbing the particles with which they collide.\\ When a particle $p$ collides with an agent, its energy level can be modified according to the following equation: \begin{equation} N_{x}=\sum_{p}(\Phi - \epsilon* i_p) \end{equation} $N_{x}$ is the amount of energy that a particle delivers to an agent $x$, $\Phi$ is the maximum energy value that a particle can deliver to an agent, $i_p$ is an index which represents the type of particle that can be found in the genetic code of the agent $x$, and $\epsilon$ represents a penalizing factor for the energy value. The collision of a particle with an agent increases or decreases the energy of the agent, depending on the genetic affinity between the agent and the particle. \\ As an example, consider a system with five different particles. Each agent has a genetic vector, which contains a permutation of the five particles. In this way, if an agent $A$ has a vector $A_v=(e,a,c,b,d)$ and the arrival of a package $P$ to the network introduces the particles $e$ and $b$, the nutritional value associated to $P$ given $A$ will be: $N_A=(\Phi - \epsilon * i_e) + (\Phi - \epsilon* i_b)$, where $i_e$ is $0$ and $i_b$ is 3. In this scenario, the particle $e$ produces the maximum nutritional profit for A. On the other hand, the particle $b$ is less beneficial and can even be toxic (negative value of $N$) depending on the value of $\epsilon$.\\ The ABS model presents the following important issues: \begin{enumerate} \item \textbf{Lack of reactive capabilities}: The original ABS model does not have built-in detection capabilities; detection is done through the use of an external observation process. This process receives the agent's cardinality and their energy level as input. Then, this tool uses this information for classification purposes. The output can be one of these answers: {\em normal situation} or {\em system under attack}. Therefore, the attack report is not triggered by the agent's reaction.\\ \item \textbf{The problem of the retraining of agents:} When an attack persists over time, agents tend to adapt to it. This is an undesirable side effect since the agents can become contaminated with the attack. Its function should be to characterize a normal operation of the system. \item \textbf{Slow reaction capability:} The dynamics of the system is given by a set of adaptive agents, and the classification process is based on the disturbance that the network attack causes in the agents. Since the disturbance is analyzed by an external tool, that considers trend patterns that involve some parameters of the system, the final reaction can be slow. \item \textbf{ Lack of learning capacities} The original model does not provide a learning mechanism useful for the treatment of repeated attacks. \end{enumerate} \section{The R-ABS Model} This section describes a proposal for dealing with the four problems identified in the ABS model. To solve these problems, the new model must satisfy the following requirements: \begin{itemize} \item All reactions are triggered by the agents of the model. No external tools participate in this action, nor do global metric values of the model. In this sense, the new proposal does not alter the implicit rules on the existing relations between neighbors; and that correspond to the functionalities activated by the emergency. This is how the problem of {\em lack of reactive capacities} of the ABS model is solved. \item The new model tackles the {\em problem of the retraining of agents}, providing a mechanism for the protection of the self-characterization, achieved by the implementation of new memory entities and constraints relationships, to encourage or inhibit their creation. \item The new proposal as an AIS has two levels of response to threats. First, an innate and generic response for unknown attacks and second, an adaptive response for known attacks. In this second level, the characterization of the unknown threats achieves the speed-up of the reactions. Allowing the detection by signatures and not only by anomaly detection. In this way, R-ABS tries the {\em slow reaction and the lack of learning capacities} of ABS. \end{itemize} \begin{figure} \centering \includegraphics[width=0.9\textwidth]{DiagramaRABS.pdf} \caption{Main Model of R-ABS} \label{fig:RABS} \end{figure} In Figure \ref{fig:RABS}, it is shown the R-ABS response on the same ABS action scenario. The structure is composed by a set of different agents populations, and the network traffic is captured by a sniffer that is in charge of feeding the system. R-ABS has two types of evolutionary agents. The first type is quite similar to the original definition of agents in the ABS model. These agents are called n-agents (agents of normality) in the R-ABS model. The n-agents are defined to characterize the normal behavior of the system being monitored (Self) and each R-ABS model maintains a population of these agents. The second type of agent corresponds to the r-agents (reactive agents); this type of agent is designed to learn the threat's behavior. R-ABS can deploy and maintain several r-agents populations, one population for each different threat occurrence. There are different signals that communicate different agent's populations. in this way, perturbations over n-agents produce danger signals, and these signals are used for the creation and consolidation of populations of r-agents. It is important to highlight that the creation of multiples r-agents populations does not imply a computing or memory overhead, because only one population is created per event, and when a r-agents population is already trained, it maintains only a few consolidated agents for a straightforward pattern recognition procedure. \\ The presence of an anomaly (perturbation of n-agents) triggers the activities of r-agents in the same way that innate immunity activates adaptive immunity. Mature (Consolidated) r-agents can produce other types of signals when known attacks activate them. These signals have the purpose of inhibiting the evolution of n-agents, preventing the contamination of normal (Self) behavior characterization. In general terms, the relationship between signals and agents populations can be described by means of the following rules: \\ \scalebox{1}{ (a) $\blacktriangledown$(n-agents)$\wedge\blacktriangle$(r-agents)$\overset{produce}{\rightarrow}$ \{full reaction\} } \\ \scalebox{1}{ (b) $\blacktriangledown$(n-agents)$\wedge\blacktriangledown$(r-agents)$\overset{produce}{\rightarrow}$ \{new population, soft reaction\} } \\ \scalebox{1}{ (c) $\blacktriangle$(n-agents)$\wedge\blacktriangle$(r-agents)$\overset{produce}{\rightarrow}$ \{full reaction, i-NSA \}} \\ \scalebox{1}{ (d) $\blacktriangle$(n-agents)$\wedge\blacktriangledown$(r-agents)$\overset{produce}{\rightarrow} \emptyset$ } \\ This set of four rules explains the primary behavior of R-ABS. The rules are not triggered by an external tool but by the direct action of the agents. In rule (a), R-ABS is operational, and under attack. In this situation, the n-agents lost their affinity to the incoming network traffic. Also, one of the r-agents population presents high-affinity levels with the incoming traffic, producing the reaction of the r-agents over the recognized threat. Rule (b) is triggered when the R-ABS is exposed to a new threat. In this way, the n-agent affinity to the traffic decreases, but none of the r-agents population has high-affinity with the incoming attack. In this situation, R-ABS deploys a new r-agent population and adapts it to the incoming threat. In this new-threat scenery, R-ABS can produce a soft reaction in the same way that innate immunity produces a nonspecific reaction in BIS. Rule (c) shows an inconsistency between the R-ABS population. While the r-agents affinity levels mark the presence of a threat, the n-agents population is not affected by the same perturbation. In this situation, R-ABS apply a non-scheduled variation of the Negative Selection Algorithm (i-NSA) to solve the inconsistency, and perform the full reaction of the r-agents. i-NSA is described in the next subsection. Finally, the rule (d) denotes the state of R-ABS in the absence of attacks. In this condition, the affinity of the n-agents is high and does not exist a population of r-agent with high affinity over the incoming traffic. \subsection{Inverted Negative Selection Algorithm} The Negative Selection Algorithm NSA was introduced by Forrest in \cite{1}. The NSA's primary goal is to allow the safe creation of new antigens detectors, destroying detectors that classify the self-behavior as a threat before they become mature. This algorithm is based on the immutability of the Self. We consider a different premise in R-ABS. The normal behavior of the systems is mutable, and it changes over time, but a specific threat is static. In this way, the exposure to a variation of a known attack triggers the generation of new r-agents populations to characterize this particular unknown hostile behavior. In other words, threat characterizations are, by definition, immutable. \\ R-ABS takes as reference the known threat for the destruction of harmful n-agents, this is, with high-affinity to the characterization of attacks provided by r-agents. In this way, inverted Negative Selection (i-NSA) is similar to NSA but cleaning the Self repertory taking as reference the non-Self definitions, and not cleaning the threat detectors repertory based on the Self repertory as the original NSA algorithm. \subsection{Model Simplification} We conduct a simplification of the original model, from a $2D$ world to a $1D$ topology. The main reason for doing this is that the ABS model does not justify the two dimensions need. In this sense, ABS does not take advantage of the 2D-world properties like distance between objects, movements, and agents' emergent clusters. We suppose a reduction of the computational effort by re-thinking the ABS idea over a 1D Topology, with a fixed number of agents, fewer parameters, and more simple interaction rules between the model elements. Besides that, ABS has other not informed settings values such as the size of the world $(range-in-X, range-in-Y)$, the speed of the particles in the model, and maybe other virtual world parameters that can affect the model behavior. \\ \subsection{R-ABS over Cybersecurity Domain} Technically, R-ABS is a {\em Network-based Intrusion Detection System} (NIDS), a system designed to detect network threats. In this way, The required input data is taken from a monitoring system generating an output report, useful for stop or mitigate the incoming hostile behavior. R-ABS was conceived as a symbiotic structure coupled with its host. In this way, R-ABS tries to maintain the network homeostasis for surviving and preserve the host's health. The input used by R-ABS is the network traffic of the monitored organizational network. We consider a set of binary characteristics extracted from headers of the Transport and Network layer of (TCP-UDP)/IP connections. We also consider SANS reference over the most attacked service ports for individualizing some critical services \cite{AB-EIA}. The selection of these characteristics is justified because they are used by ABS and allow a fair comparison between the algorithms. The detail for input information used by R-ABS is the following: \begin{itemize} \item \textbf{Reserved bits and network flags:} RB, MF, DF, F1, F2, URG, ACK, PSH, RST SYN, FIN. \item \textbf{Most attacked port (SANS):} Telnet, SSH, FTP, Netbios, Rlogin, RPC, NFS, NNTP, Lockd, Netbios, Xwin, DNS, LDAP, SMTP, POP, NTP, IMAP, HTTP, SSL, px, Serv, Time, TFTP, Finger, lpd, Syslog, SNMP, bgp, Socks. \end{itemize} Finally, we create a single binary vector $ V $ of length $ lv $ for each incoming network packet, where $ lv $ is the number of different traffic characteristics. Each position in the vector is associated with a specific traffic property.\\ \subsection{The agents of the R-ABS Model} R-ABS preserves the idea of agents that act bioindicators. Thus, the environment (network traffic) establishes a pressure mechanism that causes the population of agents continually adapts to this changing environment. In this context, the fittest individuals are those with higher levels of energy. All agents implemented in R-ABS have evolutive properties. For this purpose, each agent holds a genetic vector. This vector $ G $ establishes the affinity of the agents with the environment. The genetic representation of $ G $ is the same as the binary vector $V$ for the characterizing the incoming network traffic. The evolving mechanism of R-ABS is described through Algorithms 1 and \ref{algo:evolution-r}. The first one represents the behavior of the n-agents population, meanwhile the second algorithm represents the r-agents operation. Both procedures are very similar between them, and they are codependent. In this way, the n-agents population activates the evolution of the set of r-agents, and the r-agents populations can inhibit the n-agents population's change. These algorithms are activated whenever a new network package is captured. In detail, Algorithm 1 shows that the n-agents population $A$ is exposed to each network packet ($p_{cap}$), then, in line 4, the number of agents with energy below $energy_{thres}$ is calculated and stored in DS (danger signals), and the entire r-agent population inspects it because DS trigger their execution. In line 5, the algorithm checks if the Attack level evidence ($AS$) is under a threshold $AS_{thres}$. When the condition is true, the population continues evolving normally; in the other case, the algorithm inhibits the evolving process for preventing the contamination of the n-agents population with attack behavior. When the protection condition is satisfied, the algorithm selects a parent's group ($A'$). The chosen agents, from $A$, must have an energy level above a threshold ($energy_{thres} $). This is, agents already adapted to the normal network conditions. In the same way, the algorithm selects the a second group of agents ($A*$) from $A$, using the threshold ($Mem_{thres}$) in an elitist form ($Mem_{thres} >> energy_{thres}$). The Agents in $A*$ are considered matured because of their high affinity with the normal incoming traffic. Algorithm 1 defines $r$ as the number of new agents to be created and stored in $A_n$; the value of $r$ is determined using a proportion ($R$) of the total population of n-agents and considering the constraint of at least replacing dead agents. In lines 11 and 12, two parents ($p_1, p_2$) are selected from $A'$ using {\em Fitness Proportionate Selection} ($FPS$) and combined in ($o1, o2$) using a uniform crossover ($X_{uni}$) \cite{Michalewicz2004} , then the new offsprings are added to $A_n$. This process is repeated until obtaining a number of new agents equal to, or larger than, $r$. In line 15, the algorithm step represents the replacement mechanism for the n-agents. The policy is straightforward, and it consists of changing the weakest n-agents in terms of their energy level with the new agents in $A_n$. The normal behavior of the system can change over time. In this way, R-ABS must provide a mechanism to update the representation of the Self. This process is achieved through the function update (line 16) that replaces the weakest mature r-agents (memory cells) in $A^{**} $ with new high energy elements in $A^{*}$. The evolving mechanism of r-agents is presented in Algorithm 2. The algorithm is quite similar to the one previously presented. The main difference is that the evolution and the evaluation of the r-agents are allowed only in the presence of danger signals ($DS$). In this way, the algorithm takes as input the value of $DS$ determined by the n-agents population. When this value achieves the threshold level ($DS_{thres}$), r-agents are exposed to the network traffic ($p_{cap}$) and evolve with the same rules that govern n-agents evolution. Another significative difference is that r-agents does not have an update mechanism for mature agents. Thus, when one population of r-agents characterizes an attack scenario, it stops evolving and it is only used to establish an already known attack. The r-agents are responsible for computing the value of attack signals ($AS$) used by the n-agents population to inhibit the evolving process in case of attacks (line 5).\\ \begin{algorithm}[t] \caption{Evolving mechanisms of n-agents in R-ABS} \label{evolutionn} \begin{algorithmic}[1] \STATE {\bf input:} $A,energy_{thres},R,p_{cap},AS$ \STATE {\bf input:} $AS_{thres}, Mem_{thres}$ \STATE $expose(A, p_{cap})$ \STATE $DS =|\left \{ a \in A^{**} | a_{energy} < energy_{thres} \right \}|$ \IF{ $AS < AS_{thres}$} \STATE $A':=\left \{ a \in A | a_{energy} \ge energy_{thres} \right \}$ \STATE $A^{*}:= \left \{ a \in A | a_{energy} \ge Mem_{thres} \right \}$ \STATE $A_n:=\emptyset$ \STATE $r:=argMax(deadAgents,R\cdot|A|)$ \WHILE{$|A_n|<r$} \STATE $p_1,p_2:=FPS(A')$ \STATE $o_1,o_2:=X_{uni}(p_1,p_2)$ \STATE $A_n:=A_n\cup \{ o_1, o_2\}$ \ENDWHILE \STATE $replace(A,An, policy(lower\_energy))$ \STATE $update(A^{**},A^{*}, policy(lower\_energy))$ \ENDIF \end{algorithmic} \end{algorithm} \begin{algorithm}[t] \caption{Evolving mechanisms of r-agents in R-ABS} \label{algo:evolution-r} \begin{algorithmic}[1] \STATE {\bf input:} $A,energy_{thres},R,p_{cap},DS$ \STATE {\bf input:} $DS_{thres}, Mem_{thres},AS_{thres}$ \IF{ $DS > DS_{thres}$} \STATE $expose(A, p_{cap})$ \STATE $AS =|\left \{ a \in A^* | a_{energy} \ge AS_{thres} \right \}|$ \STATE $A':=\left \{ a \in A | a_{energy} \ge energy_{thres} \right \}$ \STATE $A^{*}:=A^{*} \cup \left \{ a \in A | a_{energy} \ge Mem_{thres} \right \}$ \STATE $A_n:=\emptyset$ \STATE $r:=argMax(deadAgents,R\cdot|A|)$ \WHILE{$|A_n|<r$} \STATE $p_1,p_2:=FPS(A')$ \STATE $o_1,o_2:=X_{uni}(p_1,p_2)$ \STATE $A_n:=A_n\cup \{ o_1, o_2\}$ \ENDWHILE \STATE $replace(A,An, policy(lower\_energy))$ \ENDIF \end{algorithmic} \end{algorithm} \section{Experimental Evaluation} The experimental setup was designed to check out the on-line attack learning capabilities of R-ABS and the possible improvement in the response speed of the model for previously seen attacks, not for validating R-ABS as a full operational IDS. In order to comply with these requirements, we carry out two types of experiments. The first one establishes a comparison between R-ABS and ABS models, and the second one was designed for determining the R-ABS proposal's advantages. All experiences are structured using a subset of the following phases: \begin{itemize} \item \textbf{Phase 1}: The model is exposed to normal network traffic. The goal is to achieve the initial adaptation to the protected network's ordinary operation condition. \item \textbf{Phase 2}: The model is exposed to an unknown attack to evaluate its response. \item \textbf{Phase 3}: Network traffic is changed back to normal conditions. \item \textbf{Phase 4}: The model is exposed again to the attack presented in Phase 2 for testing the algorithms' secondary immune response. \end{itemize} To deal with the non-deterministic behavior of the algorithms under evaluation, every experiment is executed ten times. The experimental dataset used is composed of elements from DARPA'98 and some complementary normal and hostile traffic captured for this work generated with \textit{GoldenEye} \footnote{https://sourceforge.net/projects/goldeneye/}. The details about the used testbed can be inspected in the following table:\\ \begin{table} \caption{Experimental Dataset Composition} \centering \scalebox{1.2}{ \begin{tabular}{ l|l|r } \hline \textbf{Type of Attack} & \textbf{Name} & \textbf{Packets} \\ \hline \multirow{4}{*}{Denial of Service (DoS)} & {\em land} & 1100 \\ & {\em syslog} & 1002 \\ & {\em udp-storm} & 1667 \\ & {\em custom$^{*}$ } & 3000 \\ \hline \multicolumn{2}{ c| }{DoS total} & 6769 \\ \hline \multirow{2}{*}{Remote to Local (R2L)} & {\em http-tunnel } & 1196 \\ & {\em sendmail} & 1548 \\ \hline \multicolumn{2}{ c| }{R2L total} & 2744 \\ \hline \multirow{4}{*}{User to Root (U2R)} & {\em sql} & 1026 \\ & {\em ffbconfig} & 1533 \\ & {\em ps} & 703 \\ \hline \multicolumn{2}{ c| }{U2R total} & 3262 \\ \hline Normal traffic & normal & 8618 \\ \hline \multicolumn{2}{ c| }{\textbf{Total}} & 21393 \\ \hline \end{tabular} } \end{table} \subsection{ ABS v/s R-ABS Baseline Experiment} ABS model has two important weaknesses already described (the problem of the retraining of agents and lack of learning capacities). It was taken into account for establishing a fair comparison between R-ABS and ABS in terms of pure anomaly detection capacity. Thus, we produce an experiment with only the two first phases already described. Also, Phase 2 is interrupted when the ABS's agents begin to adapt to the abnormal behavior. Then, the same traffic pattern was applied over R-ABS. This baseline experiment has the same structure described in the original ABS paper \cite{AB-EIA}. \subsection{ ABS v/s R-ABS Extended Comparison} For a better understanding of the differences between ABS and R-ABS, two additional experiments were carried out. The first one is two phases too, but without the extension constraints of the attack phase (Phase 2). In this sense, this experiment does not protect from the agent retraining problem. The second experiment is a simple extension of the previously described. This experience adds Phase 3. Thus, this experiment verified the classifiers' response when the normality is restored. \subsection{ R-ABS Capabilities Evaluation} Because R-ABS has learning capabilities not available in ABS, we perform an additional experiment. This experience uses the four defined phases. Thus, R-ABS is exposed twice to each particular attack for comparing the behavior between an unknown attack and a known one for the second exposure. \section{Results} The Results of the experiments for the ABS and R-ABS models are presented using confusion matrices. Thus, the result tables show the correlation between the {\em Actual} or correct status of each evaluated network package versus the {\em Predicted} status informed by the models. This status can be Normal ($N$) and Attack ($A$). In the case of an {\em Actual} Attack package informed by the model (Predicted) as Attack, it will increment the $TP$ (True Positive counter); but if the predicted status is Normal, it will increment the $FN$ (False Negative counter). The $TN$ (True Negative) and $FP$ (False Positive) are similarly calculated when the actual status of the evaluated package is Normal. We used the previous values to compute the {\em sensitivity } $Sens=TP/(TP+FN)$ and the {\em specificity} $Spec=TN/(TN+FP)$. Table \ref{baseline} shows the baseline experiments results with a Phase 2 that does not compromise the ABS agents' integrity. In this situation, ABS performs better than R-ABS with higher sensitivity for a similar specificity, this scenario shows the strength of ABS as an anomaly detector but does not highlight its weaknesses. \begin{table}[!htb] \caption{Baseline Results} \label{baseline} \begin{subtable}{.55\linewidth} \centering \caption{ABS Baseline} \scalebox{1.3}{ \begin{tabular}{cc|cc} \multicolumn{1}{c}{} &\multicolumn{1}{c}{} &\multicolumn{2}{c}{Predicted} \\ \multicolumn{1}{c}{} & \multicolumn{1}{c|}{} & \multicolumn{1}{c}{$A$} & \multicolumn{1}{c}{$N$} \\ \hline \multirow[c]{2}{*}{\rotatebox[origin=tr]{90}{Actual}} & $A$ & 20.9 & 9.1 \\[1.5ex] & $N$ & 53.4 & 756.6 \\ \hline & &Sens:& 0.70\\ & &Spec:& 0.93\\ \\ \end{tabular} } \end{subtable}% \begin{subtable}{.5\linewidth} \centering \caption{R-ABS Baseline} \scalebox{1.3}{ \begin{tabular}{cc|cc} \multicolumn{1}{c}{} &\multicolumn{1}{c}{} &\multicolumn{2}{c}{Predicted} \\ \multicolumn{1}{c}{} & \multicolumn{1}{c|}{} & \multicolumn{1}{c}{$A$} & \multicolumn{1}{c}{$N$} \\ \hline \multirow[c]{2}{*}{\rotatebox[origin=tr]{90}{Actual}} & $A$ & 18.6 & 1.4 \\[1.5ex] & $N$ & 58.9 & 751.5 \\ \hline & &Sens:&0.62\\ & &Spec:&0.93\\ \\ \end{tabular} } \end{subtable} \end{table} Table \ref{extended} (a),(b) shows the results achieved when the experiments use a Phase 2 with arbitrary length (unique difference with the baseline experiment). In (a), the table shows a dramatic decrement in ABS's sensitivity from 0.7 to 0.33 considering the baseline experiment. Meanwhile, R-ABS (b) increments its sensitivity from 0.62 to 0.71 with a very controlled decrement of the specificity from 0.93 to 0.9. The results are similar for experiments that include the restoration of the normality (Phase 3) in (c) and (d). This decrease in performance for ABS is due to the innate capabilities of the agents to adapt to anything, even an attack, rendering the model mostly indifferent to the ongoing attack, R-ABS, on the other hand, has does not have this problem. \begin{table}[!htb] \caption{Extended Comparison Results} \label{extended} \begin{subtable}{.5\linewidth} \centering \caption{ABS 2-phases} \scalebox{1.3}{ \begin{tabular}{cc|cc} \multicolumn{1}{c}{} &\multicolumn{1}{c}{} &\multicolumn{2}{c}{Predicted} \\ \multicolumn{1}{c}{} & \multicolumn{1}{c|}{} & \multicolumn{1}{c}{$A$} & \multicolumn{1}{c}{$N$} \\ \hline \multirow[c]{2}{*}{\rotatebox[origin=tr]{90}{Actual}} & $A$ & 46.7 & 92.8 \\[1.5ex] & $N$ & 53.3 & 756.7 \\ \hline & &Sens:& 0.33\\ & &Spec:& 0.93\\ \\ \end{tabular} } \end{subtable}% \begin{subtable}{.5\linewidth} \centering \caption{R-ABS 2-phases} \scalebox{1.3}{ \begin{tabular}{cc|cc} \multicolumn{1}{c}{} &\multicolumn{1}{c}{} &\multicolumn{2}{c}{Predicted} \\ \multicolumn{1}{c}{} & \multicolumn{1}{c|}{} & \multicolumn{1}{c}{$A$} & \multicolumn{1}{c}{$N$} \\ \hline \multirow[c]{2}{*}{\rotatebox[origin=tr]{90}{Actual}} & $A$ & 98.9 & 30.6 \\[1.5ex] & $N$ & 58.5 & 751.6 \\ \hline & &Sens:& 0.71\\ & &Spec:& 0.90\\ \\ \end{tabular} } \end{subtable} \begin{subtable}{.5\linewidth} \centering \caption{ABS 3-phases} \scalebox{1.3}{ \begin{tabular}{cc|cc} \multicolumn{1}{c}{} &\multicolumn{1}{c}{} &\multicolumn{2}{c}{Predicted} \\ \multicolumn{1}{c}{} & \multicolumn{1}{c|}{} & \multicolumn{1}{c}{$A$} & \multicolumn{1}{c}{$N$} \\ \hline \multirow[c]{2}{*}{\rotatebox[origin=tr]{90}{Actual}} & $A$ & 48.6 & 96.4 \\[1.5ex] & $N$ & 115.2 & 1564.8 \\ \hline & &Sens:& 0.34\\ & &Spec:& 0.93\\ \\ \end{tabular} } \end{subtable}% \begin{subtable}{.5\linewidth} \centering \caption{R-ABS 3-phases} \scalebox{1.3}{ \begin{tabular}{cc|cc} \multicolumn{1}{c}{} &\multicolumn{1}{c}{} &\multicolumn{2}{c}{Predicted} \\ \multicolumn{1}{c}{} & \multicolumn{1}{c|}{} & \multicolumn{1}{c}{$A$} & \multicolumn{1}{c}{$N$} \\ \hline \multirow[c]{2}{*}{\rotatebox[origin=tr]{90}{Actual}} & $A$ & 104.5 & 30.5 \\[1.5ex] & $N$ & 170.4 & 1509.6 \\ \hline & &Sens:&0.72\\ & &Spec:&0.90\\ \\ \end{tabular} } \end{subtable} \end{table} Table \ref{RABS} and Table \ref{Reaction} presents the results for the most relevant experiment over R-ABS. This experiment uses the four phases defined. In this sense, the experience allows us to known the effects of the activation mechanism using danger signals to deploy and mature r-agents populations. Also, allows us to observe the impact of the evolution inhibition process of the n-agents population induced by attack signals launched by r-agents that prevent the n-agent contamination. Additionally, the experiment evaluates the learning capabilities of R-ABS and the effect on the detection speed for the exposition to a previously detected and characterized threats. It is interesting to note from Table \ref{RABS} that the sensitivity of R-ABS in the 4-phases experiment increase when compared to the {\em 3-phases} experiment. This information can be correlated with Table \ref{Reaction}, where R-ABS did not detect the attacks {\em ffbconfig} and {\em ps} in the first exposition (RABS column), but it was detected in the second exposure (RABS* column). \begin{table}[!htb] \caption{R-ABS Evaluation Results} \label{RABS} \begin{subtable}{1\linewidth} \centering \caption{R-ABS 4-phases} \scalebox{1.3}{ \begin{tabular}{cc|cc} \multicolumn{1}{c}{} &\multicolumn{1}{c}{} &\multicolumn{2}{c}{Predicted} \\ \multicolumn{1}{c}{} & \multicolumn{1}{c|}{} & \multicolumn{1}{c}{$A$} & \multicolumn{1}{c}{$N$} \\ \hline \multirow[c]{2}{*}{\rotatebox[origin=tr]{90}{Actual}} & $A$ & 224.2 & 45.8 \\[1.5ex] & $N$ & 201 & 1479 \\ \hline & &Sens:&0.80\\ & &Spec:&0.88\\ \\ \end{tabular} } \end{subtable} \end{table} Table \ref{Reaction} shows the reaction times of ABS and R-ABS for different attacks from the dataset. The results are shown in terms of the packages needed for raising the alert of attack. In this table, the label \textbf{RABS} indicates the first exposure to the specific threat, and \textbf{RABS}$^*$ for the second exposure to the same attack. Anomaly detection is faster in ABS than R-ABS. Nevertheless, R-ABS performs two different operations during the first exposure: anomaly detection and anomaly characterization. The learning capability of R-ABS allows a quasi-instantaneous secondary response for a previously characterized threat, where the classifier requires only two network packages for the attack identification in the average case. \begin{table} \caption{Comparison of the Reaction Time} \centering \label{Reaction} \scalebox{1.2}{ \begin{tabular}{ l|c|c|c } \hline \textbf{Attack Name} & \textbf{ABS} & \textbf{RABS} & \textbf{RABS}$^*$ \\ \hline land & 80.5 & 99&2 \\ syslog & 85.1 & 99&1.5 \\ udp-storm & 86.4 & 210.1&2.5 \\ custom$^*$ & 112.7 & 99&2.75 \\ \hline http-tunnel & 109 & 526.1&1.2 \\ sendmail & 117.3 & 657.2&2 \\ \hline sql & 111 & 488.8&2 \\ ffbconfig & 112 &no &1.4 \\ ps & 110 &no &2 \\ \hline \hline \textbf{Average} & 103.6 & 311.3&1.8 \\ \hline \end{tabular} } \end{table} \section{Conclusion and Future Work} Overall, our results suggest that R-ABS provides a significant improvement over the ABS model in terms of quality and classification speed. These advantages are achieved by the learning capabilities and the control of the adaptive conditions for the characterizing agents given by R-ABS. We provide a test of the R-ABS capabilities in the security domain, allowing the comparison with the original ABS model. However, R-ABS is thought of as a generalist tool for anomaly detection and characterization, useful for other domains like complex machine failure management. The exploration of new application domains and the improvement of the different components of R-ABS are the future works for this research. \iffalse \section{Introduction} \label{intro} Your text comes here. Separate text sections with \section{Section title} \label{sec:1} Text with citations \cite{RefB} and \cite{RefJ}. \subsection{Subsection title} \label{sec:2} as required. Don't forget to give each section and subsection a unique label (see Sect.~\ref{sec:1}). \paragraph{Paragraph headings} Use paragraph headings as needed. \begin{equation} a^2+b^2=c^2 \end{equation} \begin{figure} \includegraphics{example.eps} \caption{Please write your figure caption here} \label{fig:1} \end{figure} \begin{figure*} \includegraphics[width=0.75\textwidth]{example.eps} \caption{Please write your figure caption here} \label{fig:2} \end{figure*} \begin{table} \caption{Please write your table caption here} \label{tab:1} \begin{tabular}{lll} \hline\noalign{\smallskip} first & second & third \\ \noalign{\smallskip}\hline\noalign{\smallskip} number & number & number \\ number & number & number \\ \noalign{\smallskip}\hline \end{tabular} \end{table} \fi \bibliographystyle{plainnat}
{'timestamp': '2021-09-14T02:17:12', 'yymm': '2109', 'arxiv_id': '2109.05376', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05376'}
arxiv
\section{Introduction}\label{sec:introduction}} \else \section{Introduction} \label{sec:introduction} \fi \IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file'' for IEEE Computer Society journal papers produced under \LaTeX\ using IEEEtran.cls version 1.8b and later. I wish you the best of success. \hfill mds \hfill August 26, 2015 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \appendices \section{Proof of the First Zonklar Equation} Appendix one text goes here. \section{} Appendix two text goes here. \ifCLASSOPTIONcompsoc \section*{Acknowledgments} \else \section*{Acknowledgment} \fi The authors would like to thank... \ifCLASSOPTIONcaptionsoff \newpage \fi \section{Introduction} This demo file is intended to serve as a ``starter file'' for IEEE Computer Society conference papers produced under \LaTeX\ using IEEEtran.cls version 1.8b and later. I wish you the best of success. \hfill mds \hfill August 26, 2015 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \ifCLASSOPTIONcompsoc \section*{Acknowledgments} \else \section*{Acknowledgment} \fi The authors would like to thank... \section{Introduction} \IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file'' for IEEE journal papers produced under \LaTeX\ using IEEEtran.cls version 1.8b and later. I wish you the best of success. \hfill mds \hfill August 26, 2015 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \appendices \section{Proof of the First Zonklar Equation} Appendix one text goes here. \section{} Appendix two text goes here. \section*{Acknowledgment} The authors would like to thank... \ifCLASSOPTIONcaptionsoff \newpage \fi \section{Introduction}\label{sec:introduction}} \IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file'' for IEEE Computer Society journal papers produced under \LaTeX\ using IEEEtran.cls version 1.8b and later. I wish you the best of success. \hfill mds \hfill August 26, 2015 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \appendices \section{Proof of the First Zonklar Equation} Appendix one text goes here. \section{} Appendix two text goes here. \ifCLASSOPTIONcompsoc \section*{Acknowledgments} \else \section*{Acknowledgment} \fi The authors would like to thank... \ifCLASSOPTIONcaptionsoff \newpage \fi \section{Introduction} \IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file'' for IEEE Communications Society journal papers produced under \LaTeX\ using IEEEtran.cls version 1.8b and later. I wish you the best of success. \hfill mds \hfill August 26, 2015 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \appendices \section{Proof of the First Zonklar Equation} Appendix one text goes here. \section{} Appendix two text goes here. \section*{Acknowledgment} The authors would like to thank... \ifCLASSOPTIONcaptionsoff \newpage \fi \section{Introduction} \IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file'' for IEEE \textsc{Transactions on Magnetics} journal papers produced under \LaTeX\ using IEEEtran.cls version 1.8b and later. I wish you the best of success. \hfill mds \hfill August 26, 2015 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \appendices \section{Proof of the First Zonklar Equation} Appendix one text goes here. \section{} Appendix two text goes here. \section*{Acknowledgment} The authors would like to thank... \ifCLASSOPTIONcaptionsoff \newpage \fi \section{Introduction} \subsection{Motivation} Deploying Machine Learning (ML) for real-world problems causes a number of challenges, e.g., selecting the proper model among a set of candidate models, hyper-parameter tuning, and selecting the dataset's features to feed to ML models. An ML model's performance depends on such initial design decisions, which can be confusing to new users who want to choose the suitable model \cite{mohammadi2019parameter}. These decisions need to be made based on some selection criteria, and are usually based on the model's obtained quality (performance indicator) \cite{neath2012bayesian}. According to the principle of Occam's razor, a model should not be too simple nor too complex so that it can be efficient (in regards to computations) and at the same time capture data patterns, without overfitting \cite{biem2003model, mohammadi2019parameter}. Hyper-parameter tuning is choosing the parameters' values that have a more considerable impact on the ML model's final performance (e.g., accuracy and run-time). Hyper-parameters on an ML model control the convergence of the learning process. Hence, to find an ML models' optimal performance, it is crucial to find the optimal values for hyper-parameters \cite{claesen2015hyperparameter}. Independent from the ML users, obtaining desirable results for their specific dataset can be conducted manual and tedious \cite{sharmaart, yang2020hyperparameter}. This is where Automated ML (AutoML) comes into the picture, to alleviate such burden in an automated way. Automated Hyper-parameter Optimization (HPO) is one of the decisive and primary tasks of AutoML \cite{sui2020bayesian}. In HPO, the challenge is that there exists a large number of possible configurations. However, there is always a trade-off between performance and time. Therefore, there should be a balance in the number of candidates and the resources allocated to them \cite{yang2020hyperparameter}. Population-Based Algorithms (PBAs) have recently gained much attention across fields as they are used for different applications. Swarm intelligence (SI), a type of PBA, is the collective behavior of self-organized and decentralized swarms (such as birds, ants, or bees). The self-organization and division of labor characteristic of swarm intelligence can be observed in bee colonies, so they are ideal for developing intelligent approaches. Among different bee colony algorithms, Artificial Bee Colony (ABC) is the most popular due to its capabilities \cite{karaboga2014comprehensive}. Therefore, in this work, ABC is chosen to tackle large-scale optimization problems (regarding search space) in HPO. \subsection{Objective} \label{sec:ResearchObjective} Manual search and automated exhaustive search among \begin{math}n^{k}\end{math} configurations of hyper-parameters are impractical and time inefficient \cite{yin2016classification}. Manual tuning does not provide reproducibility. Exhaustive search, on the other hand, suffers from dimensionality issues in large search spaces. As such, there has been increased research in HPO to optimize the performance of ML models regarding both accuracy and time. When making decisions, time is of the essence. Hence, many of the black-box optimization models are not a good fit for such optimization problems because they do not consider the function evaluation time \cite{yang2020hyperparameter}. Therefore, proper algorithms should be applied to such a problem to find the optimal set of hyper-parameters. Mohammadi et al. provided different examples of applying PBAs, such as feature extraction, in different domains and encouraged researchers to apply such methods to solve large-scale optimization problems \cite{mohammadi2020evolutionary, mohammadi2020applications}. On the other hand, automated HPO methods may change the final model in comparison to when a model is being trained with default hyper-parameters \cite{zahedi2021search}. Hence, they also provide fairness to research and scientific studies. Our goal is to design and develop an HPO framework to tackle the challenges discussed above in this work. The framework utilizes ABC to minimize the run-time caused by large dimensions of search-space scales, known as Curse of Dimensionality (CoD), and possibly improving the accuracy of the ML model. This framework will assist the predictions for intelligent and real-time educational decision-making and lessen the costs and manual and human efforts. In the literature, ABC has been used to tune the parameters of deep learning algorithms, convolutional neural networks, and least squares support vector machine \cite{badem2018new, ozcan2020human, ozcan2019transfer}. In this paper, a real-world educational dataset is used to build a binary classification model to predict students' success, specifically graduation. Figure \ref{fig:general} shows the general diagram of our experiment. We utilize HyP-ABC to tune the main hyper-parameters of Random Forest (RF), Extreme Gradient Boosting (XGBoost), and Support Vector Machine (SVM). These three models are based on the reports from an earlier study \cite{zahedi2021search} indicating the high tuning-time using exhaustive automated HPO approaches, namely Grid Search (GS) and Random Search (RS). \begin{figure} \centering \includegraphics[width =0.45 \textwidth]{Images/HPO.png} \centering \caption{General framework of the study} \label{fig:general} \end{figure} \subsection{Contribution} \label{sec:contribution} The main contributions of this study are as follows: \begin{enumerate} \item This paper is developing a novel optimization method for three ML algorithms using a modified heuristic optimization algorithm. \item The propsoed HyP-ABC algorithm outperforms the state-of-the-art HPO methods utilized in an existing study in 2021 \cite{zahedi2021search}, in terms of both tuning time and accuracy. \item This paper is the first to investigate the optimization of ML models tailored towards the MIDFIELD dataset \item Unlike most of the previous works that try to address the issues on single ML models, in this work, we explore utilizing the HyP-ABC on three different ML algorithms to tune their hyper-parameters and select the final model among them based on their performance. \end{enumerate} \subsection{Organization of Paper} \label{sec:Organization} The rest of the paper is organized as follows: in section \ref{sec:PBO} we provide an introduction to PBA and a comprehensive explanation of ABC, in section \ref{sec:PBO}. Then, we present the related work regarding hyper-parameter tuning and different automated tuning methods in section \ref{sec:related}. We also cover ABC applications in this section. Section \ref{sec:HPO-ABC} covers hyper-parameter tuning using the ABC approach and the advantages of ABC over other techniques. In section \ref{sec:MABC}, we propose the HyP-ABC algorithm, which is an ABC-based algorithm fitted to HPO problems. The experimental methodology, search space, and dataset are then presented in section \ref{sec:methodology}. Section \ref{sec:results} presents experimental results to demonstrate the performance achievable by the proposed approach. Last, section \ref{sec:conclusion} concludes the paper and discusses future directions. \section{Population-Based Optimization Algorithms} \label{sec:PBO} Population-based optimization algorithms work based on generating and updating individuals in each generation; this continues until the final optimal solution is identified \cite{yazdani2021survey}. These algorithms are based on the interaction between different individuals called food sources to find the near-global optimal solutions. These algorithms garnered much attention because of their excellent performance and are particularly useful to solve optimization problems \cite{pierezan2018coyote}. PBAs include different heuristic algorithms such as EAs, Genetic Algorithms (GAs), Particle Swarm Optimization (PSO), Ant Colony Optimization (ACO), Grey Wolf Optimization (GWO), Fish Swarm Algorithms (FSA), and Artificial Bee Colony (ABC). The main difference between these algorithms is how a population is generated and selected \cite{yao2018taking}. One of the main advantages of these algorithms is that unlike many model-based optimization methods (such as Bayesian optimization), they have the capability of parallelization \cite{hutter2019automated}. Among these algorithms, ABC is one of the most popular methods due to the excellent exploration and exploitation capabilities to find the optimal solution \cite{karaboga2007artificial}. Therefore, ABC was chosen for further exploration in this study to answer HPO challenges. \subsection{Artificial Bee Colony (ABC)} ABC, first defined by Karaboga \cite{karaboga2007powerful}, is one of the most recent and popular swarm intelligence algorithms that simulate honey bees' foraging behavior. In ABC, different groups of bees fly around in an area (search space). The bee colony, in this algorithm, is divided into three groups: 1) employed, 2) onlookers, and 3) scouts. At the initialization stage, a random set of food sources get selected by \textbf{scout bee}, and their amount of nectar is determined. Then scout bees share the nectar information with employed bees. Then the \textbf{employed bees} visit those food sources and choose a new food source in that neighborhood and compare with the current food source. Next, \textbf{onlooker bee} may prefer a food source based on the information employed bees shared with them (nectar amount). The higher the amount of nectar around food increases the chance of getting selected by onlooker bees. Then the onlooker bee chooses a new food source in that neighborhood and makes the comparison. The better food source gets replaced in both employed and onlooker phases. When the bees abandon a food source, the scout bee selects a random food source and gets replaced with the left food source.\\ Employed and onlooker bees both do the \emph{exploration} based on their own experience, leave poor food sources, and move toward better ones through a greedy selection process. However, the difference between these two phases is that a food source may or may not be selected in the onlooker phase. If the food source is not selected, the onlooker bee moves to the next food source, while in the employed phase, each food source is assigned to one employed bee. When a food source exploitation is exhausted and can not be further improved (based on trial limits), the employed bee discards the food source and becomes a scout bee and start \emph{exploration}. The pseudo-code of the original ABC is described in Algorithm \ref{alg:ABC} \cite{karaboga2009comparative}, to show the main steps of the ABC approach. \begin{algorithm}[H] \caption{Implementation of original ABC} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \STATE {Initialize population} \WHILE{Stopping criteria is not met} \STATE {Assign food sources to employed bees} \STATE Place the onlooker bees on the food sources based on the amount of nectar \STATE Send the scouts to different areas to find new food sources \STATE Memorize and update the best food source \ENDWHILE \RETURN Best found food source \end{algorithmic} \label{alg:ABC} \end{algorithm} \section{Related Works} \label{sec:related} \subsection{Hyperparameter Tuning} \label{sec:hyperparameter} GS is a decision-theoretic and brute-force method that searches all the hyper-parameters within a fixed search space. The advantage of this method is that it obtains the optimal solution in a discrete search space \cite{zahedi2021search}. However, it is computationally expensive in large-scale spaces. RS is also a decision-theoretic approach that randomly selects the configurations with limited resources (time or number of iterations). This method works well for search spaces containing continuous search spaces. However, luck plays a part in this method, and given more resources increases the chance of getting better results \cite{zahedi2021search}. Unlike GS and RS, Bayesian Optimization (BO) \cite{eggensperger2013towards} prevents evaluating many of the unnecessary configurations based on the evaluations of the previous steps. However, since BS methods work sequentially to balance the exploration and exploitation, they are complicated to parallelize. For some models, such as tree-based models (RF and XGB), the number of main hyper-parameters and their ranges are higher than other ML models. This leads to large search space scales, making them the most complex ML models to be tuned \cite{hutter2019automated}. Furthermore, since different ML algorithms have different types of hyper-parameters (continuous, integer, and categorical), they should be treated differently in tuning processes \cite{decastro2019effect}. Hence, they are the main focus of this study. For the ML models in this study, ABC is selected. It has a reasonable convergence rate and enables parallel executions to improve tuning time, particularly for models that often require massive training time. Some other techniques, like GA, can also be used, but they may cost more time than ABC since it is difficult to parallelize these techniques. Also, techniques such as PSO have a reasonable convergence rate; however, the PSO technique has a higher chance of sticking into local optimums. \begin{table*}[ht] \centering \caption{Comparison of GA, PSO and ABC algorithms} \label{tab:HPOcompare} \def1.2{1.5} \begin{tabular}{|c|c|c|c|} \hline \textbf{Method} & \textbf{Advantages} & \textbf{Disadvantages} & \textbf{\makecell{Time Complexity}}\\ \hline \textbf{GA} & \makecell{~~\llap{\textbullet}~~ No proper initialization is needed} & \makecell{~~\llap{\textbullet}~~ Poor with parallelization\\ ~~\llap{\textbullet}~~ Introduces new parameters\\ ~~\llap{\textbullet}~~ Slow Convergence} & \makecell{\begin{math}O(n^{2})\end{math}}\\ \hline \textbf{PSO} & \makecell{~~\llap{\textbullet}~~ Enables parallelization ~~\llap{\textbullet}~~ Faster convergence} & \makecell{~~\llap{\textbullet}~~ Needs proper initialization\\~~\llap{\textbullet}~~ May stuck in local optimum} & \makecell{\begin{math}O(n\log{n})\end{math}} \\ \hline \textbf{ABC} & \makecell{~~\llap{\textbullet}~~ Enables Parallelization~~\llap{\textbullet}~~ Higher efficiency \\~~\llap{\textbullet}~~ Balances exploration \& exploitation \\~~\llap{\textbullet}~~ More likely to find global optimum} & \makecell{~~\llap{\textbullet}~~ Need proper initialization \\~~\llap{\textbullet}~~ Slower convergence than PSO} & \makecell{\begin{math}O(n)\end{math}} \\ \hline \end{tabular} \end{table*} \subsection{ABC Applications} \label{sec:relatedABC} In this section, we cover some of the previous studies of ABC for different optimization problems. one of the important trend that ABC started in \cite{mohammadi2014image} by proposing IFAB, an approach to apply ABC to distinguish between clean and unclean images. The authors technically applied ABC by converting the ABC into a way it works best for discrete problems. Moreover, Sarac Essiz and Oturakci developed a comparative analysis. They explored the effects of the ABC-based feature selection algorithm \cite{xu2020duplicationsha} to eliminates non-informative features on the classification performance of a cyberbully detection problem. They also showed that their method has a better performance than some conventional methods such as information gain, Relief, and chi-square \cite{sarac2021artificial} Amar and Zeraibi \cite{amar2018application}, combined ABC and Support Vector Regression (SVR) to predict minimum miscibility pressure and improve the oil recovery process. In their study, ABC was used to find the best hyper-parameters of the SVR model. In another study, Dokeroglu et al. developed a hybrid ABC optimization algorithm for the quadratic assignment problem using Tabu search to simulate exploration and exploitation phases \cite{dokeroglu2019artificial}. The results showed that an ABC performs well for most quadratic assignment problems and can compete with other state-of-the-art meta-heuristic algorithms existing in the literature. Choong et al. utilized a modified choice function for the ABC algorithm. This algorithm adjusts the neighborhood search performed in the employed and onlooker phases. The results showed that the modified choice function brought advantages to the search process \cite{chang2018solving}. Mohammadi et al. provided a comprehensive review of evolutionary-based image processing on real-time processing in universal image steganalysis and detected hidden messages in images. Since training ML models is time-consuming, the authors argued that the use of algorithms such as the ABC algorithm is of great benefit to solve NP-hard problems caused by CoD \cite{mohammadi2019evolutionary}. In \cite{mala2021hybrid}, the authors proposed two algorithms to modify two steps of the original ABC. The first algorithm was to employ neural network initialization, and the second algorithm utilized stochastic gradient descent in the employed phase of ABC to improve the convergence. The authors examined the performance of the modified ABC on three benchmark datasets and observed promising results. In another study, Zhao et al. performed a comparative analysis that proposed a modified version of ABC to improve the performance of SVM classification using parameter optimization. The proposed method utilized chaotic sequences for the initialization step. They also defined an adaptive step size for the neighborhood search to boost the algorithm convergence. The modified ABC algorithm was examined to perform classification on two hyper-spectral images. The authors then compared the results with three other PBAs and observed the superiority of the ABC method over the rest of the algorithms regarding both performance and efficiency \cite{zhao2020improvement}. Pandiri and Singh \cite{pandiri2018hyper} developed a hyper-heuristic-based artificial bee colony algorithm for the k-Interconnected multi-depot multi-traveling salesman problem (k-IMDMTSP). The authors stated that due to the parameter values, it is impossible to have a unique algorithm that outperforms the rest of the algorithms emanating from k-IMDMTSP. Hence, they leveraged a hyper-heuristic-based ABC algorithm for this problem. The authors presented an encoding scheme to be used inside the algorithm. The experimental results for this study exhibited smaller search space than previous encoding schemes, yet they performed better than other approaches existing in the literature regarding quality and run-time. In another study, Mazini et al. took advantage of the parameters regulation method of ABC for feature selection to propose a reliable hybrid method to detect anomaly network-based intrusion. Experimental results on an unbalanced network traffic dataset exhibited significant improvement in performance and detection rate compared to other intrusion detection systems in various scenarios \cite{mazini2019anomaly}. Gunel and Gor developed a modified ABC algorithm to solve initial value problems. To define a mutation operator, the authors in this study used a dynamically constructed hyper-sphere to generate new food solutions; This method improved the exploitation ability of ABC. In this approach, the best solution was used to define the mutation operator. The solutions for the differential equations were yielded through training neural networks applying the modified ABC \cite{gunel2019modification}. In \cite{sayed2019parameters}, Sayed et al. used an ABC-based approach to tune the hyper-parameter of ABC to improve the learning performance. In this study, the authors adjust the main hyper-parameter of the SVM model to enhance the accuracy. The proposed method was examined on six different datasets and was also compared with popular swarm algorithms. The experimental results showed promising results compared with the mentioned algorithms. Agrawal also proposed an extended optimization of ABC using some features of the Gaussian ABC scheme to tackle some of the disadvantages of the original ABC, such as a slow convergence. The proposed method was used to adjust the exploration and exploitation phases. They examined the proposed approach on some benchmark datasets and observed that the proposed method outperformed the original ABC in most experiments \cite{agrawal2020modified}. \section{Hyper-parameter Optimization using ABC} \label{sec:HPO-ABC} There are different optimization problems in multiple fields. To such problems, there exist classical approaches and heuristic approaches. Classical techniques are not efficient enough in solving optimization problems. This is primarily due to dimensionality. Heuristic approaches such as genetic algorithms and evolutionary algorithms do not suffer from many of the drawbacks of classical methods. ABC is a stochastic, population-based optimization technique and belongs to the family of swarm intelligence techniques. ABC is inspired by social interactions in honeybees and has recently garnered much success in different applications. It is as simple as some other swarm techniques such as PSO and is beneficial for NP-hard problems. Looking for the best hyper-parameter in the hyper-parameters search space is also an NP-hard problem with a time-complexity of \begin{math}O(n^{k})\end{math}. Among heuristics, ABC has shown more encouraging behavior. Hence, ABC is being explored in this study to find the best hyper-parameters of ML algorithms. This study was undertaken specifically to tackle the challenge regarding the high tuning time authors mentioned in an earlier work \cite{zahedi2021search} regarding models such as RF, XGBoost, and SVM. \label{sec:ABC} \begin{figure*}[b] \centering \includegraphics[width =0.60 \textwidth]{Images/POA.png} \centering \caption{General scheme of the HyP-ABC} \label{fig:POA} \end{figure*} \subsection{Time Complexity} \label{sec:time} Table \ref{tab:HPOcompare} summarizes each of these methods' advantages and disadvantages along with their time complexity. We cover the time complexity of our method in the next section. As shown in Table \ref{tab:HPOcompare}, the time complexities of the methods mentioned in the previous section are summarized. ABC requires a one-pass scan for each of the initialization, employed, and onlooker phases. Also, the ABC algorithm can repeat based on a maximum number of iterations defined for the algorithm. The time complexity for each of the neighborhood searches is \begin{math}O(N*D)\end{math} where N is the number of population, and $D$ is the dimensionality. Therefore, the complexity of ABC can be presented as \begin{math}O(3N*D*I_{max})\end{math} where $I_{max}$ is the expected maximum number of iterations. Since $D$ and $I_{max}$ are constant the overall time complexity of the HyP-ABC is linear (\begin{math}O(N)\end{math}). Hence, this research is based on an ABC-based approach. \subsection{Advantages of ABC} BO \cite{eggensperger2013towards}, GA \cite{lessmann2005optimizing} and PSO \cite{guo2008novel} are among the common approaches used for HPO problems. There are various features that ABC has which make it efficient in solving optimization problems, especially for hyper-parameter tuning are as follows: \begin{enumerate} \item The underlying concept and implementation are easy and offer high accuracy. \item Although almost all meta-heuristic make use of randomization to have global research as well as local search, ABC balances the exploration and exploitation steps (local and global search) \cite{karaboga2009comparative}. This enables the algorithm to search for various parts of the search space. Randomization also helps the model not get stuck in the local minimum and complete the global search. This is despite BO or PSO methods that may stick to a local optimum and which fail to reach a global optimum \cite{yang2020hyperparameter}. \item Parallelization is one the advantages of PBA because each population can be assessed on one machine \cite{hutter2019automated}, while sequential methods such as BOs and GAs are challenging to parallelize since solutions are dependant on each other \cite{decastro2019effect}. \item Some PBA methods such as GA have some additional hyper-parameters (crossover and mutation probability, population size, number of generations, crossover, mutation, and selection operators) to tune; therefore, GA has lower convergence speed \cite{lessmann2005optimizing}. Having fewer parameters to be tuned by the user is one of the advantages of methods such as PSO and ABC. \end{enumerate} \subsection{General objective of study} Many optimization problems, including hyper-parameter tuning of ML algorithms, all or some of the hyper-parameter are discrete. The schematic objective of HyP-ABC is shown in Figure \ref{fig:POA}. As shown in Figure \ref{fig:POA}, the vectors of hyper-parameters could consist of discrete (integer and categorical) and/or continuous (float) values. Solving these problems is even more challenging than the problems with only continuous variables. Since the basic ABC is only applicable to continuous problems, proper strategies should be adopted to make them applicable to discrete or combinatory problems. Therefore we need to modify the original ABC to adopt it to HPO problems. The first step is generating the initial population. Each sample should be described as a vector, including a set of hyper-parameters. This step is done by a {\textbf{scout bee}}. Corresponding to each of the vectors, we have an objective function produced after training the ML model (accuracy of the model) and a fitness function. The fitness function is calculated based on the objective function. After the population is generated, each vector is assigned to one \textbf{employed bee}. The employed bee generates a new vector of hyper-parameters in the neighborhood, meaning that only one random hyper-parameter of the current vector changes based on some functions being applied on the same hyper-parameter of another vector (neighbor) in the population. If the new vector has a better fitness, it gets replaced with the current vector. In the mutation step, \textbf{onlooker bees} start operating. They calculate the quality of each vector. Each of these vectors may or may not get selected. The higher the quality of the vector, the higher the probability of it being selected. If a vector is selected, the onlooker bee generates a new vector of hyper-parameter in the vicinity and starts assessing the new vector by comparing its fitness with the previous vector. If the new vector has a better fitness, it gets replaced with the previous vector (similar to the employed bee phase). In the next step, an exhausted vector of hyper-parameters (the vector that had the chance to improve the fitness but did not) is selected and replaced with a random vector generated by the scout bee. Unlike the vectors generated in employed and onlooker phases, the new vector consists of randomly generated values for all hyper-parameters. This phase helps the algorithm not to stick to the local optimum. If stopping criteria are met at any of the above phases, the algorithm stops and returns the optimal performance of the ML model, and if not, the process repeats until stopping criteria are met. \section{HyP-ABC: Modified ABC Algorithm}\label{sec:MABC} \subsection{Converting continuous ABC to combinatory version} As we mentioned in the previous section, we face a combination of hyper-parameters' types while original ABC is only applicable to continuous problems. Also, the range of variables in basic ABC is the same for all the dimensions. Therefore proper strategies should be adopted to make it applicable to discrete or combinatory problems. There are different strategies used for tackling discrete optimization in swarm optimization \cite{ziari2012integrated, wu2008feeder,durgut2017artificial,chang2018solving}. Rounding off is one of the most common approaches to tackle discrete variables. In this approach, the integer variables are treated similarly as continuous variables during the optimization process. However, in most studies, when the optimization process is done, the variables are rounded off to the nearest integer number. Simplicity and low computational cost are among the main advantages of this method. However, entering impossible regions and high variation of fitness value of rounded value and the original value are among the disadvantages of this method. In this study, we use a function to adjust each vector's member based on their type and in each iteration. Hence, we yield precise accuracy with the very same hyper-parameters at the end of the optimization process. Hyper-parameters have different types (discrete, categorical, continuous), and therefore should be treated differently in each iteration of generating food sources. Instead of using strings for categorical variables in the population generation phase, we encode them and generate integer numbers (and treat them as integer variables afterward). We then convert them again to corresponding strings after the optimization process is done and just before training the model. From this step on, if the selected hyper-parameter's type by employed/onlooker is an integer (or categorical), the newly generated food source is modified to an accepted vector by converting that hyper-parameter to the closest integer number. For continuous variables, the algorithm performs similarly to the original ABC. Algorithm \ref{alg:hypabc} shows the steps for the HyP-ABC we applied in this study. We also added an additional step to check if the updated food source equals the current food source. This is specifically useful when the categorical hyper-parameter is the variable selected to be changed due to having fewer options. Hence the HyP-ABC prevents training the ML model with the same hyper-parameters and tries to find a different food source, and the objective function is not calculated for a configuration that is already evaluated. For binary categorical variables (such as criterion in RF), we use the XOR operator to flip the value of the hyper-parameter. \begin{algorithm}[H] \caption{Hybrid artificial ABC algorithm} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \REQUIRE $Population\_number$, $Search\_Space$ \ENSURE Best food source identified\\ \STATE Call a function to create an initial population X{i} based on the hyper-parameters type and range \STATE Set the trail=0 for all food sources \WHILE{Stopping criteria is not met} \FOR{ $i$ to $Population\_number$} \STATE Employed bee generate a new food \(N{i}\) source in neighborhood and modify the new food source to an accepted food source \(M{i}\) (accepted type within range) \IF{ \(M{i}\) $==$ \(X{i}\) } \STATE Move to step 5 \ENDIF \STATE Train the ML model with the modified food source \IF{ \(f(M{i})\) $<$ \(f(X{i})\) } \STATE \(X{i}\) = \(M{i}\) \STATE Reset trial \ELSE \STATE Increment trial \ENDIF \ENDFOR \FOR{ $i$ to $Population\_number$} \IF{ \((rand{(0,1)})\) $>$ \((P{i})\) } \STATE Onlooker bee generate a new food source in neighborhood \(N{i}\) and then modify the new food source to an accepted food source \(M{i}\) \IF{ \(M{i}\) $==$ \(X{i}\) } \STATE Move to step 5 \ENDIF \STATE Train the ML model with the updated food source \IF{ \(f(N{i})\) $<$ \(f(X{i})\) } \STATE \(X{i}\) = \(M{i}\) \STATE Reset trial \ELSE \STATE Increment trial \ENDIF \ELSE \STATE Onlooker disregard the food source and move to the next food source \ENDIF \ENDFOR \STATE Memorize and update the best food source \IF {trial $>$limit} \STATE Scout bee generates a new food source \ENDIF \ENDWHILE \RETURN Best found food source \end{algorithmic} \label{alg:hypabc} \end{algorithm} In all phases, values outside the ranges defined for the hyper-parameters get replaced with lower bound or higher bound values before training the model. Stopping conditions in this algorithm are when the desired accuracy is reached or when the algorithm evaluated a specific number of evaluations. In this experiment, we set the maximum number of evaluations equal to the number of iterations in RS to have a fair comparison of HPO methods. \subsection{HyP-ABC Steps} For the random initialization of the population. Each food source is a vector of hyper-parameters, $X_i$, with the length of $D$, where $D$ is the dimension of vector or the number of hyper-parameters. Unlike original ABC, in HyP-ABC, each vector member may have discrete or continuous type: \begin{equation} X_{i,j}=x_{min,j}+rand(0,1)(x_{max,j}-x_{min,j}) \end{equation} Where $X_{i,j}$ is each element in the vector and $x_{max,j}$ and $x_{min,j}$ are upper-bound and lower-bound for a specific hyper-parameter ($j$). Then, each vector is assigned to an employed bee. The employed bee generate a new food source $N_{i,j}$ in that neighborhood by changing only one of the hyper-parameter using below formula: \begin{equation} N_{i,j}=x_{i,j}+rand(-1,1)(x_{i,j}-x_{k,j}) \end{equation} Where $x_{k,j}$ represent a value in the neighborhood of current food source and for the same dimension. Therefore $k$ and $i$ are different. Then the fitness of the $N_{i}$ and $X_{i}$ are compared. In case the fitness of $N_{i}$ is better, it get replaced with $X_{i}$ and therefore becomes a new member of the population. Fitness is calculated from the objective function (classification accuracy): \begin{equation} fit_{i}= \begin{cases} \frac{1} {1+ f_{i}}, & \text{$f_{i}$ $\geq$ 0} \\ {1+ abs(f_{i})}, & \text{$f_{i}$ $<$ 0} \end{cases} \end{equation} When employed bees complete the search, onlooker bees receive information from employed bees and may select a vector based on selection probability values. The vector with higher quality (higher selection probability) has a better chance to get selected by onlooker bees. In this phase, roulette wheel selection, as shown in the below formula, is utilized to calculate the probabilities. \begin{equation} P_{i}=\frac{f_{i}}{\sum_{j=1}^{PN}(f_{j})} \end{equation} Where $f_{i}$ is the fitness value for the \(i\)th food source and $PN$ is the population number. Next, scout bees start explorations searching random configurations of search space without using experience or memorizing the locations. They do not use greedy selection when exploring for new solutions. Exploration by scout bees is through below formula: \begin{equation} X_{i,j}=x_{min}+rand(0,1)(x_{max}-x_{min}) \end{equation} \section{Experimental Methodology} \label{sec:methodology} In this section, we describe our methodology for this study's experiment. The process is performed in several consecutive phases. It includes data pre-processing, feature engineering, leveraging ML models, and optimization steps. The Hyp-ABC algorithm proposed in this study is replaced with the HPO methods utilized in our most recent work in 2021 \cite{zahedi2021search}. \subsection{Data pre-processing and feature Engineering} Data pre-processing is a technique used to transform the raw data into an understandable format for ML algorithms. It includes data cleansing, data normalization, and data reduction. For data cleansing, we removed the features with more than 60\% percent of the values missing. Data normalization is also a method to standardize the data when the different features' values vary widely. \textit{StandardScaler} from Scikit-learn library was used for scaling the input data. We filtered the data in the data reduction step and included only the target population, students from computing fields. In the feature engineering step, one-hot encoding -encoding categorical variables to binary variables for each unique category- is used. \subsection{Hyper-parameter tuning} Tuning hyper-parameters is essential to yield the best performance of an ML model. Due to the varied nature of the hyper-parameters in different ML models, we implement a HyP-ABC to tune the hyper-parameters of three ML models. HyP-ABC is replaced and compared with an automated HPO method performed in our most recent study in 2021 \cite{zahedi2021search}. Algorithm \ref{alg:GRS} shows the previous work process, along with the changes we made to improve the tuning process regarding run-time and performance. Figure \ref{fig:ABC} shows the overall schematic process of our framework. \begin{figure*} \centering \includegraphics[width =0.750\textwidth]{Images/ABC.png} \centering \caption{The schematic process of the study} \label{fig:ABC} \end{figure*} \newcommand\redsout{\bgroup\markoverwith{\textcolor{red}{\rule[0.5ex]{2pt}{0.4pt}}}\ULon} \begin{algorithm}[b] \caption{Automated optimization in a previous work \cite{zahedi2021search}} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \REQUIRE \(List_{ML}\) of models (DT, RF, NB, LR, XGB, SVM, KNN) \& raw dataset \ENSURE Best model along performance and optimal architecture \STATE Call PreProcessing \FOR {every model in the \(List_{ML}\)} \STATE \redsout{Call $GS$ \& $RS$} $\Rightarrow$ \textcolor{red}{Call Hyp-ABC} \STATE { \redsout{\textbf{if} GS.Acc larger than RS.Acc \textbf{then}}} \STATE \textcolor{red}{{\textbf{if} ABC.ACC larger than reported {(GS \& RS)}.Acc \textbf{then}}} \STATE \redsout{Replace model, GS BestHPs} \STATE $\Rightarrow$ \textcolor{red}{{Replace Model, ABC BestHPs}} \STATE {\textbf{end if}} \STATE {\redsout{\textbf{if} RS.Acc larger than GS.Acc \textbf{then}}} \STATE \hspace{10pt}\redsout{Replace model, RS BestHPs} \STATE \redsout{\textbf{end if}} \ENDFOR \RETURN FinalModel, BestHP, Final.Acc, TuningTime \end{algorithmic} \label{alg:GRS} \end{algorithm} Since RF, XGBoost, and SVM are computationally highly expensive regarding tuning time when using automated HPO methods \cite{zahedi2021search}, they are selected to be explored in this study. The tuning time complexity in these three models is mainly due to the model's complexity and the number, the range, and the type of hyper-parameters. \section{Experimental Results} \label{sec:results} In this section, we discuss the dataset, evaluation metrics, and experimental results in depth. \subsection{Dataset} In this study, we used a real-world educational data, Multiple-Institution Database for Investigating Engineering Longitudinal Development (MIDFIELD)\cite{ohland2004creation}, to predict students' graduation. This dataset is a unit-record longitudinal dataset for undergraduate students from 16 universities. MIDFIELD contains all the information that appears in students' academic records, including demographic data (sex, age, and race/ethnicity) and information about major, enrollment, graduation, and school and pre-school performance. We used a reduced version of MIDFIELD, including only students majoring in computing fields (with CIP=11). This version of the MIDFIELD dataset is used for a binary classification problem and has 4532 samples with 91 features. \subsection{Metrics for Performance Evaluation} The evaluation metrics used in this experiment to evaluate the performance of the classification and the proposed framework are accuracy and execution time. Accuracy is the ratio of the number of correct predictions to the total number of predictions. This metric is used since the dataset is balanced and the number of samples belonging to each class is almost equal. We also used cross-validation to partly reduce or prevent over-fitting. This helped to find a stable optimum that is suitable for all the subsets of the dataset instead of only a singular validation set \cite{hutter2019automated}. Table \ref{tab:cls-abc} summarizes the results and shows the accuracy of different HPO methods among different ML models. It is important to note that cross-validation also increases the tuning time by the number of folds. Therefore, we used 3-fold cross-validation to avoid very high tuning time. However, we parallelized the cross-validation process to reduce the impact of cross-validation on execution time. To extend the experiment, we also separated the MIDFIELD dataset into train and test sets and repeated the experiment. The train set contains 80\% of the dataset, and the test set includes 20\% of the dataset. In this experiment, the Scikit-learn and XGBoost libraries were used to leverage ML models. All experiments were conducted using Python 3.8 on Amazon Web Services (AWS) servers with four v-CPUs up to a 3.0 GHz scalable processor and 16 GB RAM. \begin{figure*}[ht] \begin{subfigure}[b]{0.45\textwidth} \begin{tikzpicture}[scale=0.8] \begin{axis}[ width=0.43\paperwidth, height=0.31\paperwidth, major x tick style = transparent, ymin=87, ybar=3*\pgflinewidth, bar width=10pt, ymajorgrids = true, ylabel = {Accuracy (\%)}, symbolic x coords={SVM,RF,XGBoost}, xtick=data, ytick = {87.5,88,88.5}, enlarge x limits=0.2, legend cell align=center, legend style={ at={(1,0)}, anchor=south east, column sep=1pt, nodes={scale=0.7, transform shape}, } ] \addplot[style={bblue,fill=bblue,mark=none}] coordinates {(SVM,87.93) (RF, 87.57) (XGBoost,87.97)}; \addplot[style={rred,fill=rred,mark=none}] coordinates {(SVM,88.00) (RF, 88.74) (XGBoost,88.64)}; \addplot[style={ggreen,fill=ggreen,mark=none}] coordinates {(SVM,88.00) (RF, 88.77) (XGBoost,88.84)}; \legend{NP=20,NP=50,NP=100} \end{axis} \end{tikzpicture} \caption{Effect of number of food sources in HyP-ABC on accuracy} \label{a} \end{subfigure} \centering \begin{subfigure}[b]{0.45\textwidth} \begin{tikzpicture}[scale=0.8] \begin{axis}[ width=0.43\paperwidth, height=0.31\paperwidth, major x tick style = transparent, ymin=0, ymax=100, ybar=3*\pgflinewidth, bar width=10pt, ymajorgrids = true, ylabel = {Execution Time (Hours)}, symbolic x coords={GS, RS, HyP-ABC}, xtick=data, ytick = {10,25,40,55,70,85}, enlarge x limits=0.2, legend cell align=center, legend style={ at={(1,0.75)}, anchor=south east, column sep=1pt, nodes={scale=0.7, transform shape}, } ] \addplot[style={cherryRed,fill=cherryRed,mark=none}] coordinates {(GS,97.47) (RS, 26.33) (HyP-ABC,34.15) }; \addplot[style={emerald,fill=emerald,mark=none}] coordinates {(GS,64.55) (RS, 10.85) (HyP-ABC,1.55) }; \addplot[style={orange,fill=orange,mark=none}] coordinates {(GS,68.97) (RS, 29.60) (HyP-ABC,29.22) }; \legend{SVM,RF,XGBoost} \end{axis} \end{tikzpicture} \caption{Comparison of execution times among HPO methods} \label{a} \end{subfigure} \caption{Comparison of Execution Time and Accuracy Among Different ML Models Using 3-fold Cross Validation} \label{fig:cv} \end{figure*} \begin{figure*}[ht] \begin{subfigure}[b]{0.45\textwidth} \begin{tikzpicture}[scale=0.8] \begin{axis}[ width=0.43\paperwidth, height=0.31\paperwidth, major x tick style = transparent, ymin=87, ybar=3*\pgflinewidth, bar width=10pt, ymajorgrids = true, ylabel = {Accuracy (\%)}, symbolic x coords={SVM,RF,XGBoost}, xtick=data, ytick = {87.5,88,88.5}, enlarge x limits=0.2, legend cell align=center, legend style={ at={(1,0)}, anchor=south east, column sep=1pt, nodes={scale=0.7, transform shape}, } ] \addplot[style={bblue,fill=bblue,mark=none}] coordinates {(SVM,87.80) (RF, 88.71) (XGBoost,88.60) }; \addplot[style={rred,fill=rred,mark=none}] coordinates {(SVM,87.86) (RF, 88.74 ) (XGBoost,88.70)}; \addplot[style={ggreen,fill=ggreen,mark=none}] coordinates {(SVM,87.85) (RF,88.79 ) (XGBoost,88.75) }; \legend{NP=20,NP=50,NP=100} \end{axis} \end{tikzpicture} \caption{Effect of number of food sources on the accuracy} \label{b} \end{subfigure} \centering \begin{subfigure}[b]{0.45\textwidth} \begin{tikzpicture}[scale=0.8] \begin{axis}[ width=0.43\paperwidth, height=0.31\paperwidth, major x tick style = transparent, ymin=0, ymax=70, ybar=3*\pgflinewidth, bar width=10pt, ymajorgrids = true, ylabel = {Execution Time (Hours)}, symbolic x coords={SVM,RF, XGBoost}, xtick=data, ytick = {5,15,25,35,45,55,65}, enlarge x limits=0.2, legend cell align=center, legend style={ at={(1,0.75)}, anchor=south east, column sep=1pt, nodes={scale=0.7, transform shape}, } ] \addplot[style={cherryRed,fill=cherryRed,mark=none}] coordinates {(SVM,23.95) (RF, 2.37) (XGBoost,4.07) }; \addplot[style={emerald,fill=emerald,mark=none}] coordinates {(SVM,53.05) (RF, 09.07) (XGBoost,5.85)}; \addplot[style={orange,fill=orange,mark=none}] coordinates {(SVM,62.57) (RF, 3.18) (XGBoost,4.23) }; \legend{NP=20,NP=50,NP=100} \end{axis} \end{tikzpicture} \caption{Effect of number of food sources on execution times} \label{b} \end{subfigure} \caption{Comparison of Execution Time and Accuracy Among Different ML Models Using a 80:20 Ratio Test/Train Set} \label{fig:ncv} \end{figure*} \begin{table}[b] \centering \caption{Performance evaluation of utilizing HPO methods to the ML classifiers on the MIDFIELD dataset (cv=3)} \label{tab:cls-abc} \def1.2{1.5} \begin{tabular}{|c|c|c|c|} \hline \textbf{} & \multicolumn{3}{c|}{Accuracy (\%)}\\ \hline \textbf{HPO Method / ML Classifier} & \textbf{RF} & \textbf{XGBoost} & \textbf{\makecell{SVM}}\\ \hline \textbf{\makecell{GS}} & \makecell{$>$ 1 year} & \makecell{$>$ 1 year} & \makecell{87.99}\\ \hline \textbf{\makecell{GS \cite{zahedi2021search} \\(minimized search space)}} & \makecell{88.34} & \makecell{88.33} & \makecell{NA} \\ \hline \textbf{RS \cite{zahedi2021search}} & \makecell{88.37} & \makecell{88.80} & \makecell{87.43}\\ \hline \textbf{HyP-ABC} & \makecell{\textbf{88.77}} & \makecell{\textbf{88.84}} & \makecell{\textbf{88.00}}\\ \hline \end{tabular} \end{table} \subsection{Results} The above-described HyP-ABC is developed to achieve the best hyper-parameters of SVM, RF, and XGBoost algorithms in an efficient time. Figure \ref{fig:cv} shows the comparison of tuning time and accuracy among the three ML models. Figure \ref{fig:cv}(a) shows the impact of the different numbers of population on the accuracy; As can be seen, the more the number of food sources, the better the accuracy. Figure \ref{fig:cv}(b) also shows that the execution time for all the ML models decreased in comparison to the GS method. Regarding RS, the execution time has also decreased or did not change except for the SVM model. The slight differences in tuning time for RS and HyP-ABC are mainly due to the maximum number of evaluations equal that is defined as equal to the number of iterations in RS. That being said, even if execution time remained stagnant for some cases but the accuracy of the model has been improved, which is promising. It is important to note that for RF and XGBoost algorithms, the GS tuning time considering all the configurations leads to a tuning time of more than years. This estimation was calculated from the average tuning time for each configuration from the RS experiment. Therefore the experiment for the GS method is implemented using a reduced search space with steps of five to make the experiment feasible. As for the performance of the proposed method, the overall accuracy of all the ML models has increased after hyper-parameter tuning using HyP-ABC. Therefore, the HyP-ABC method outperformed the previous HPO methods from the most recent work, and more importantly, the tuning time has decreased. This is due to the fact that the ABC method in general, unlike GS and RS, is a model-based method and has a methodical way of moving toward the close to an optimal solution. Also, among all the models, XGBoost had the best accuracy score. Hence, XGBoost is the final model to be used on the MIDFIELD dataset in this study. \begin{comment} \begin{table}[ht] \centering \caption{Performance evaluation of utilizing HPO methods to ML classifiers on the MIDFIELD (80:20 ratio train/test sets)} \label{tab:nvc} \def1.2{1.5} \begin{tabular}{|c|c|c|} \hline \textbf{Classifier} & \textbf{\makecell{Best Accuracy (\%)}} & \textbf{\makecell{Execution Time}}\\ \hline \textbf{\makecell{SVM}} & \makecell{87.86} & \makecell{2 days, 14:34:54} \\ \hline \textbf{RF} & \makecell{88.80} & \makecell{07:04:10} \\ \hline \textbf{XGBoost} & \makecell{{88.75}} & \makecell{08:42:45} \\ \hline \end{tabular} \end{table} \end{comment} \begin{comment} \begin{figure} \caption{Execution time comparison with previous methods} \vspace{5pt} \begin{tikzpicture}[trim axis right] \pgfplotstableread[col sep=&, header=true]{ description &SVM &RF &XGBoost GS &97.47 &64.55 &68.97 RS &26.33 &1.85 &29.60 HyP-ABC. &34.15 &1.55 &29.22 }\datatableentry \begin{axis}[ enlarge y limits ={value=0.1,upper}, enlarge x limits ={value=0.1}, width=0.43\paperwidth, height=0.3\paperwidth, xtick=data, ymin=-5, ytick = {20,50,80,110}, xticklabels ={ GS, RS, Hyp-ABC}, xtick pos=bottom, x tick label style={rotate=-3,anchor=north,font={\small}}, ymajorgrids = true, ylabel=Execution Time (Hours), ylabel style={yshift=-0.6cm}, xlabel=HPO method, legend style={font={\small}, legend pos=outer north east,legend cell align=top, at={(0.5,1)},anchor=north}, legend columns=3, every axis plot/.append style={ultra thick} ] \addlegendentry{SVM}; \addplot [color=red, thick] table [y=SVM, x expr=\coordindex] {\datatableentry}; \addlegendentry{RF}; \addplot [color=blue, dotted, ultra thick] table [y=RF, x expr=\coordindex] {\datatableentry}; \addlegendentry{XGBoost}; \addplot [color=green, dashed, ultra thick] table [y=XGBoost, x expr=\coordindex] {\datatableentry}; \end{axis} \end{tikzpicture} \label{fig:CT} \end{figure} \begin{figure} \caption{Food sources effect for the accuracy \textcolor{blue}{random numbers}} \begin{tikzpicture} \begin{axis}[ width = 0.45*\textwidth, height = 4cm, major x tick style = transparent, ymin=80.0, ybar=3*\pgflinewidth, bar width=9pt, ymajorgrids = true, ylabel = {Accuracy (\%)}, xlabel = {Food Sources}, symbolic x coords={2,5,10,20,40}, ytick = {70,75,80,85,90}, scaled y ticks = false, enlarge x limits=0.1, legend cell align=left, legend style={ at={(1,0)}, anchor=south east, column sep=1pt, nodes={scale=0.40, transform shape}, } ] \addplot[style={bblue,fill=bblue,mark=none}] coordinates {(2,88.09) (5, 80.59) (10,84.45) (20,85.16) (40,99.66) }; \addplot[style={rred,fill=rred,mark=none}] coordinates {(2,85.49) (5, 87.72) (10,87.99) (20,88.33) (40,84.89) }; \addplot[style={ggreen,fill=ggreen,mark=none}] coordinates {(2,85.49) (5, 87.45) (10,87.43) (20,88.82) (40,84.89) }; \legend{SVM,RF,XGBoost} \end{axis} \end{tikzpicture} \label{fig:pop-num} \end{figure} \end{comment} \begin{comment} \textbf{Notes:} \begin{enumerate} \item ABC algorithm delivers more accurate optimization than PSO does, but it suffers from delayed convergence. On the other hand, PSO is faster; but its accuracy is relatively inferior. So, why not PSO if the goal is minimizing tuning time. \item To improve the performance of ABC in terms of convergence, new neighbor production mechanisms can be proposed. Also, New strategies can be described for scouts or onlookers production phase \cite{karaboga2014comprehensive}. \item Since ABC does not use an operator like crossover as employed in GA or DE. The distribution of good information between solutions is not at a required level. This causes the convergence performance of ABC for a local optimum to be slow. \end{enumerate} \end{comment} \section{Conclusion and Discussions} \label{sec:conclusion} In this paper, a modified evolutionary optimization algorithms for hyper-parameter tuning in ML models, referred to as HyP-ABC, was proposed to enable hyper-parameter tuning of the conventional ML classifiers. We carried out the experiment using the MIDFIELD dataset. The behavior of HyP-ABC has been explored under a different number of populations, and the accuracy and execution time of the HyP-ABC has been compared with HPO methods in an earlier study. Experimental results verified that HyP-ABC outperforms the tuning methods used in the state-of-the-art methods, Hyp-ABC improves the classification accuracy, and more importantly, it decreases the tuning time significantly. HyP-ABC can be deployed to solve the HPO problems with large search spaces. The major advantage of this work is the strong potential to improve tuning time without negatively affecting the performance. To summarize, HyP-ABC is recommended for optimizing RF, GXBoost, and SVM. In the future work, we will explore the semantic initialization of the population to further reduce the tuning time. Also, time complexity of algorithms such as SVM is highly dependent on the number of features and samples of a dataset. \section{Acknowledgement} \label{sec:acknowledge} The authors would like to thank Dr. Matthew Ohland from Purdue University for giving access to the MIDFIELD dataset, and Dr. Monique Ross from Florida International University for her valuable inputs. \bibliographystyle{IEEEtran} \section{Leveraged ML Algorithms} A summary of the ML algorithms used in this study as follows: \begin{enumerate} \item \textbf{Random Forest (RF)} \cite{breiman2001random} is an ensemble method and a type of Decision Tree (DT) learner that operates by constructing many DTs in the training phase. That is the reason it is called 'forest.' The term 'random' is also because the trees are built differently with random samples and random features to add diversity to the models and decrease the chance of overfitting \cite{breiman2001random,liaw2002classification,louppe2014understanding}. Random forest initially uses the bagging method to combine the predictions from each tree and calculate the overall predictions. \item \textbf{eXtreme Gradient Boosting (XGBoost)} \cite{chen2015xgboost} is a developed version of Gradient Boosting that utilizes a gradient boosting framework as an ensemble. One of the XGBoost focuses is the efficiency and speed of the model and supports parallelization. Focusing on the computational speed and model efficiency. XGBoost also tries to prevent overfitting using Ridge and Lasso regularization. XGBoost trains the model iteratively, correcting or fixing the newer models in each iteration \cite{chen2017xgboost}. XGBoost also has internal cross-validation. Hence, there is no need to identify the number of iterations in each run. \item \textbf{Support Vector Machine (SVM)} is a supervised learning technique that generates input-output mapping functions. The mapping function in the purpose of this study is a classification function, in which nonlinear kernel functions are used to transform input to a high-dimensional feature space. In this feature space, the data become more separable when compared to the raw input. SVM works by finding the maximum-margin hyper-planes between positive and negative observations. Using mapping function, SVM transforms the non-separable feature to linearly separable features \cite{wang2005support,shalev2014understanding}. \end{enumerate} \section{Main Hyper-parameters} Applying ML algorithms to different problems, only several hyper-parameters significantly impact the model's performance. These parameters are the main hyper-parameters of the model that require tuning\cite{yang2020hyperparameter}. Although the rest of the hyper-parameters may have a slight impact on the performance but they also increase the search space scales. The increase in the number of hyper-parameters increases the number of configurations exponentially, and as a result, the tuning time also increases \cite{decastro2019effect}. Therefore we reduce the impact of large space on tuning time by only considering the main hyper-parameters of ML models. To put theory into practice, we conducted our experiment based on Table \ref{tab:MainHP} that provides a summary of the applied ML algorithms and their main hyper-parameters. \begin{table}[ht] \centering \caption{ML Classifiers' Main Hyper-parameters} \label{tab:MainHP} \def1.2{1} \begin{tabular}{|c|c|} \hline \textbf{ML Classifier} & \textbf{Main Hyper-parameters}\\ \hline \textbf{RF} & \makecell{n\_estimators, criterion, max\_depth, max\_features,\\ min\_samples\_split, min\_samples\_leaf} \\ \hline \textbf{XGBoost} & \makecell{n\_estimators, max\_depth, learning\_rate,\\ subsample, colsample\_bytree} \\ \hline \textbf{SVM} & \makecell{C, kernel} \\ \hline \end{tabular} \end{table} \section{Search Spaces} Table \ref{tab:search} shows the details of hyper-parameters' search space configured for this study as well as their ranges and type. The determined search scales are based on testings and domain knowledge. \begin{table}[ht] \centering \caption{ML Classifiers' Main Hyper-parameters} \label{tab:search} \def1.2{1.2} \begin{tabular}{|c|c|c|} \hline \textbf{Hyper-parameter} & \textbf{Search Space} & \textbf{Type}\\ \hline \textbf{n\_estimators} & \makecell{ [5,500] } & Integer \\ \hline \textbf{criterion} & \makecell{ [gini, entropy] } & Categorical \\ \hline \textbf{max\_depth} & \makecell{ [5,50]} & Integer \\ \hline \textbf{max\_features} & \makecell{ [1,91]} & Integer \\ \hline \textbf{min\_samples\_split} & \makecell{ [2,30]} & Integer\\ \hline \textbf{min\_samples\_leaf} & \makecell{[1,15]} & Integer \\ \hline \textbf{learning\_rate} & \makecell{ [0,1]} & Continuous\\ \hline \textbf{subsample} & \makecell{(0,1]} & Continuous\\ \hline \textbf{colsample\_bytree} & \makecell{(0,1]} & Continuous\\ \hline \textbf{C} & \makecell{ [0.1,50]} & Continuous\\ \hline \textbf{Kernel} & \makecell{linear, poly, rbf, sigmoid} & Categorical\\ \hline \end{tabular} \end{table} \bibliographystyle{IEEEtran}
{'timestamp': '2021-09-14T02:14:38', 'yymm': '2109', 'arxiv_id': '2109.05319', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05319'}
arxiv
\section{Introduction} The current pandemic revitalized research on group testing, a methodology to reduce the number of required tests to screen a large population for a certain disease. The increased testing efficiency results from jointly testing groups, instead of subjecting each individual to a test. Specifically, we consider the scenario of \textit{probabilistic} group testing as first described by \citet{dorfman43}, where every individual has a certain (known) probability to be infected. Probabilistic group testing is in contrast to combinatorial group testing \cite{Du2000Combinatorial,lee2019saffron} where one assumes a fixed known number of infected individuals. Furthermore, we assume that while the number of tests is limited, all tests are perfectly accurate. Although the case of imprecise tests also leads to interesting resource allocation problems \cite{ely2020optimal}, we will not consider it in this work. Thus, if none of the individuals in a tested group are infected, the test will yield a negative result with certainty and one test was sufficient to obtain a definite result for several individuals. If, however, the test is positive, one cannot say which individuals in the group are infected and further tests have to be conducted. Formally, a \textit{testing strategy} is a deterministic algorithm, describing which groups of individuals are pooled and jointly subjected to the test. We assume that the choice of the next group can depend on the results of previously conducted tests. This \textit{adaptive} group testing, is in contrast to non-adaptive group testing (for a recent survey see \citet{aldridge2019group}), where the testing strategy is fixed and all tests can thus be performed in parallel. \subsection*{Previous work} The theoretical work on adaptive, probabilistic group testing started with \citet{dorfman43} who considered the simple strategy of testing groups of $M$ individuals and subsequently, if the pooled test is positive, testing each individual in the group separately. Although this strategy is far from optimal, it is easy to implement and can significantly increase the testing capabilities, compared to testing every sample individually. Further research in this direction was focused on finding new, more efficient and practical testing strategies, e.g., nested testing \cite{sobel1959group}, binary splitting \cite{hwang1972method}, and array testing \cite{phatarfod1994use}. The binary splitting algorithms by \citet{hwang1972method} perform close to the theoretic optimum, within a factor of $1.11$ of an information-theoretic lower bound, as shown by \citet{aldridge2019rates}. However, such a binary splitting technique requires extensive bookkeeping and many tests need to be performed sequentially, and cannot be conducted in parallel. Simpler, two-stage procedures are investigated by \citet{berger2002asymptotic}. The close relation of adaptive, probabilistic group testing to variable length source coding is well-detailed by~\citet{wolf1985born}. Due to the current pandemic, several works rediscover slight variations of these results and argue for the use of group testing \cite{gollier2020group,eberhardt2020multi}. Also, the practical implementation of group testing has seen a new surge of research, in particular, questioning the practical use in testing for SARS-CoV-2. Here, however, the focus was on the classical Dorfman testing strategy \cite{abdalhamid2020assessment,hogan2020sample,yelinevaluation} and only few works considered more elaborate non-adaptive testing strategies \cite{shental2020efficient}. Hardly any works go beyond the assumptions of perfect sensitivity and independence of the infection status of tested individuals. However, \citet{pilcher2020group} takes the dilution effect into account, i.e., reduced sensitivity of tests for large groups, and \citet{deckert2020simulation} performed a simulation study that found benefits of group testing if there is positive correlation of infection status between individuals in the same group. The common ground of all works above is that they focus on identifying exactly, which individuals are infected. This is a valid strategy and clearly the best outcome. However, there can be situations where not sufficiently many tests are available to subject all potentially infected individuals to a test. This is particularly the case when many individuals are (potentially) infected and testing resources are scarce. Here, a strategy needs to be found that uses these limited resources effectively. When insufficient tests for the entire population are available, it is unavoidable that some healthy individuals will be treated as infected and/or some infected individuals treated as healthy. For the design of a testing strategy, it is important to note, that these two events are not equally harmful in general. It might be considerably worse to have an undetected infection (false negative) present, than to treat one healthy individual as infected (false positive). A suitable balance has to be found and sensitive questions like ``How many false positives are we willing to accept to prevent one false negative?'' need to be answered to do so. Here, assuming that quantitative answers to these questions can be given, we propose a framework for designing and evaluating group testing strategies. Mathematically, the resulting problem is one of rate-distortion theory, a branch of information theory, established in the 1950s in a seminal paper by~\citet{Shannon1959Coding}. This connection allows us to formulate bounds on the performance of any group testing strategy. Although the problem of (combinatorial) group testing was extensively explored by information-theorists (e.g., in Ch.~24--29 in \citet{Aydinian2013Information} and by \citet{aldridge2019group}), this rate-distortion viewpoint has apparently not been considered so far. Thus, fundamental bounds are missing even for elementary scenarios. Only recently, researchers suggested that ``the scarcity of tests obviously means that it is better to use a test to detect the virus in another untested group than to try to discover who is infected in a positive group'' \cite{gollier2020group} which is a first step into the direction of the rigorous theory developed here. Finally, the scenario discussed in~\cite{jonnerby2020maximising} is closest to our ideas but considers only a single fixed testing strategy. We will use it in our theory for comparison and as a starting point for some more evolved testing strategies. \subsection*{Contributions} We present a rigorous mathematical framework for evaluating the cost incurred by false positive and false negative assignments under a given group testing strategy. An ultimate lower bound on the expected cost that cannot be surpassed by any testing strategy is derived and compared to existing and novel testing strategies. We consider two basic scenarios in more detail: First, a toy example where all individuals are equally likely to be infected and where wrong assignments incur the same cost for each individual; and, subsequently, a division of the population into subpopulations that have different probabilities of being infected (e.g., individuals showing symptoms are more likely to be infected than individuals without symptoms) and/or different costs associated to false assignments (e.g., misclassified health care workers result in a higher cost). Our work is focused on a simple model that requires as few parameters as possible. Thus, it does not capture several aspects that might be relevant in practical scenarios, such as dependence of the infection status between individuals, compliance of individuals with their assigned health status, or imperfect test results, nor does it incorporate testing strategies into a larger disease model. Nevertheless, basic questions that were so far answered by ``common sense,'' can be discussed on a sound mathematical basis. For example, optimal testing priorities can be shown to depend heavily on the specific scenario and subjecting only symptomatic individuals to a test is often a suboptimal decision. The rest of this article is organized as follows. In \cref{sec_problem}, we formulate the problem, give a mathematical definition of testing strategies, and introduce the expected cost associated with a testing strategy, as well as the minimal expected cost. Our main theoretical results are presented in \cref{sec:results}. We establish fundamental lower bounds on the minimal expected cost and calculate the expected cost of various simple testing strategies. A first simple example is given to illustrate the bound and the strategies. \Cref{sec:case} showcases a more complicated example. It illustrates how to allocate limited testing resources to obtain significant improvements using simple testing strategies. In \cref{sec:discussion}, we discuss our results and their limitations. Finally, in \cref{sec:itdetails}, we provide the information-theoretic statements that underlie our main results. Detailed proofs are relegated to a technical appendix. \section{Problem formulation}\label{sec_problem} We assume that we have a sequence of individuals and the infection status of the $n$-th individual is given by a binary random variable $X_n$ on $\Omega := \{0,1\}$, where $X_n=1$ corresponds to being infected and $X_n=0$ to being healthy. All $X_n$ are assumed to be independent but not necessarily identically distributed. Thus, each $X_n$ is a Bernoulli($p_n$) random variable with possibly different probability $\Pr[X_n=1] = p_n \in (0, 1)$. The second ingredient we need is a \textit{cost function} $\rho_n(x_n, y_n)$ that models the cost of wrong assignments, i.e., assigning an estimated infection status $y_n$ to the $n$-th individual with actual infection status $x_n$. In contrast to communication scenarios where $0$ and $1$ are usually interchangeable, the cost $\rho_n(0,1)$ of false positive assignment (i.e., a healthy individual is wrongly assigned an infected status) is not necessarily the same as the cost $\rho_n(1,0)$ of a false negative assignment (i.e., an infected individual is wrongly assigned a healthy status). Thus, we define \begin{align} \rho_n(0,1) = b_n\,, && \text{ and} && \rho_n(1,0) = c_n\,, \label{eq:false} \end{align} where $b_n, c_n > 0$. The cost of correct assignments is set to zero, i.e., $\rho_n(0,0) = \rho_n(1,1) = 0$ and the total cost $\rho\colon \Omega^N \times \Omega^N \to \mathbb{R}$ is given by summation $(\mathbf{x},\mathbf{y}) \mapsto \rho(\mathbf{x}, \mathbf{y}) = \sum_{n=1}^{N} \rho_n(x_n, y_n)$. We now turn to the mathematical description of testing strategies. A \textit{testing strategy} for $N$ individuals consists of a test procedure and a decision procedure. An $(N,K)$-\textit{test procedure} is given by $\boldsymbol{\eta} = (\eta_1, \eta_2, \dots, \eta_K)$ where $\eta_1 \in \mathcal{P}\big(\{1,2,\dots,N\}\big)$ and for $k > 1$, $\eta_k\colon \Omega^{k-1} \to \mathcal{P}\big(\{1,2,\dots,N\}\big)$, where $\mathcal{P}\big(\{1,2,\dots,N\}\big)$ denotes the collection of all subsets of $\{1,2,\dots,N\}$. Here, the set $\eta_1$ indicates the group used for the first test and the set-valued function $\eta_k$ indicates the group used for the $k$-th test, given the results of the previous $k-1$ tests. The corresponding \emph{test function} $\boldsymbol{\vartheta}\colon \Omega^N \to \Omega^K$ is given by $\vartheta_1(\mathbf{x}) = \max\{x_n | n \in \eta_1\}$ and for $k > 1$, we have $\vartheta_k(\mathbf{x}) = \max\big\{x_n \big| n \in \eta_{k}\big(\vartheta_1(\mathbf{x}), \vartheta_2(\mathbf{x}), \dots, \vartheta_{k-1}(\mathbf{x})\big)\big\}$. Thus, the $k$-th component $\vartheta_k$ corresponds to the result of the $k$-th test. A $(K,N)$-\textit{decision procedure} is a mapping $\kappa\colon \Omega^K \to \Omega^N$ that assigns, based on the outcome of $K$ tests, a status (infected/healthy) to all $N$ individuals. The concatenation of $\boldsymbol{\vartheta}$ and $\kappa$ maps the true status $\mathbf{X} := (X_1, \dots, X_N)$ of all $N$ individuals to an estimated status $(Y_1, \dots, Y_N) = \kappa \big(\boldsymbol{\vartheta} (X_1, \dots, X_N) \big)$ of these individuals using $K$ group tests. In total, this corresponds to $R=K/N$ \ac{TpI} which is referred to as the \textit{rate} of the testing strategy. If $R < 1$, which is the regime we are interested in, there is a positive probability that the tests will not enable a perfect identification of all infected individuals. Note that such an estimate ($0$: not infected, $1$: infected) has to be given for all $N$ individuals. We do not allow for individuals to be ``skipped,'' which would correspond to a ternary output alphabet. To assess the average cost of the wrong assignments for given test and decision procedures, we use the \emph{expected cost per individual}, defined as the expected value \begin{equation} D_{\text{test}}^{(\mathbf{X}, \rho)}(\boldsymbol{\vartheta}, \kappa) = \mathbb{E}\bigg[\frac{1}{N}\sum_{n=1}^N \rho_n(X_n, Y_n)\bigg]. \end{equation} Because there are only finitely many possible choices for $\boldsymbol{\vartheta}$ and $\kappa$, we can define the minimum \begin{equation} \label{eq:defdfink} D^{(\mathbf{X}, \rho)}(K) = \min_{\boldsymbol{\vartheta}, \kappa} D_{\text{test}}^{(\mathbf{X}, \rho)}(\boldsymbol{\vartheta}, \kappa) , \end{equation} where $\boldsymbol{\vartheta}$ and $\kappa$ range over all $(N,K)$-test and $(K,N)$-decision procedures, respectively. The quantity $D^{(\mathbf{X}, \rho)}(K)$ specifies the minimal cost, measured by $\rho$, that can be achieved by using $K$ tests for the $N$ individuals with random infection status $\mathbf X$. \section{Results} \label{sec:results} Calculating $D^{(\mathbf{X}, \rho)}(K)$ directly from \cref{eq:defdfink} is computationally infeasible, unless $N$ and $K$ are very small. Nevertheless, we can use information-theoretic ideas to provide bounds. These bounds are based on the idea of keeping the rate $R = K/N$ fixed, while letting $N$ approach infinity. Our first result is a lower bound, that holds if all individuals share the same parameters. Here, and in the remainder of the paper, we use the symbol $H_2(p) = -p\log p - (1-p)\log(1-p)$ for the binary entropy function, $\log(\,\cdot\,)$ denotes the logarithm to base $2$, and we adopt the convention that ``$0\cdot\log 0 = 0$.'' The proofs of the results in this \lcnamecref{sec:results} are presented in \cref{sec:itdetails} and in the appendices. The following \lcnamecref{thm:RD_function} presents a lower bound on $D^{(\mathbf{X}, \rho)}(K)$ for the case when infection is equally likely and independent across the entire population. It follows immediately from the more general \cref{th:partitions}, which will be stated later in this \lcnamecref{sec:results}. \begin{theorem} \label{thm:RD_function} Let $\mathbf{X} := (X_1, \dots, X_N)$ be $N$ independent and identically distributed Bernoulli($p$) random variables describing the infection status of a given population. The cost of wrong assignments is given by \cref{eq:false} with $b_n = b$ and $c_n = c$ for all $n$. Furthermore, set $a := c/b > 0$. For $v\in [0, v_0)$ define \begin{align} \label{eq:defdviidsup} \bar D(p, a, v) &= p \bigg(\frac{v}{1-v}-\frac{av^a}{1-v^a} \bigg) + \frac{a}{1-v^a} - \frac{a+v^{a+1}}{1- v^{a+1}} \\ \label{eq:defrviidsup} \bar R(p, a, v) &= \bar D(p, a, v) \log v + H_2(p) - \log \bigg(\frac{1- v^{a+1}}{1-v^a}\bigg) + p \log \bigg(\frac{1-v}{1-v^a} \bigg) \end{align} and for $v \ge v_0$, define $\bar D(p,a,v) = \min \big\{1-p,a p \big\}$ and $\bar R(p,a,v) = 0$. Here, $v_0$ is the smallest solution $v > 0$ of the equation \begin{align} (p v^{a+1} + 1 - p - v)(p v^{-a-1} + 1 - p - v^{-1}) = 0 . \label{eq:solv0} \end{align} Then there cannot exist a testing strategy that uses fewer than $\bar R(p, a, v)$ \ac{TpI} (i.e., $\bar R(p, a, v) N$ tests in total) and achieves an expected cost less than $b \bar D(p, a, v)$, i.e., $D^{(\mathbf{X}, \rho)}(K) \geq b \bar D(p, a, v)$ for all $K\leq \bar R(p, a, v) N$. \end{theorem} We emphasize that, in contrast to similar results in classical information theory, the lower bound in \cref{thm:RD_function} cannot always be achieved arbitrarily closely for increasing $N$. For example, for $p = \frac{1}{2}(3-\sqrt{5}) \approx 0.381$ and $v=0$, we obtain $\bar D(p, a, v)=0$ and $\bar R(p, a, v)=H_2(p)\approx 0.959$, although it is known \citep{ungar1960cutoff} that only individual testing (i.e., $R=1$) can achieve $D^{(\mathbf{X}, \rho)}(K)=0$ in this setting. Even though the lower bound in \cref{thm:RD_function} is somewhat cumbersome and difficult to grasp intuitively, it can easily be calculated for a given scenario. We will compare it to proposed testing strategies in \cref{fig:rda50} to illustrate its applicability. \begin{figure}[p!] \centering \includestandalone[width=.95\textwidth]{figs/Fig1} \caption{ Testing of a population with probability of infection $p=0.01$ and cost parameters $b=1$ and $c=50$. The lower bound from \cref{thm:RD_function} is compared to the binary splitting algorithm, and our strategies 1SG and 2SG as well as the significantly worse individual testing. Markers with associated numbers indicate the testing strategy used to achieve the given point, e.g., $(32)$ indicates the use of 1SG($32$) and $(66,22)$ indicates the use of 2SG($66$,$22$).} \label{fig:rda50} \end{figure} We next calculate the necessary number of tests and the resulting cost for some simple testing strategies. We first consider the strategy, proposed by \citet{jonnerby2020maximising}, to separate the population into equally sized and disjoint groups, test each group, and assign an infected status to each member of a positive group without conducting further tests. We refer to this strategy as \textit{one stage group testing (1SG)} and designate the size of the group in parenthesis, e.g., 1SG($50$) for a group size of $50$ individuals. We restate the following simple result from Section~2.3.1 in \citet{jonnerby2020maximising}, which is a special case of the more general \cref{lem:ksg} below. \begin{lemma} The 1SG($u$) testing strategy has a rate of $1/u$ \ac{TpI} and an expected cost of $D_{\textrm{1SG($u$)}} = b \big(1 - p - (1-p)^u\big)$. \end{lemma} Note that the exact rate and expected cost can be achieved only for a population $N$ that is an integer multiple of the group size $u$. However, the overhead is at most $1$ additional test for a final group of smaller size, resulting in an additional $1/N$ \ac{TpI} and a negligible decrease of the expected cost. Since we are usually concerned with large $N$, we ignore these terms in this and the following testing strategies. Of course, 1SG($u_1$) can be further extended by testing those individuals again, that belong to a positively tested group of size $u_1$. Specifically, we can separate the group into disjoint subgroups of smaller size $u_2$ and subject these subgroups again to a group test. This \textit{two stage group testing (2SG)} strategy is a generalization of Dorfman testing \cite{dorfman43} which corresponds to the case $u_2 = 1$, i.e., each individual in a positive group is tested separately. The decision strategy remains the same as in 1SG: Those individuals that belong to a positively tested subgroup (of size $u_2$) are declared infected. We again designate the group sizes in parenthesis, e.g., 2SG($50,10$) for a group size of $50$ individuals that is divided into five subgroups of $10$ individuals each, if the first group test is positive. Again, we can calculate the rate and expected cost in closed form. \begin{lemma} The 2SG($u_1,u_2$) testing strategy has an expected rate of $R_{\textrm{2SG($u_1$,$u_2$)}} = \frac{1}{u_1} + \frac{1-(1-p)^{u_1}}{u_2}$ and an expected cost per individual of $D_{\textrm{2SG($u_1$,$u_2$)}} = b (1 - p - (1-p)^{u_2})$. \end{lemma} Evidently, more than 2 stages could be used, but even more bookkeeping is then required and, typically, very large group sizes are needed to obtain a benefit. Thus, this extension may not be practically useful anymore. For the sake of completeness, we nevertheless provide the rate and expected cost of $k$ stage group testing, abbreviated as $k$SG($u_1, \dots, u_k$), where $u_\ell$ denotes the group size at stage $\ell$. Here, positive groups of size $u_\ell$ are separated into smaller subgroups of size $u_{\ell+1}$ for $\ell=1, \dots, k-1$ and individuals that belong to a positive subgroup at stage $k$ are declared infected, while all others are declared healthy. A proof of the result is given in \cref{app:proofksg}. \begin{lemma} \label{lem:ksg} The $k$SG($u_1, \dots, u_k$) testing strategy has an expected rate of \begin{equation} \label{eq:rateksg} R_{\textrm{$k$SG($u_1, \dots, u_k$)}} = \frac{1}{u_1} + \sum_{\ell =1}^{k-1}\frac{1-(1-p)^{u_\ell}}{u_{\ell+1}} \end{equation} and an expected cost per individual of \begin{equation} \label{eq:distksg} D_{\textrm{$k$SG($u_1, \dots, u_k$)}} = b (1 - p - (1-p)^{u_k})\,. \end{equation} \end{lemma} \begin{example} \label{ex:a50} We consider the setting $p=0.01$, $b=1$, and $c = a = 50$, i.e., we assume that we have a prevalence of $1\%$ and a false negative is fifty times worse than a false positive assignment. We begin with some trivial observations. First, if we do not have any tests available, the best strategy is to assign everyone to be healthy. This is because the expected cost of declaring an individual healthy is $\mathbb{E}\big[\rho(X_n, 0)\big] = p\cdot a + (1-p)\cdot 0 = 0.5$, while the expected cost for declaring someone infected is $\mathbb{E}\big[\rho(X_n, 1)\big] = p\cdot 0 + (1-p)\cdot 1 = 0.99$. On the other extreme is the case of zero cost, i.e., to determine exactly which individuals are infected. Here, clearly individual testing at a rate of $1$ \ac{TpI} could be applied, but Theorem~2 in \citet{aldridge2019rates} shows that it is also possible using a binary splitting algorithm at a rate of $0.0855$ \ac{TpI}. Any rate-cost tradeoff between these extreme points can be achieved by applying the available tests to as many individuals as possible, while declaring all others as healthy by default. Unfortunately, using approaches like a binary splitting algorithm do not come without problems: There is a significant amount of bookkeeping required and individuals usually have to be tested many times in a row delaying the notification about the result. Shifting to the strategies 1SG and 2SG that do not aim at identifying the status of each individual but to minimize the overall expected cost can lead to simpler procedures and better performance at the same time. Our lower bound in \cref{thm:RD_function}, the binary splitting algorithm, and the strategies 1SG and 2SG, as well as individual testing, for comparison, are illustrated in \cref{fig:rda50}. Note, that for all strategies, one can always subject only part of the individuals to a test and simply declare the rest healthy. In particular, we see that the optimal 2SG strategy when tests are scarce (less than $0.037$ \ac{TpI}) is to use the testing strategy 2SG($66, 22$) for as many individuals as possible, outperforming the binary splitting approach. \end{example} The example above illustrates that the proposed strategies, although very simple, can outperform the best known testing strategies if there are not sufficient tests available to test all individuals. This is because previous strategies always aimed at exactly identifying the infection status and did not consider the possibility to declare an infection status based on imperfect information. However, there are also many situations where the simple strategies we discussed above are useless. In particular, if the relative cost $a$ is small, then it is hardly ever useful to declare an individual infected if one is not very sure about the infection status. We now turn to the more general setting of a heterogeneous population, i.e., individuals may have different prevalence $p_n$ and also different costs $b_n$ and $c_n$. One simple example of this situation is to distinguish between individuals with symptoms (that have a higher prevalence $p_n$) and individuals without symptoms. Additionally, different costs may occur for individuals in critical areas, e.g., health care. There, a higher risk of infecting vulnerable individuals may increase the cost $c_n$ of false negatives, and additionally, a higher false positive cost $b_n$ might be incurred due to the importance of the work being performed by these individuals. We will discuss a specific scenario in \cref{sec:case} but first present the lower bound, an extension of \cref{thm:RD_function}. The proof of the following \lcnamecref{th:partitions} will be presented at the end of \cref{sec:itdetails}, as it requires several results from rate-distortion theory which are introduced there. \begin{theorem} \label{th:partitions} Let $\mathbf{X} := (X_1, \dots, X_N)$ be $N$ independent Bernoulli random variables describing the infection status of a given population. Assume further that the total population is separated into $I$ subpopulations, of sizes $N^{(1)}, \dots, N^{(I)}$, and that all $N^{(i)}$ individuals in the $i$-th subpopulation have the same probability $p^{(i)}$ of infection and are measured using the same cost function with parameters $b^{(i)}, c^{(i)}$ as in \cref{eq:false}. Define $a^{(i)} = c^{(i)}/b^{(i)} > 0$ and for $v \in [0,1]$, let \begin{align} \label{eq:subpopDR} D(v) = \frac{1}{N} \sum_{i = 1}^I N^{(i)} b^{(i)} \bar D\big(p^{(i)}, a^{(i)}, v^{b^{(i)}}\big), \; R(v) = \frac{1}{N} \sum_{i = 1}^I N^{(i)} \bar R\big(p^{(i)}, a^{(i)}, v^{b^{{(i)}}}\big), \end{align} where $\bar D(p, a, v)$ and $\bar R(p, a, v)$ are defined in \cref{thm:RD_function}. Then there cannot exist a testing strategy that uses fewer than $R(v)$ \ac{TpI} (i.e., $R(v) N$ tests in total) and achieves an expected cost less than $D(v)$, i.e., $D^{(\mathbf{X}, \rho)}(K) \geq D(v)$ for all $K\leq R(v) N$. \end{theorem} \section{Historic example case}\label{sec:case} We consider the SARS-CoV2 pandemic situation in Austria in mid November 2020. On average there were $N=8\,916\,845$ individuals living in Austria in 2020~\cite{StatistikAustria2020Population}. During the three days from 12th of November 2020 until 14th of November 2020 a total of $N_t = 103\,621$ individuals were subjected to a PCR-test for SARS-CoV2~\cite{OAGEG2021Dashboard}. Of these $N_t$ individuals, $20\,349$ tested positive~\cite{OAGEG2021Dashboard}. This corresponds to a prevalence of $p_t = 0.196$ in this tested subpopulation. We will refer to this subpopulation as the \textit{high prevalence subpopulation}. At the same time, a prevalence study found that approximately $3.1\%$ of the total population were infected~\cite{STATISTIKAUSTRIA2021COVID}. Thus, in the untested population of $N_u = 8\,813\,224$ the prevalence was about $p_u = 0.029$. We will refer to this subpopulation as the \textit{low prevalence subpopulation}. To illustrate the full potential of our model, we further consider individuals working in health care separately and will assign a higher cost for wrong assignments within this subpopulation. The most recent count of health care professionals working in hospitals and health care centers in Austria was $N_h = 121\,567$ at the end of 2019~\cite{STATISTIKAUSTRIA2021Personal}. Note that a finer separation into subpopulations is of course possible but avoided for the sake of simplicity. It is difficult to argue for the choice of specific costs of wrong assignments. However, in mid November 2020, a lockdown was issued in Austria,\footnote{\url{https://www.ris.bka.gv.at/Dokumente/BgblAuth/BGBLA_2020_II_479/BGBLA_2020_II_479.pdfsig} (in German)} which we interpret as the turning point where considering all (untested) individuals as infected is less costly than considering these individuals as healthy. This implies $(1-p) b \approx p c$, thus, at a prevalence of $p = 0.029$ in the untested, general population, we obtain $c \approx 33 b$. We normalize $b=1$ and choose $c = 33$. Since health-care facilities were not closed during this time, we assume that individuals working in health care have a different trade-off between $b$ and $c$. Specifically, we assume that a false positive assignment for this subpopulation is significantly more expensive and we set $b=6$ for these individuals. Although also a different $c$ value could be argued, we assume that the professional training counters the higher risk due to closer contact with susceptible individuals and we keep $c$ the same. Since there is no data available on the prevalence within the health care system, we assume that it is the same as in the general population. In particular, also the split into the high prevalence and low prevalence subpopulations is assumed to be the same. We thus end up with the following four subpopulations \begin{itemize} \item The first subpopulation consists of individuals working in health care that belong to the high prevalence subpopulation with $p^{(1)}=0.196$ and costs $b^{(1)}=6$, $c^{(1)} = 33$. We assume that $N^{(1)} = 1\,413$ belong to this subpopulation. \item The second subpopulation consists of individuals working in health care that belong to the low prevalence subpopulation with $p^{(2)}=0.029$ and costs $b^{(2)}=6$, $c^{(2)} = 33$. We assume that $N^{(2)} = 120\,154$ belong to this subpopulation. \item The third subpopulation consists of individuals not working in health care that belong to the high prevalence subpopulation with $p^{(3)}=0.196$ and costs $b^{(3)}=1$, $c^{(3)} = 33$. We assume that $N^{(3)} = 102\,208$ belong to this subpopulation. \item The fourth subpopulation consists of individuals not working in health care that belong to the low prevalence subpopulation with $p^{(4)}=0.029$ and costs $b^{(4)}=1$, $c^{(4)} = 33$. We assume that $N^{(4)} = 8\,693\,070$ belong to this subpopulation. \end{itemize} \begin{figure}[tbh] \centering \begin{tikzpicture} \begin{axis}[ DRaxis, legend entries={Individual Testing, 1SG/2SG, Binary Splitting, Lower Bound}, ymin=0.0,ymax=1.0, xmin=0.0, xmax=2.5e4, max space between ticks=45pt, ] \addplot+[DRplot, red, dotted] table[DRtable] {data/individual_p0.20_0.03_0.20_0.03.csv}; \addplot+[DRplot, blue, solid] table [DRtable] {data/2SG_p0.20_0.03_0.20_0.03.csv}; \addplot+[DRplot, green!50!black, solid] table [DRtable] {data/binsplit_p0.20_0.03_0.20_0.03.csv}; \addplot+[DRplot, black] table[DRtable] {data/RD_p0.20_0.03_0.20_0.03.csv}; \addplot+[DRlabeled, blue, only marks] table [DRtable_label] {data/2SG_p0.20_0.03_0.20_0.03_labels.csv}; \end{axis} \end{tikzpicture} \caption{Testing of the Austrian population grouped into 4 different sub-populations in mid November 2020. The lower bound from \cref{th:partitions} is compared to the binary splitting algorithm, and an optimal combination of strategies 1SG and 2SG as well as the significantly worse individual testing. Markers with associated numbers indicate the four testing strategies used to achieve the given point, where $\infty$ indicates that the given subpopulation is not tested, e.g., $(2)(\infty)(\infty)(30,10)$ indicates that subpopulations $2$ and $3$ are not tested, subpopulation $1$ is tested using 1SG($2$), and subpopulation $4$ is tested using 2SG($30$,$10$).} \label{fig:subpop} \end{figure} Our lower bound and the performance of the optimal combinations of 1SG and 2SG strategies for these specific parameters are illustrated in \cref{fig:subpop} in comparison to optimized binary splitting algorithms and individual testing. More specifically, the depicted curves correspond to the optimal use of the available tests under the given strategy. For individual testing and the binary splitting algorithms, this means that depending on the number of tests, a certain amount of people can be tested and correctly informed about their status, while many untested individuals remain and are assigned a status without being tested resulting in the depicted cost. For the $103\,621$ tests used during the discussed period, which correspond to $0.0116$ \ac{TpI}, the optimized strategy is to subject as many individuals from the fourth subpopulation as possible to a test using a 1SG($33$) testing strategy. By this approach, the expected cost is $0.816$. Individual testing could only reduce the expected cost to $0.944$, hardly any improvement over not testing at all at an expected cost of $0.956$. Note that in all subpopulations and strategies we assume that an optimal decision for untested individuals is used, namely, that a healthy status is assigned to untested individuals in subpopulations two and four and an infected status to untested individuals in subpopulations one and three. To illustrate the implications of this kind of strategy, we calculate the expected number of individuals that are considered infected. First, this number includes all individuals in the subpopulations one and three. Furthermore, each 1SG($33$) test in subpopulation four has a probability of $1-(1-0.029)^{33} \approx 0.621$ to result in a positive outcome. Thus, an additional expected number of $2\,124\,712$ individuals would be considered infected in this subpopulation. In total, an expected number of $2\,228\,333$ individuals would be considered infected. We see that the decrease in expected cost is very limited with such a low number of tests, even if an optimized strategy is used. In particular, our lower bound shows that no strategy can reduce the expected cost below $0.609$ using the assumed $103\,621$ tests. However, our theory can also be used to estimate how many tests are required to achieve a certain reduction in expected cost. For example, we can find the number of tests necessary to obtain half the expected cost than without testing, i.e., $0.478$. Our lower bound shows that at least $0.0226$ \ac{TpI} ($201\,256$ tests in total) are necessary, while our optimized strategies show that $0.0419$ \ac{TpI} ($373\,636$ tests in total) are sufficient. Our optimized strategies suggest to use a 1SG($4$) strategy to test all individuals in subpopulation one and a mix of 1SG($24$) and 1SG($23$) strategies to test all individuals in subpopulation four. We also want to point out that an astonishing number of $0.499$ \ac{TpI} ($4\,447\,461$ tests in total) would be required to achieve the same goal with individual testing; and even the previously best known binary splitting testing strategies require $0.102$ \ac{TpI} ($909\,637$ tests in total). A second example case is presented in~\cref{sec:second-example-case}, analyzing the situation in Austria during the SARS-CoV-2 pandemic in early April 2020. The two examples showcase how our theory can be used to explore possible strategies for a given set of parameters and a given number of tests. Furthermore, they already illustrate that the specific scenario can affect all parts of the optimal testing strategy, e.g., there is no general rule that the testing of individuals with highest prevalence has priority. Maybe surprisingly, the examples also illustrate that there are situations where our approach can result in substantial gains using very simple testing strategies. Any other parameter choices can be explored using the Jupyter notebook and Python code, available at \url{https://github.com/g-pichler/group-testing}. This software was created using a Jupyter Notebook~\citep{Perez2007IPython}, as well as SciPy~\citep{Virtanen2020SciPy}, NumPy~\citep{Harris2020Array}, and Matplotlib~\citep{Hunter2007Matplotlib}. Finally, we want to emphasize, that the historic example cases discussed here certainly do not completely reflect the reality of testing in Austria in 2020. In addition to the somewhat arbitrary choices of values $b, c$, our analysis suffers from the shortcomings that are to be discussed in~\cref{sec:discussion}. E.g., considering the first example case~(\cref{fig:subpop}), a 1SG($33$) test is positive with probability around $0.621$, while the chance of infection is less than $0.03$. One would not expect this strategy to be viable, as compliance will be low. \section{Information theoretic details} \label{sec:itdetails} Readers familiar with information theory will see the obvious analogues between our problem formulation and classical rate-distortion theory \cite{gray90source}. Indeed, an $(N,K)$-test function can be seen as a specific encoder of a binary sequence, whereas the corresponding $(K,N)$-decision procedure is a specific decoder. Thus, $D^{(\mathbf{X}, \rho)}(K)$ defined in \cref{eq:defdfink} is the minimal expected distortion of a restricted class of source codes of rate $R = K/N$ for the vector $\mathbf{X}$. A fundamental information-theoretic result provides a lower bound on the minimal expected distortion of an arbitrary source code of rate $R$, the so-called information distortion-rate function. \begin{definition} \label{def:DR_function} Let $\mathbf{X}$ be a random variable on $\Omega^N$ and $\rho\colon \Omega^N \times \Omega^N \to \mathbb R_+$ a distortion function. The \emph{information distortion-rate function} of $(\mathbf{X}, \rho)$ is given by \begin{align} \label{eq:DR_function} D_{\textrm{I}}^{(\mathbf{X}, \rho)}(R) = \min_{p_{\mathbf{Y}|\mathbf{X}} : I(\mathbf{X}; \mathbf{Y}) \le NR} \mathbb E_{p_{\mathbf{X}} p_{\mathbf{Y}|\mathbf{X}}} \bigg[ \frac{1}{N} \rho(\mathbf{X}, \mathbf{Y}) \bigg], \end{align} where $I({}\cdot{};{}\cdot{})$ denotes mutual information in bits \cite[Sec.~2.6]{gray90source}. \end{definition} Because $D_{\textrm{I}}^{(\mathbf{X}, \rho)}(R)$ is a lower bound on the minimal expected distortion of an arbitrary source code of rate $R$, it can be used to obtain a lower bound on $D^{(\mathbf{X}, \rho)}(K)$. The following \lcnamecref{lem:rdgtrd} is a direct consequence of Theorem~3.2.1 in \cite{gray90source} and a proof is thus omitted. \begin{lemma} \label{lem:rdgtrd} The minimal cost $D^{(\mathbf{X}, \rho)}(K)$, as defined in \cref{eq:defdfink}, is lower-bounded by the information distortion-rate function $D_{\textrm{I}}^{(\mathbf{X}, \rho)}(R)$, i.e., for all $R\geq 0$, $D^{(\mathbf{X}, \rho)}\big(K) \geq D_{\textrm{I}}^{(\mathbf{X}, \rho)}(R)$, when $K \le RN$. In particular, no testing strategy can achieve an expected cost strictly less than $D_{\textrm{I}}^{(\mathbf{X}, \rho)}(R)$ if only $R$ \ac{TpI} are available. \end{lemma} To prove our main results, it remains to characterize the information distortion-rate function $D_{\textrm{I}}^{(\mathbf{X}, \rho)}(R)$. We first focus on the case $N=1$ and will subsequently extend our setting to prove \cref{th:partitions}. The following result is based in the variational description of the information distortion-rate function (see Section 2.4 in \citet{gray90source}) and a detailed proof is provided in \cref{app:proofiid_rd_final}. \begin{theorem} \label{thm:iid_rd_final} Let $X\in \Omega$ be a Bernoulli($p$) random variable and $\rho\colon \Omega^2\to [0,\infty)$ a distortion function satisfying $\rho(0,0)=\rho(1,1)=0$, $\rho(0,1)=1$, and $\rho(1,0)=a$. Then the entire information distortion-rate function is parameterized as $D_{\textrm{I}}^{(X, \rho)}\big(\bar R(p, a, v)\big) = \bar D(p, a, v)$ with $v \in [0, 1]$. Here, $\bar D(p, a, v)$ and $\bar R(p, a, v)$ are defined in \cref{thm:RD_function}. \end{theorem} \begin{remark} \label{rmk:DR_deriv} For later use, we note that under the assumptions of \cref{thm:iid_rd_final}, $1/ (\log v)$ is the slope of the information distortion-rate function \cite[p.~86]{gray90source} for $v \in [0,v_0]$, i.e., $\dot D_{\textrm{I}}^{(X, \rho)}\big(R(p,a,v)\big) = (\log v)^{-1}$. Furthermore, note that $\big(\bar R(p, a, v_0), \bar D(p, a, v_0)\big)$ is the point $(0, \min\{ap,1-p\})$ on the distortion-rate curve. Thus, in particular, $\dot D_{\textrm{I}}^{(X, \rho)}(0) = (\log v_0)^{-1}$. \end{remark} We can now state the central characterization result of the information distortion-rate function in the setting of \cref{th:partitions}. A detailed proof of the result is provided in \cref{app:proofsubpop2}. \begin{theorem} \label{th:subpop2} Let $\mathbf{X}$ be as in \cref{th:partitions}. Then $D_{\textrm{I}}^{(\mathbf{X}, \mathbf{\rho})}\big(R(v)\big) = D(v)$ for every $v \in [0,1]$, where $D(v)$ and $R(v)$ are given in \cref{eq:subpopDR}. \end{theorem} Combining the previous results, we can now prove \cref{th:partitions,thm:RD_function}. \begin{proof}[Proof of~\cref{th:partitions,thm:RD_function}] By~\cref{lem:rdgtrd}, we have for all $R\geq 0$, that $D^{(\mathbf{X}, \rho)}(K) \geq D_{\textrm{I}}^{(\mathbf{X}, \rho)}(R)$ if $K \le NR$. Using the characterization of the information distortion-rate function in~\cref{th:subpop2}, this yields $D^{(\mathbf{X}, \rho)}(K) \geq D(\nu)$ whenever $K \le NR(\nu)$, concluding the proof of~\cref{th:partitions}. \Cref{thm:RD_function} is merely a special case of \cref{th:partitions} with $I=1$. \end{proof} Finally, we want to point out that many information theoretic questions about the problem remain open. In particular, the characterization of a ``group testing distortion-rate function'' that can be defined as the infimum of all expected distortions that are achievable at a given rate as the population size $N$ goes to infinity is a challenging new problem that can also be formulated as a problem in classical rate-distortion theory with significant restrictions on the encoder. Here, non-adaptive group testing may be easier to analyze because the encoder is essentially restricted to the $\max(\,\cdot\,)$ function. Another direction for future work is to incorporate testing errors, resulting in a joint source-channel coding scenario. It is not clear whether the source--channel separation theorem holds in this case. Nevertheless, we expect that a lower bound similar to the one presented here can be obtained, by adding the additional bits (i.e., tests) necessary for error-free communication over a binary (most likely asymmetric) channel. \section{Discussion} \label{sec:discussion} We introduced a rigorous mathematical formulation of optimal testing strategies for a given number of available group tests. The problem is formulated as a one-time testing procedure in the sense that we assume that the infection status of the population does not change during the testing procedure and we do not consider any time evolution. This enables us to use only very few parameters that describe a current pandemic situation and we do not require any detailed personal information such as contact maps between individuals. However, even these few parameters can be difficult to estimate and may also result in ethical challenges. The prevalence $p$ is the easiest and most obvious parameter and can be estimated using a negligible number of tests for a pilot study and the estimate can be improved as the testing strategy is applied. The costs $b$ and $c$ of wrong assignments are more difficult to choose. They can be adapted to the infectiousness of the disease, the cost and effectiveness of quarantine, non-pharmaceutical interventions that reduce the risk of infection, and most likely many more variables. How to exactly choose these costs is beyond the scope of our work and very specific for a given situation. It may also include political decisions by weighing health factors (e.g., minimize the number of infections by quarantining many individuals) against economic factors (e.g., minimize the number of quarantined individuals). Note however that at least implicitly these costs are used in political decisions: A society-wide lockdown can be interpreted as the assertion, that assigning all (untested) individuals an infected status is less costly than considering them to be healthy. Thus, at a prevalence $p$, this implies $(1-p) b \le p c$. Once the parameters are fixed for a given scenario, our theory on the one hand gives ultimate bounds on how large a cost reduction can be achieved by group testing, and on the other hand suggests optimal allocation of resources for simple (suboptimal) testing strategies. The present work is only a first step towards establishing a mathematical theory of group testing. Thus, we do not consider the most general scenario and focus on basic scenarios that are simplified in many aspects. In particular, the scope of our results is limited by the following assumptions: \begin{itemize} \item We assume that tests are perfect, i.e., a group test of $u$ individuals is negative if and only if all $u$ individuals are healthy. However, we expect that a small error probability will not significantly influence the results and simple simulations incorporating these errors can be used to check the robustness in a specific scenario. A rigorous theoretical treatment on the other hand should not only consider a fixed error probability for a group test, but the error probability should rather depend on the group size and the number of infected individuals within the group (cf.~\citet{pilcher2020group}). Thus, an extension of our work in this direction would imply a more quantitative approach of testing outcomes and not merely the binary options we consider here. \item In this work, no upper bound on the group size is assumed a priori. The information theoretic lower bounds would not be affected by such a limitation, but certain points of the $k$SG strategy will become infeasible, requiring minor modifications to the published code. However, a more thorough analysis would not impose a hard limit on the group size, but consider the trade-off between test accuracy and group size, as mentioned in the previous point. \item We assume that the infection status of different individuals is independent. \item We assume that the choice of testing strategy does not alter the cost of wrong assignment. This assumption may be violated in reality, as e.g., individuals that are assigned an ``infected'' will likely show different levels of compliance, depending on whether they were tested individually, in a group, or not at all. Going beyond this assumption could be achieved by changing the infection status from a binary decision to a probability assignment and using a suitably adapted cost function. \item The cost function is fixed and applied independently to each individual. E.g., we cannot express the fact, that quarantining a small number of individuals working in critical areas is hardly problematic but once a critical threshold is passed the cost of quarantining further individuals becomes more costly than the linear increase assumed in our model. \item We do not consider the collection of samples from individuals as a limiting factor, but merely the number of tests is limited. \item The testing strategies presented in this work are not at all optimal but merely illustrate the potential of our approach. For example, we do not consider testing individuals in several groups at the first stage (as, e.g., in the array testing approach by~\citet{phatarfod1994use}), nor mixing individuals from different subpopulations within a group. Nevertheless, our suggested strategies are surprisingly simple and can outperform even the best (significantly more complicated) strategies currently known. \item We consider testing as a stand-alone task and do not incorporate it into a larger disease model, as is done, e.g., in \citet{berger2020seir}. In particular, the probabilities of infection and the cost functions are assumed to be fixed and do not change over time. \end{itemize} From a theoretical viewpoint, our analysis reveals several surprising insights that are in contrast to long established fundamental statements in group testing theory. First, an established statement is that group testing is beneficial exactly in the regime $p< \frac{1}{2}(3-\sqrt{5}) \approx 0.381$ \cite{ungar1960cutoff}, i.e., in this regime, group testing cannot outperform individual testing. However, this result was proven under the assumption that perfect identification of the infection status of each individual is required. Maybe surprisingly, this statement does not extend to our setting. Indeed, for the specific case of $p= \frac{1}{2}(3-\sqrt{5})$, $b=1$, and $c=10$, using the testing strategy 1SG($2$) has a strictly lower expected cost than individually testing every second individual (both have rate $1/2$ \ac{TpI}). Similarly, in the non-adaptive regime (i.e., all tests are performed in parallel) an established result is that individual testing is optimal if all individuals are independent and have a fixed prevalence $p$ \cite{aldridge2018individual}. Again, this result only holds if perfect identification of the infection status of each individual is required. In our setting, the simple 1SG testing strategy is a non-adaptive strategy and is clearly superior to individual testing (see \cref{fig:rda50}). \begin{appendix} \section{Second example case} \label{sec:second-example-case} As a second example with significantly different prevalences, we consider the SARS-CoV2 pandemic situation in Austria in early April 2020. More specifically, another prevalence study was conducted from 1st of April until 6th of April 2020. Here, a prevalence of approximately $p = 0.0033$ was found~\cite[Section~3.2]{ogob20}. Since most of the samples were collected on the 4th of April, we consider a timeframe from 3rd of April until 5th of April. On these three days a total of $N_t = 16\,226$ tests were conducted~\cite{OAGEG2021Dashboard}. Of those, $778$ did yield a positive result~\cite{OAGEG2021Dashboard}. Thus, the prevalence in this high prevalence subpopulation was $p_t = 0.048$. The resulting untested population is $N_u = 8\,900\,619$ with a prevalence of $p_u = 0.0032$. We consider the same separation into subpopulations as before as well as the same costs. \begin{itemize} \item The first subpopulation consists of individuals working in health care that belong to the high prevalence subpopulation with $p^{(1)}=0.048$ and costs $b^{(1)}=6$, $c^{(1)} = 33$. We assume that $N^{(1)} = 221$ belong to this subpopulation. \item The second subpopulation consists of individuals working in health care that belong to the low prevalence subpopulation with $p^{(2)}=0.0032$ and costs $b^{(2)}=6$, $c^{(2)} = 33$. We assume that $N^{(2)} = 121\,346$ belong to this subpopulation. \item The third subpopulation consists of individuals not working in health care that belong to the high prevalence subpopulation with $p^{(3)}=0.048$ and costs $b^{(3)}=1$, $c^{(3)} = 33$. We assume that $N^{(3)} = 16\,005$ belong to this subpopulation. \item The fourth subpopulation consists of individuals not working in health care that belong to the low prevalence subpopulation with $p^{(4)}=0.0032$ and costs $b^{(4)}=1$, $c^{(4)} = 33$. We assume that $N^{(4)} = 8\,779\,273$ belong to this subpopulation. \end{itemize} \begin{figure}[tbh] \centering \begin{tikzpicture} \begin{axis}[ DRaxis, legend entries={Individual Testing, 1SG/2SG, Binary Splitting, Lower Bound}, ymin=0.0,ymax=0.12, xmin=0.0, xmax=1.2e4, max space between ticks=45pt, ] \addplot+[DRplot, red, dotted] table[DRtable] {data/individual_p0.05_0.00_0.05_0.00.csv}; \addplot+[DRplot, blue, solid] table [DRtable] {data/2SG_p0.05_0.00_0.05_0.00.csv}; \addplot+[DRplot, green!50!black, solid] table [DRtable] {data/binsplit_p0.05_0.00_0.05_0.00.csv}; \addplot+[DRplot, black] table[DRtable] {data/RD_p0.05_0.00_0.05_0.00.csv}; \addplot+[DRlabeled, blue, only marks] table [DRtable_label] {data/2SG_p0.05_0.00_0.05_0.00_labels.csv}; \end{axis} \end{tikzpicture} \caption{Testing of the Austrian population grouped into 4 different sub-populations in early April 2020. The lower bound from \cref{th:partitions} is compared to the binary splitting algorithm, and an optimal combination of strategies 1SG and 2SG as well as the significantly worse individual testing. Markers with associated numbers indicate the four testing strategies used to achieve the given point, where $\infty$ indicates that the given subpopulation is not tested, e.g., $(8, 2)(\infty)(18, 6)(72, 12)$ indicates that subpopulation $2$ is not tested and subpopulations $1$, $3$, and $4$ are tested using 2SG($8, 2$), 2SG($18, 6$), and 2SG($72, 12$), respectively.} \label{fig:subpop2} \end{figure} Our lower bound and the performance of the optimal combinations of 1SG and 2SG strategies for these specific parameters are illustrated in \cref{fig:subpop2}. For the $16\,226$ tests used during the discussed period, which correspond to $0.0018$ \ac{TpI}, the optimized strategy is to subject all individuals in subpopulation one to a test using a 2SG($8,2$) testing strategy, all individuals in subpopulation three using a 2SG($18, 6$) testing strategy, and as many individuals from the fourth subpopulation as possible using a 2SG($72,12$) testing strategy. Using this approach yields an expected cost of $0.1023$. Individual testing could only reduce the expected cost to $0.1054$, while not testing at all results in an expected cost of $0.1072$. \section{Proofs of information theoretic results} \label{app:proofsit} In this \lcnamecref{app:proofsit}, we provide detailed proofs of the two main information theoretic results in the main manuscript, namely \cref{thm:iid_rd_final} and \cref{th:subpop2}. \subsection{Proof of Theorem~\ref{thm:iid_rd_final}} \label{app:proofiid_rd_final} The following variational description of the information distortion-rate function is a particularization of Corollary~4.2.1 in \citet{gray90source} to our setting of binary random variables with an asymmetric distortion function, substituting $v= 2^s$. \begin{corollary} \label{cor:parrdfunc} Let $X$ be a Bernoulli($p$) random variable and $\rho\colon \Omega^2\to [0,\infty)$ a distortion function satisfying $\rho(0,0)=\rho(1,1)=0$, $\rho(0,1)=1$, and $\rho(1,0)=a$. Then for every $v \in [0,1]$ a point $(R_v, D_v)$ on the graph of the information distortion-rate function, i.e., $D_{\textrm{I}}^{(X, \rho)}(R_v) = D_v$, is given as \begin{equation} R_v = D_v \log v + \min_{q\in [0,1]} \Big(- p \log \big(q +(1-q)v^{a}\big) - (1-p) \log \big(q v + (1-q)\big) \Big) \label{eq:defrstd} \end{equation} and \begin{equation} D_v = \frac{ a p (1-q^*) \big(q^* v + (1- q^*)\big) v^{a} + q^*( 1- p) \big(q^* + (1- q^*) v^{a} \big) v}{\big(q^* + (1 - q^*) v^{a}\big) \big(q^* v + (1- q^*)\big)} \label{eq:defdvprelim} \end{equation} where $q^*$ solves the minimization in \cref{eq:defrstd}. \end{corollary} The minimization in \cref{eq:defrstd} can easily be done exactly. Although one could use existing results, e.g., Theorem~4.2.3 in \citet{gray90source}, it is easier to derive the optimization directly than to particularize these general results. \begin{lemma} \label{lem:opimqs} For $v,p \in (0,1)$ and $a > 0$, the function $\phi\colon [0, 1] \to \mathbb{R}$ defined by \begin{equation} \phi(q) = - p \log \big(q +(1-q)v^{a}\big) - (1-p) \log \big(q v + (1-q)\big) \label{eq:objminq} \end{equation} is convex and \begin{equation} \argmin_{q\in [0,1]} \phi(q) = \begin{cases} q_v & \textrm{ if } q_v \in (0,1) \\ 0 & \textrm{ if } q_v \leq 0 \\ 1 & \textrm{ if } q_v \geq 1\,, \end{cases} \label{eq:optqcases} \end{equation} where \begin{align} q_v := \frac{ (1 - p) v^{a+1} +p - v^{a} }{ (1 -v) (1- v^{a})}\,. \label{eq:defqs} \end{align} \end{lemma} \begin{proof} The derivative of $\phi$ is given as \begin{equation} \phi'(q) = - p \frac{1-v^{a}}{q +(1-q)v^{a}} - (1-p) \frac{v-1}{q v + (1-q)}\,. \label{eq:minqderiv} \end{equation} Thus, $\phi'(q)=0$ if and only if \begin{equation} 0 = - p (q(v-1)+1)(1-v^{a}) - (1-p) (q(1-v^{a}) +v^{a})(v-1) \end{equation} which is equivalent to \begin{equation} p(1-v^{a}) +(1-p) v^{a}(v-1) = q(1-v)(1-v^{a}) \end{equation} and in turn to $q=q_v$. The second derivative is given as \begin{equation} \phi''(q) = p \frac{(1-v^{a})^2}{(q +(1-q)v^{a})^2} + (1-p) \frac{(v-1)^2}{(q v + (1-q))^2} \label{eq:minqderiv2} \end{equation} which is positive and thus $\phi$ is convex. Thus, if the critical value $q_v$ is in $(0,1)$ then it is the global minimum. Otherwise, $q_v \geq 1$ implies $\phi'(q)<0$ on $(0,1)$ and thus the global minimum is at $1$, and $q_v \leq 0$ implies $\phi'(q)>0$ on $(0,1)$ and thus the global minimum is at $0$. \end{proof} To prove \cref{thm:iid_rd_final}, it remains to combine \cref{cor:parrdfunc,lem:opimqs} and to note that, by \cite[Theorem~4.2.1b]{gray90source}, the entire distortion-rate curve is parameterized by $v$. We first show that $q_v \in (0,1)$ (i.e., the first case in \cref{eq:optqcases}) if and only if $v \in (0, v_0)$. By the definition of $q_v$ in \cref{eq:defqs}, $q_v > 0$ is equivalent to \begin{equation} (1 - p) v^{a+1} +p - v^{a} > 0 \end{equation} and $q_v < 1$ is equivalent to \begin{equation} (1 - p) v^{a+1} +p - v^{a} < (1 -v) (1- v^{a})\,. \end{equation} These equations are, in turn, easily seen to be equivalent to \begin{equation} p v^{-(a+1)} + (1 - p) - v^{-1} > 0 \label{eq:cond1qv} \end{equation} and \begin{equation} p v^{a+1} + (1 - p) - v > 0\,. \label{eq:cond2qv} \end{equation} The function $f(u) := p u^{a+1} + (1 - p) - u$ has derivatives $f'(u) = (a+1) p u^{a} - 1$ and $f''(u) = (a+1) a u^{a-1}$ and is thus convex for $u > 0$. Furthermore, $f(1)=0$, $f(0) = 1-p > 0$, and $\lim_{u\to \infty}f(u) = \infty$ and hence the function has either one more zero or is nonnegative everywhere. In either case, \cref{eq:cond1qv,eq:cond2qv} are satisfied if and only if $v \in (0,v_0)$. Thus, the assumptions of \cref{thm:iid_rd_final} imply that the minimum in \cref{eq:defrstd} is $q_v$ and we can insert it into $D_v$ and $R_v$ in \cref{cor:parrdfunc}. To this end, we first derive $1-q_v$ as \begin{align} 1- q_v & = \frac{p v^{a+1} + (1 - p) - v}{ (1 - v) (1 - v^{a})}. \end{align} Next, we note that \begin{align} q_v + (1 - q_v)v^a & = \frac{ p (1 - v^{a+1}) }{1 - v} \end{align} and \begin{align} q_v v + (1 - q_v) & = \frac{ (1 - p) (1 - v^{a+1}) }{1 - v^{a}}\,. \end{align} Inserting these relations into $D_v$ in \cref{eq:defdvprelim}, simple algebraic manipulations yield $D_v = \bar D(p, a, v)$. Similarly, inserting the relations into \cref{eq:defrstd}, we obtain $R_v = \bar R(p, a, v)$. On the other hand, consider the case $v \in [v_0, 1)$. Assuming $f(v_0) = 0$, we must have $f'(1) \ge 0$, which is equivalent to $1-p \le ap$. Furthermore, $v$ lies between two zeros of a convex function and is thus nonpositive, i.e., \cref{eq:cond2qv} is not satisfied. Thus, $q_v \ge 1$, which in turn yields $R_v = 0 = \bar R(p,a,v)$ and $D_v = 1-p = \bar D(p,a,v)$. The case $f(v_0^{-1}) = 0$, i.e. $ap \le 1-p$, similarly yields $R_v = 0 = \bar R(p,a,v)$ and $D_v = ap = \bar D(p,a,v)$. Finally, observing that the case $v \in \{0,1\}$ follows by continuity concludes the proof of \cref{thm:iid_rd_final}. \subsection{Proof of Theorem~\ref{th:subpop2}} \label{app:proofsubpop2} We first establish a general result for the joint information distortion rate function of several independent sources particularized to the setting of \cref{th:subpop2}. We will use the shorthand $D_{\textrm{I}}^n = D_{\textrm{I}}^{(X_n, \rho_n)}$ for the $n$-th individual and $D_{\textrm{I}}^{(i)} = D_{\textrm{I}}^{(X^{(i)}, \rho^{(i)})}$, where $X^{(i)}, \rho^{(i)}$ are the random infection status and the cost function of an arbitrary individual in the $i$-th subpopulation. \begin{lemma} \label{lem:dr_function} \begin{enumerate} The information distortion-rate function $D_{\textrm{I}}^{(\mathbf{X}, \rho)}(R)$ can be decomposed as \begin{align} \label{eq:dr_decomp1} D_{\textrm{I}}^{(\mathbf{X}, \rho)}(R) &= \min_{\boldsymbol{\xi} \in [0,1]^N :\sum_n \xi_n = 1} \frac{1}{N} \sum_{n=1}^{N} D_{\textrm{I}}^n(\xi_n N R) \\ &= \min_{\boldsymbol{\xi} \in [0,1]^{\mathcal I} : \sum_i \xi^{(i)} N^{(i)} = 1} \frac{1}{N} \sum_{i \in \mathcal I} N^{(i)} D_{\textrm{I}}^{(i)}(\xi^{(i)} NR) . \label{eq:dr_decomp2} \end{align} \end{enumerate} \end{lemma} \begin{proof} In \cref{eq:DR_function}, the right-hand side can be rewritten as \begin{align} \min_{p_{\mathbf{Y}|\mathbf{X}} : I(\mathbf{X}; \mathbf{Y}) \le NR} \mathbb E_{p_{\mathbf{X}} p_{\mathbf{Y}|\mathbf{X}}} \bigg[ \frac{1}{N} \rho(\mathbf{X}, \mathbf{Y}) \bigg] & = \min_{p_{\mathbf{Y}|\mathbf{X}} : I(\mathbf{X}; \mathbf{Y}) \le NR} \mathbb E_{p_{\mathbf{X}} p_{\mathbf{Y}|\mathbf{X}}} \bigg[ \frac{1}{N} \sum_{n=1}^{N} \rho_n(X_n, Y_n) \bigg] \notag \\ & = \min_{p_{\mathbf{Y}|\mathbf{X}} : I(\mathbf{X}; \mathbf{Y}) \le NR} \frac{1}{N} \sum_{n=1}^{N} \mathbb E_{p_{\mathbf{X}} p_{\mathbf{Y}|\mathbf{X}}} \big[ \rho_n(X_n, Y_n) \big] \notag \\ & = \min_{p_{\mathbf{Y}|\mathbf{X}} : I(\mathbf{X}; \mathbf{Y}) \le NR} \frac{1}{N} \sum_{n=1}^{N} \mathbb E_{p_{X_n} p_{Y_n|X_n}} \big[ \rho_n(X_n, Y_n) \big]\,. \label{eq:proofseprdfunc} \end{align} Furthermore, we can expand the mutual information as \begin{align} I(\mathbf{X}; \mathbf{Y}) & = H(\mathbf{X}) - H(\mathbf{X}\,\vert\,\mathbf{Y}) \notag \\ & = \sum_{n=1}^N H(X_n) - H(X_n\,\vert\,\mathbf{Y}, X_1, \dots, X_{n-1}) \notag \\ & \geq \sum_{n=1}^N H(X_n) - H(X_n\,\vert\,Y_n) \notag \\ & = \sum_{n=1}^N I(X_n;Y_n) \end{align} with equality if $p_{\mathbf{Y}|\mathbf{X}}(\mathbf{y}|\mathbf{x}) = \prod_n p_{Y_n|X_n}(y_n| x_n)$. We can thus restrict the minimization in \cref{eq:proofseprdfunc} to $p_{\mathbf{Y}|\mathbf{X}}(\mathbf{y}|\mathbf{x}) = \prod_n p_{Y_n|X_n}(y_n| x_n)$ and obtain \begin{align} D_{\textrm{I}}^{(\mathbf X, \rho)}(R) &= \frac{1}{N} \min_{p_{\mathbf{Y}|\mathbf{X}} : \sum_n I(X_n; Y_n) \le NR} \sum_{n=1}^N \mathbb E_{p_{X_n} p_{Y_n|X_n}} \big[ \rho_n(X_n, Y_n) \big] \\ &= \frac{1}{N} \min_{\xi \in [0,1]^N : \Vert v \Vert_1 = 1} \;\min_{p_{Y_n|X_n} : I(X_n; Y_n) \le \xi_n NR} \sum_{n=1}^N \mathbb E_{p_{X_n} p_{Y_n|X_n}} \big[ \rho_n(X_n, Y_n) \big] , \end{align} which immediately yields \cref{eq:dr_decomp1}. Note that the only difference between \cref{eq:dr_decomp1,eq:dr_decomp2} is that all $\xi_n$ for $X_n$ belonging to the same subpopulation are chosen to be equal, i.e., $\xi_n = \xi^{(i)}$. To justify this choice, we have to show that this indeed minimizes the sum, i.e., \begin{equation} N^{(i)} D_{\textrm{I}}^{(i)}(\xi^{(i)} NR) % \leq \sum_{n=1}^{N^{(i)}} D_{\textrm{I}}^{(i)}(\xi_n NR) \label{eq:convexsubpop} \end{equation} for $\sum_{n=1}^{N^{(i)}} \xi_n = N^{(i)} \xi^{(i)}$. The convexity of the information distortion-rate function \cite[Sec.~4.1]{gray90source} implies that \begin{equation} D_{\textrm{I}}^{(i)}\bigg(\sum_{n=1}^{N^{(i)}} \frac{1}{N^{(i)}} R_n\bigg) \leq \sum_{n=1}^{N^{(i)}} \frac{1}{N^{(i)}} D_{\textrm{I}}^{(i)}(R_n) \end{equation} which is precisely \cref{eq:convexsubpop} for $R_n = \xi_n NR$. \end{proof} \Cref{th:subpop2} now follows by solving the minimization in \cref{eq:dr_decomp2}. More specifically, we can write the optimization problem in \cref{eq:dr_decomp2} as an unconstrained optimization problem using a Lagrangian formalism \cite[Sec.~5.5.3]{Boyd2004Convex} \begin{align} \label{eq:2} \mathcal L(\boldsymbol{\xi}, \lambda, \boldsymbol{\mu}) = \frac{1}{N} \sum_{i \in \mathcal I} N^{(i)} D_{\textrm{I}}^{(i)}(\xi^{(i)} NR) + \lambda \left( 1 - \sum_i \xi^{(i)} N^{(i)} \right) - \sum_i \mu^{(i)} \xi^{(i)} \end{align} and obtain the associated Karush-Kuhn-Tucker (KKT) conditions for $\lambda \in \mathbb R$ and $\boldsymbol \mu \in \mathbb R^{\mathcal I}$, \begin{align} R N^{(i)} \dot D_{\textrm{I}}^{(i)}(\xi^{(i)} NR) - \lambda N^{(i)} - \mu^{(i)} &= 0 \qquad \text{ for } i \in \mathcal I \label{eq:kkt1}\\* 1 - \sum_i \xi^{(i)} N^{(i)} &= 0 \label{eq:sum_constraint}\\* \xi^{(i)} \ge 0, \; \mu^{(i)} \ge 0 , \; \xi^{(i)} \mu^{(i)} &= 0 \qquad \text{ for } i \in \mathcal I . \label{eq:ximu0} \end{align} By the convexity of $D_{\mathrm{I}}^{(i)}$ \cite[Sec.~4.1]{gray90source}, the minimization problem \cref{eq:dr_decomp2} is convex and the KKT conditions therefore necessary and sufficient. Recall that we actually want to solve the minimization problem for a given $v$ at the fixed $R$ \begin{align} R(v) = \frac{1}{N}\sum_i N^{(i)} \bar R(p^{(i)}, a^{(i)}, v^{b^{(i)}})\,. \end{align} Choosing $\xi^{(i)} = \frac{\bar R(p^{(i)}, a^{(i)}, v^{b^{(i)}})}{NR}$ now obviously satisfies \cref{eq:sum_constraint}. To check \cref{eq:kkt1} and \cref{eq:ximu0} for all $i\in \mathcal I$, we consider two cases. If $v^{b^{(i)}} < v^{(i)}_0$, where $v^{(i)}_0$ is defined as $v_0$ in \cref{thm:RD_function}, then \cref{rmk:DR_deriv} implies that $\dot D_{\textrm{I}}^{(i)}\big(\bar R(p^{(i)}, a^{(i)}, v^{b^{(i)}})\big) = \frac{b^{(i)}}{\log v^{b^{(i)}}}$. Hence, setting $\mu^{(i)}=0$, \cref{eq:ximu0} is satisfied and \cref{eq:kkt1} reduces to choosing $\lambda = \frac{R}{\log v}$, such that \cref{eq:kkt1} is satisfied for all $i$ with $v^{b^{(i)}} < v^{(i)}_0$. If $v^{b^{(i)}}\geq v^{(i)}_0$, we obtain from the definition of $\bar R(p^{(i)}, a^{(i)}, v^{b^{(i)}})$ that $\xi^{(i)} = 0$. According to \cref{rmk:DR_deriv}, the derivative $\dot D_{\textrm{I}}^{(i)}(0) = \frac{b^{(i)}}{\log v_0^{(i)}}$ and \cref{eq:kkt1} becomes $\mu^{(i)} = R N^{(i)} \frac{b^{(i)}}{\log v_0^{(i)}} - R N^{(i)} \frac{1}{\log v}$ which is nonnegative due to $v^{b^{(i)}}\geq v^{(i)}_0$ and thus \cref{eq:ximu0} is satisfied. Thus, the choices $\xi^{(i)} = \frac{\bar R(p^{(i)}, a^{(i)}, v^{b^{(i)}})}{NR}$, $\lambda = \frac{R}{\log v}$, and $\mu^{(i)} = R N^{(i)} \frac{b^{(i)}}{\log v_0^{(i)}} - R N^{(i)} \frac{1}{\log v}$ for $v^{b^{(i)}}\geq v^{(i)}_0$ and $\mu^{(i)}=0$ otherwise, satisfy the KKT conditions. The equations \cref{eq:subpopDR} then follow by inserting $\xi^{(i)} NR = \bar R(p^{(i)}, a^{(i)}, v^{b^{(i)}})$ into $D_{\textrm{I}}^{(i)}(\xi^{(i)} NR)$ and noting that, by \cref{thm:iid_rd_final}, we have $D_{\textrm{I}}^{(i)}(\bar R(p^{(i)}, a^{(i)}, v^{b^{(i)}})) = b^{(i)} \bar D(p^{(i)}, a^{(i)}, v^{b^{(i)}})$. \section{Evaluation of $k$ stage group testing} \label{app:proofksg} To calculate the expected rate, we denote by $T_{\ell}$ the \ac{TpI} used in the $\ell$-th stage of the testing procedure. Then \begin{equation} R_{\textrm{$k$SG($u_1, \dots, u_k$)}} = \mathbb{E}\bigg[\sum_{\ell =1}^{k} T_{\ell} \bigg] = \sum_{\ell =1}^{k} \mathbb{E}[ T_{\ell} ] . \end{equation} Since in the first stage all individuals are tested in groups of size $u_1$, the expectation is simply $ \mathbb{E}[ T_{1} ] = \frac{1}{u_1}. $ In the $(\ell+1)$-th stage for $\ell\geq 1$ only those individuals that belong to groups of size $u_{\ell}$ including at least one positive individual are tested. We can thus condition the expectation on the event that the group of size $u_{\ell}$ the individual belongs to is negative, which has probability $(1-p)^{u_\ell}$, or positive, which has probability $1-(1-p)^{u_\ell}$. Hence, the expectation expands to \begin{equation} \mathbb{E}[ T_{\ell+1} ] = \big[ 1-(1-p)^{u_\ell} \big] \frac{1}{u_{\ell+1}} + (1-p)^{u_\ell} \cdot 0 \end{equation} concluding the proof of \cref{eq:rateksg}. To prove \cref{eq:distksg}, first note that $k$SG($u_1, \dots, u_k$) never declares an infected individual as healthy. Indeed, the only cases of wrong assignment can happen in groups that are positive at the $k$-th stage. Here, all individuals in the group are declared infected, although there may be several healthy individuals in the group. Thus, the expected cost of a single individual is the probability of itself being negative times the probability that at least one of $u_k-1$ other individuals is infected times the false positive cost $b$, i.e., \begin{align} D_{\textrm{$k$SG($u_1, \dots, u_k$)}} & = b (1-p) (1-(1-p)^{u_k-1}) \notag \\ & = b (1 - p - (1-p)^{u_k})\,. \end{align} \end{appendix} \section*{Acknowledgments} We thank the anonymous reviewers for their valuable feedback and comments. This work was supported in part by the Vienna Science and Technology Fund (WWTF) under grant MA16-053 and the Austrian Science Fund under grant Y 1199. {\it Conflict of Interest}: None declared. \bibliographystyle{elsarticle-num-names}
{'timestamp': '2021-10-29T02:17:47', 'yymm': '2109', 'arxiv_id': '2109.05378', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05378'}
arxiv
\section{Introduction} Multi-Agent Path Finding is the problem of arranging a set of collision-free paths for a set of agents on a given graph. Although MAPF is NP-hard to solve optimally on graphs~\cite{yu2013structure} and even 2D grids~\cite{banfi2017intractability}, many optimal MAPF algorithms have been developed in recent years. Some reduce MAPF to other well-studied problems, e.g., ILP~\cite{yu2013planning} and SAT~\cite{surynek2016efficient}, others solve it with search-based algorithms, e.g., enhanced A* search~\cite{goldenberg2014enhanced,wagner2015subdimensional}, Conflict-Based Search~\cite{sharon2015conflict} and its improved variants~\cite{li2019improved}. However, the limitation of these centralized planning methods is that they do not scale well to a large number of agents. RL and IL methods with decentralized execution have been applied to address this issue~\cite{sartoretti2019primal,wang2020mobile,riviere2020glas,liu2020mapper,li2020graph,li2021message,ma2021distributed}. During execution, each agent takes action based on its individual decision model with its own observation (may also include messages from other agents) as input, which avoids the scalability problem. For RL-based methods~\cite{sartoretti2019primal,wang2020mobile,liu2020mapper,ma2021distributed}, MAPF is generally modeled as a Markov Game~\cite{littman1994markov} with partial observability, where a reward function is designed for each agent, and the goal of each agent is to maximize its expected total return. Usually, expert guidance is applied to guide the RL during training in terms of behavior cloning~\cite{sartoretti2019primal}, shaped reward~\cite{liu2020mapper}, or heuristic map~\cite{ma2021distributed}. For IL-based methods~\cite{riviere2020glas,li2020graph,li2021message}, partial observability is still considered, but the objective is to minimize the divergence between expert demonstrations and generated trajectories, so that the learned policy can mimic the expert behavior. Recently, researchers focus on trainable communication channels between agents for MAPF, where extra information can be obtained during both training and execution to enhance multi-agent cooperation~\cite{li2020graph,li2021message,ma2021distributed}. However, these methods focus on broadcast communication in which messages will be transmitted to all other or predefined set of agents. For instance, in \cite{li2020graph} and \cite{li2021message}, the messages are broadcast to all other agents within a distance (communication radius). In \cite{ma2021distributed}, the central agent takes the messages from the two nearest neighbors after getting all the broadcast messages from its neighbors inside the field of view (FOV). Although empirical results have shown great improvements of communication based methods compared with non communication ones~\cite{ma2021distributed}, the drawback is that broadcast communication requires lots of bandwidth and incurs additional system overhead and latency in practice. More importantly, not every agent provides useful information for cooperation, and redundant information can even impair the learning process. Plenty of methods on reducing communication overhead or learning selective communication have been proposed in the literature of RL~\cite{singh2018learning,kim2019learning,zhang2019efficient,zhang2020succinct,wang2020learning,ding2020learning}. But most of them are designed for centralized training framework on cooperative Markov Game, where agents share the same team reward. In contrast, each agent has its individual reward in MAPF, and thus more information needs to be swapped for cooperation. Therefore, selective communication is much more important in this case. To design a succinct communication protocol for MAPF, we consider a request-reply communication scenario where messages are updated in two stages, and propose \textit{Decision Causal Communication}, a simple yet efficient mechanism to enable agents to select other members in the swarm for communication during both training and execution. More specifically, before communication, each agent is capable to figure out which neighbors in its FOV are relevant and influential by just using local observation. The agent makes two temporary decisions based on its raw local observation and the modified local observation by masking out a neighbor. For any neighbor that can cause difference between these two temporary decisions, that neighbor is considered as relevant and influential, and the agent will send a request to that neighbor for communication purpose. This communication protocol is also naturally capable for decentralized execution. Empirical results show the high success rate with low communication overhead of our method compared with its counterparts. \textbf{Contributions.} In this work, we propose DCC for MAPF. Unlike broadcast communication, DCC learns selective communication, and hence encourages agents to focus only on relevant information. We demonstrate that, on one hand, selective communication can remove temporal redundant messages, which is beneficial to multi-agent cooperation. On the other hand, communication overhead is greatly cut down due to the reduction of communication frequency. \section{Related work} \subsection{Reinforcement Learning based MAPF}\label{subsec:rl-mapf} RL-based planners generally formulate MAPF as a multi-agent reinforcement learning (MARL) problem to learn decentralized policies for agents (robots). Compared with centralized planning methods, learning decentralized polices scales well to a large number of agents. Collision free policies are usually learned by guiding RL with constraints or demonstration data~\cite{everett2018motion,sartoretti2019primal,wang2020mobile,liu2020mapper}. Incorporating demonstration guidance with RL can be divided into two categories, using demonstrations generated by a centralized planner, or by a single-agent planner. For instance, a well known framework named PRIMAL~\cite{sartoretti2019primal} builds on the asynchronous advantage actor critic (A3C) network~\cite{mnih2016asynchronous} as its RL part and uses behaviour cloning to supervise the training of RL. So it requires demonstrations generated by a centralized planner named ODrM*~\cite{wagner2015subdimensional}. The limitation of using a centralized planner is that it requires solving a MAPF problem and is thus time-consuming, especially in a complex environment with a large number of agents. For methods using single-agent planner as guidance, MAPPER~\cite{liu2020mapper} and Globally Guided RL (G2RL)~\cite{wang2020mobile} use A* search for single-agent path generation and apply an off-route penalty if agents fail to follow the path. The potential issue is that, as single-agent shortest paths are usually not unique and not globally optimal for multi-agent environment, forcing agents to follow these paths by extra shaped rewards can mislead agents. To tackle the above issues, our previous method DHC~\cite{ma2021distributed} does not require a centralized planner. Although single-agent shortest paths are still adopted as guidance, DHC embeds all the potential choices of shortest paths as heuristic into the input of the model, instead of forcing agents to follow a specific path. Thus, no special shaped rewards are required. Even though empirical results have shown that enhancing RL with guidance can help to learn collision free policies for MAPF, the cooperation among agents is not directly modeled. Communication via graph convolution is a promising way to achieve multi-agent cooperation, where an agent aggregates information from its neighbors, including itself, and makes decisions based on this augmented information~\cite{das2019tarmac,jiang2020graph,niu2021multi}. This idea is recently deployed for MAPF. By treating each agent in the environment as a node and connecting neighboring nodes (agents) if they are inside the FOV of each other, a graph is formulated by DHC and multi-head dot-product attention~\cite{vaswani2017attention} serves as the convolutional kernel to compute interactions among agents. Similar ideas are applied by the work described in~\cite{li2020graph} and Message-Aware Graph Attention neTwork (MAGAT)~\cite{li2021message}, where the communication part is a graph neural network (GNN)~\cite{scarselli2008graph}. However, it is worth noting that both \cite{li2020graph} and \cite{li2021message} are IL-based methods, which train the model to imitate the demonstrations generated by Conflict-Based Search (CBS)~\cite{sharon2015conflict} and Enhanced CBS~\cite{barer2014suboptimal}, respectively. Thus, MAPF instances still need to be pre-solved while extreme scenarios may fail to be solved and collected into the training data. Also, none of these communication based methods consider the efficiency of communication, resulting in high communication overhead and latency. \subsection{Efficient and Selective Communication for MARL} Most existing works on communication in MARL, including those described above, focus on broadcast communication, i.e., broadcasting the messages to all other or predefined agents. To improve efficiency, a number of strategies have been proposed. Individualized Controlled Continuous Communication Model (IC3Net)~\cite{singh2018learning} considers that full communication is not always necessary and agents can determine whether to send messages to others indicated by a gating function. However, this gating function can block all communication channels of an agent. Cases where an agent's message is instructive to some agents but useless or harmful to others can not be handled. Schedule Communication (SchedNet)~\cite{kim2019learning} only allows a limited number of agents to broadcast messages, who are chosen by some importance weights assigned. The shortcoming is that a central scheduler is required to gather all individual weights and decide which agents should be entitled to broadcast their messages. Variance Based Control (VBC)~\cite{zhang2019efficient} lets agents transmit their messages only when the variance of the message vector is high (high variance implies that the message is informative). And agents decide whether to request messages based on local ambiguity. Temporal Message Control (TMC)~\cite{zhang2020succinct} stores agent messages in the buffer and new messages are sent out only when they contain relatively new information compared with old ones. Nearly Decomposable Q-functions (NDQ)~\cite{wang2020learning} optimizes communication via minimizing the entropy of messages between agents. Individually Inferred Communication (I2C)~\cite{ding2020learning} learns a prior network, which takes local observation and identity of another agent as input, to predict a belief of whether to communicate. All VBC, TMC, NDQ and I2C are designed on the centralized training methods that factorize the joint action-value function, such as QMIX~\cite{rashid2018qmix}, different from MAPF settings. \section{Problem formulation}\label{sec:env} \subsection{MAPF Problem Definition} MAPF has many variants as summarized in~\cite{stern2019multi}. In this paper, we consider the classical MAPF case defined in~\cite{stern2019multi} that (a) each agent performs an action in every time step, and may cause vertex and swapping conflicts, (b) agents "stay at target" until all agents have reached their goals, and (c) optimizes the sum of cost. This definition differs from the environments used in PRIMAL and MAPPER, which are much simpler. In PRIMAL, agents take actions in turn (only one agent takes action at a time), although we can treat this as all agents act simultaneously but only one agent can move while all others choose no-op action. In MAPPER, agents are removed from the environment upon reaching their goal locations, which simplifies the problem, as there will be no livelocks when an agent reaches its goal but obstructs other agents from getting to their goals. We also notice that the environment in \cite{damani2021primal} is specially designed where obstacles compose narrow corridors that only allow one agent to pass at a time. We do not consider an environment like this. Formally, we define MAPF as follows. Given an undirected graph $G=(V,E)$ and a set of $n$ agents, each agent indexed by $i$ has a unique start vertex $s_i\in V$ and a unique goal vertex $g_i\in V$. Time is discretized into time steps. At each discrete time step, each agent can either \textit{move} to an adjacent vertex or \textit{wait} at its current vertex. A path for $i$-th agent is a sequence of adjacent (indicating a moving) or identical (indicating a waiting) vertices starting at $s_i$ and terminating at $g_i$. Agents remain at their goal vertices ($g_i$) after they complete their paths. There are two kinds of collisions, either vertex collision or edge collision. A vertex collision is a tuple $\langle i,j,v,t \rangle$ where $i$-th and $j$-th agents reaching at the same vertex $v$ at time $t$. An edge collision is a tuple $\langle i, j, u, v, t\rangle$ where $i$-th and $j$-th agents traverse the same edge $(u,v)$ in opposite directions at time $t$. A solution to MAPF is a set of collision-free paths, one for each agent. The quality of a solution is measured by the sum of arrival time of all agents at their goal vertices. \begin{figure}[tpb] \centering \includegraphics[scale=0.19]{pics/commu.png} \caption{(a) Broadcast communication: agent $i$ broadcasts its message to all neighboring agents $j$, $k$, and $p$. And agents $j$, $k$, $p$ will also broadcast their messages to agent $i$. If predefined scope is set, agent $i$ can decide whose message to be used in calculation, e.g., DHC takes the nearest two agents. There is no communication between agent $i$ and $u$, as agent $u$ is outside agent $i$'s FOV. (b) Request-reply based selective communication: agent $i$ omits irrelevant agent $k$, and only communicates with relevant agent $j$ and $p$. After determining which agent to communicate, the communication is conducted in two rounds. At the first round, agent $i$ sends out messages (requests) to agent $j$ and $p$. At the second round, agent $j$ and $p$ reply with their updated messages to agent $i$. } \label{fig:req-rep} \vspace{-0.17in} \end{figure} \subsection{Environment Setup} In line with standard MAPF tasks, we focus on 2D 4-neighbor grids where agents, goals, and obstacles occupy one grid cell respectively. Formally, the map is a $m\times m$ matrix, where $0$ represents a free location and $1$ is an obstacle. Each map is chosen $n$ start positions and $n$ corresponding goal positions for $n$ agents from free locations. We make sure each goal is reachable from its start point and there is no overlap among $2n$ selected positions. At each time step, agents move simultaneously to neighboring locations or wait at their current locations. Thus, the size of the action space is 5 (move to four directions or stay still). Agents may hit obstacles or conflict with others during simulation. We handle the collision by recursively resetting the related agents to previous states until no collision exits. We consider a partially observable environment, which is more compatible with the real world problem. Each agent can only access the information inside its FOV with size $\ell\times\ell$ ($\ell<m$), where $\ell$ is an odd number to make sure agents are at the center of FOV. The reward design is adopted from DHC~\cite{ma2021distributed}, shown in Table~\ref{table:reward}. Generally, negative rewards are given to agents for each movement to facilitate goal reaching. No shaped reward is required in our method. \section{Selective communication for MAPF} In this paper, we propose DCC \footnote{Code available at https://github.com/ZiyuanMa/DCC}, a simple yet efficient mechanism to reduce communication overhead in multi-agent systems. DCC can be instantiated by independent Q-learning~\cite{tan1993multi}, or any framework of centralized training and decentralized execution, such as QMIX~\cite{rashid2018qmix} and VDN~\cite{sunehag2018value}. We consider a request-reply scenario different from the traditional setup where each agent only sends out an almost information-less indicator, e.g. a scalar value, as the request signal. Instead, in our setup, each agent sends out a request signal with rich information including its own messages along with the relative positions of neighbors. In this way, after receiving the request, the agents being requested can immediately benefit from this query by collecting some information from the query agent. Fig.~\ref{fig:req-rep} shows the difference between broadcast and our request-reply based selective communication. In the following part, We first introduce DCC communication mechanism and then instantiate DCC with independent Q-learning. \begin{table}[tbp] \caption{Reward Function Design} \label{table:reward} \begin{center} \resizebox{0.65\columnwidth}{!}{ \begin{tabular}{|c|c|} \hline \textbf{Actions} & \textbf{Reward}\\ \hline Move (Up/Down/Left/Right) & -0.075 \\ \hline Stay (on goal, away goal) & 0, -0.075 \\ \hline Collision (obstacle/agents) & -0.5 \\ \hline Finish & 3 \\ \hline \end{tabular} } \end{center} \vspace{-0.17in} \end{table} \begin{figure*} \centering \includegraphics[scale=0.26]{pics/model.png} \caption{System flow of DCC. It contains four modules: observation encoder (blue), decision casual unit (purple), communication block (green), and Q network (orange). An example of agent $i$'s FOV is shown by a $5\times 5$ grid, where the blue color represents the agent itself, the green color represents neighbors, and the gray color represents obstacles. Agent $i$'s decision casual unit constructs three modified local observations by masking each neighbor inside the FOV, represented by a red cross. The embeddings by observation encoder for the raw and modified local observations are fed to Q network directly to get temporary decisions, which are further used to decide which neighbor is relevant for communication.} \label{fig:model} \vspace{-0.1in} \end{figure*} \subsection{Decision Causal Communication}\label{subsec:DCC} Our communication mechanism is motivated by I2C~\cite{ding2020learning}, where causal inference is utilized to derive a threshold to trigger communication. Specifically, I2C defines the causal effect of agent $j$ to agent $i$ as the KL-divergence~\cite{kullback1997information} between two decision probabilities, $D_{KL}( P(a_i|\boldsymbol{a}_{-i}, \boldsymbol{o}) || P(a_i|\boldsymbol{a}_{-ij}, \boldsymbol{o}) )$, where $\boldsymbol{o}$ is the joint observations, $\boldsymbol{a}_{-i}$ denotes the joint actions except for agent $i$, and similar meaning for $\boldsymbol{a}_{-ij}$. The magnitude of this divergence indicates how much agent $i$ will adjust its policy if taken into account agent $j$'s policy. If the divergence is small, agent $i$ chooses not to communicate with $j$ as that will hardly affect its own policy. However, I2C is only effective for centralized training algorithms as it requires to know the joint observations and actions of all other agents. In real world problems such as MAPF, usually an agent with partial observability can only observe the existence of other agents instead of their policies. Although agents can broadcast their actions, that will definitely increase the communication overhead. In practice, if the policy of an agent requesting communication conditions on the action of the communicated agent, the circular dependencies can occur. At last, setting a reasonable threshold for that KL-divergence highly depends on empirical experiments and may vary in different problems. Thus, to design an appropriate communication protocol for MAPF, in this work, we restrict the strategy in I2C by triggering communication between agent $i$ and $j$ only when the \textit{existence} of agent $j$ causes the policy adjustment on agent $i$, and we call this \textit{Decision Causal Communication}. To get an intuition of the proposed protocol, consider the learning based MAPF methods discussed in Section~\ref{subsec:rl-mapf}, where most of them guide the RL agent with global or local optimal demonstrations. In order to diminish the communication cost, an agent should follow the demonstration guided policy as often as possible without communicating with others, if the existence of other agents in its FOV will not affect its current policy. Otherwise, the agent communicates with those neighbors who will individually affect its policy. Although the policy may be adjusted after communication and we can not guarantee the adjusted policy is always better than unchanged policy during simulation, training the communication part along with RL in an end to end manner to maximize the expected total return will force the communication to be helpful and performed only when it is necessary. Formally, this communication protocol can be formulated as follows. Suppose agent $j$ can be seen by agent $i$ (agent $j$ is inside the FOV of agent $i$), and the relative position of agent $j$ in $i$'s FOV is $(x_j, y_j)$. Agent $i$ gets its local observation $o_i$ from the environment and constructs another modified observation $o_{i,-j}$ ($-j$ means without $j$) by setting the information at agent $j$'s position by some special value, such as zero: $o_{i,-j}\leftarrow o_{i}(x_j, y_j)=0$. Then agent $i$ uses its local decision model, without communication, to predict two temporary actions $\widetilde{a}_i$ and $\widetilde{a}_{i,-j}$ based on $o_i$ and $o_{i,-j}$, respectively. If these two actions match with each other, implying that the existence of agent $j$ will not affect $i$'s policy, agent $i$ will not request message from agent $j$. Otherwise, agent $i$ sends a request to agent $j$ via a communication channel, and agent $j$ will respond with a message. In this work, we consider messages are updated in both request and reply stages, which is discussed in the following subsection. The final aggregated messages are further used by policy or Q-network to generate the final actions. \subsection{Deep Q-Learning Model Design} We instantiate DCC with independent Q-learning, namely the model is designed and trained from a single agent's perspective by treating other agents as part of the environment. We borrow some architecture design from DHC. The whole model of DCC consists of four main components, including observation encoder, decision causal unit, communication block, and Q-network. The model architecture is shown in Fig.~\ref{fig:model}. We begin from the model input and describe the four components one by one. \paragraph{Local observation input} At time step $t$, agent $i$ gets a matrix with the shape $\ell\times \ell\times 6$ as input, denoted by $o_i^t$. The first channel is a binary matrix representing the obstacles inside the FOV. The second channel is a binary matrix indicating the locations of other agents if within the FOV. The other four are heuristic channels proposed by DHC~\cite{ma2021distributed}, to encode multiple choices of single-agent shortest path. We refer readers to the DHC paper for further details. \paragraph{Observation encoder} The encoder contains \textit{four} stacked convolutional layers with a GRU~\cite{chung2014empirical}. The local observation $o^t_i$ is first encoded into $\hat{o}_i^t$ by four convolutional layers. Then by adopting the last step communication outcome $e^{[2]t-1}_i$ as the hidden state, the GRU gets $\hat{o}_i^t$ and generates the intermediate message $e^t_i$. \paragraph{Decision causal unit} This unit depends on the observation encoder to embed modified observations, and the Q-network (will be discussed later), to get temporary actions. Let $\mathbb{B}_i$ denote all neighbors of agent $i$. Given $o^t_i$, $o^t_{i,-j}$ is constructed according to Section~\ref{subsec:DCC} for all $j\in\mathbb{B}_i$. Each $o^t_{i, -j}$ is passed through the observation encoder as discussed above to get an embedding $e^t_{i,-j}$. By skipping the communication, $e^t_i$ and $\{e^t_{i,-j}\}_{j\in\mathbb{B}_i}$ are directly fed into the Q-network to compute Q-values. Actions $\widetilde{a}^t_i$ and $\{\widetilde{a}^t_{i,-j}\}_{j\in\mathbb{B}_i}$ are inferred by applying argmax over Q-values. Based on these actions, the communication scope of agent $i$ is \begin{align} \mathbb{C}_i = \{j|\widetilde{a}^t_i\neq \widetilde{a}^t_{i, -j}\}_{j\in\mathbb{B}_i}. \end{align} Note that temporary actions $\widetilde{a}^t_i$ and $\{\widetilde{a}^t_{i,-j}\}_{j\in\mathbb{B}_i}$ are only used to decide the communication scope, not the final action to be executed. \paragraph{Communication block} This block is the graph convolution with multi-head dot-production as the convolutional kernel~\cite{vaswani2017attention} followed by a GRU. We regard the request-reply as a two-round communication. After defining the communication scope $\mathbb{C}_i$, at the first round, agent $i$ sends request information to all agent $j\in\mathbb{C}_i$. This information includes its own message $e^t_i$ as well as the relative position of $i$'s neighbors inside $i$'s FOV, denoted as $l^t_i$. The relative position of each neighbor is originally represented as a one-hot vector, i.e. the vector length is $\ell\times\ell$, and further embedded by a neural network layer. At the first round, agent $j$ may receive many requests from different agents, and we define this request receiving scope for agent $j$ as \begin{align} \bar{\mathbb{C}}_j = \{i|j\in \mathbb{C}_i\}. \end{align} Then each agent $j$ who receives requests will update its message using multi-head attention. Let $\bar{\mathbb{C}}_{j+}$ denote the set $\{j,\bar{\mathbb{C}}_j\}$. For every agent $\bar{i}\in\bar{\mathbb{C}}_{j+}$, agent $\bar{i}$'s own message $e^t_{\bar{i}}$ is projected to \textbf{Q}uery by matrix $\boldsymbol{W}^h_Q$, while the concatenation of $e_{\bar{i}}^t$ and $l_{\bar{i}}^t$ is projected to \textbf{K}ey and \textbf{V}alue by matrix $\boldsymbol{W}^h_K$ and $\boldsymbol{W}^h_V$ in each independent attention head $h$. The relation between agent $j$ and $\bar{i}\in\bar{\mathbb{C}}_{j+}$ in $h$-th attention head is computed as \begin{align} \mu^h_{j\bar{i}}=\mathrm{softmax}\left(\frac{\boldsymbol{W}^h_Q e^t_j\cdot (\boldsymbol{W}^h_K [e^t_{\bar{i}},l^t_{\bar{i}}])^{\top} }{\sqrt{d_K}}\right), \end{align} where $d_K$ is the dimension of \textbf{K}eys. The \textbf{V}alues are weighted summed by weights $\mu^h_{j\bar{i}}$ over $\bar{\mathbb{C}}_{j+}$ at each head $h$. And all head outputs are concatenated over $\mathcal{H}$ heads to pass through a neural network layer $f_o$ for the final output \begin{align} \hat{e}^t_j=f_o\left(\mathrm{concat}\left(\sum_{\bar{i}\in\bar{\mathbb{C}}_{j+}} \mu^h_{j\bar{i}}\boldsymbol{W}^h_V[e^t_{\bar{i}},l^t_{\bar{i}}], \forall h\in\mathcal{H}\right)\right). \end{align} The message $\hat{e}^t_j$ and the initial message $e^t_j$ are first aggregated by a GRU to generate the first round outcome $e^{[1]t}_{j}$. Then $e^{[1]t}_{j}$ acts as the initial message for the next round. At the second round, agents who received requests will reply with their updated messages along with the relative position of their neighbors, i.e. agent $i$ will receive $e^{[1]t}_j$ and $l_j^t$ from all agent $j\in\mathbb{C}_i$. Let $\mathbb{C}_{i+}$ denote the set $\{i,\mathbb{C}_i\}$. Agent $i$ will update its message in the same manner as defined in Equations 3-4 by replacing $j$ with $i$, and replacing $\bar{i}\in\bar{\mathbb{C}}_{j+}$ with $\bar{j}\in\mathbb{C}_{i+}$. Denote the message generated by Equations 3-4 at this round as $\hat{e}^{[1]t}_i$. Finally, $\hat{e}^{[1]t}_i$ and $e^{[1]t}_j$ are aggregated by a GRU to output $e^{[2]t}_i$, the final outcome message of the second round. \paragraph{Q-network} The message $e^{ [2]t}_i$ is adopted by a dueling Q-network~\cite{wang2016dueling}, which separates state advantage $V_s(\cdot)$ and action advantage $A(\cdot)$, to predict the Q-values. \begin{align} Q_{s,a}^i=V_s(e^{[2]t}_i)+\left(A(e^{[2]t}_i)_a-\frac{1}{|\mathcal{A}|}\sum_{a'}A(e^{[2]t}_i)_{a'}\right), \end{align} where $\mathcal{A}$ is the action space. After we get the $Q$ values of agent $i$, the loss function for training the whole model is a time difference (TD) error. To stabilize training, we use a multi-step TD error calculated by the mean square error (MSE) \begin{align} \mathcal{L}(\theta)=\mathrm{MSE}\left(R^i_t - Q^i_{s_t,a_t}(\theta)\right) \end{align} with $R^i_t=r^i_t+\gamma r^i_{t+1}+...+\gamma^{n}Q^i_{s_{t+n},a_{t+n}}(\bar{\theta})$, where $r^i_t$ is the reward received by agent $i$ at time $t$, $R^i_t$ is the multi-step expected return, $\theta$ represents the parameters of the entail model, and $\bar{\theta}$ denotes the parameters of the target network, a periodical copy of the online parameters $\theta$. \subsection{Training}\label{subsec:training} As mentioned above, we train the model from a single agent's perspective using independent Q-learning, where each agent learns its own action value $Q^i$ independently and simultaneously, treating other agents as part of the environment. The benefit is that it avoids the scalability problem in centralized training, which requires learning a Q-function for joint actions over all agents, as the joint action space grows exponentially when the number of agents increases. To further simplify the training process, instead of training separate models for different agents, we train a single model by sharing parameters among agents. To facilitate training, we adopt two training strategies, namely distributed training and curriculum learning~\cite{bengio2009curriculum}, which are discussed in the following. \paragraph{Distributed training} Distributed training has significantly improved the performance of RL compared with non distributed ones, such as R2D2~\cite{kapturowski2018recurrent} and Ape-X~\cite{horgan2018distributed}. In MAPF, PRIMAL is a distributed RL method by using A3C. The idea behind this distributed version of algorithm is to parallelize the gradient computation, to more rapidly optimize the parameters. Another approach, as proposed in Ape-X, is to parallelize experience data generation and selection with a shared replay memory. We adopt the latter strategy, where we setup multiple runners on CPUs with their own copy of the environment and up to date model to generate experience data, and a single learner on GPU to train. The runners initialize the priorities for the experience data and feed into a global prioritized reply buffer. The learner samples the most useful experiences from the buffer to update the model parameters and also update the priorities of the experiences. The advantage is that the model training is allocated to GPU while original A3C is designed for multi-core CPU. Note that the transitions of all the agents need to be recorded for communication purpose in the model. As the priorities are shared among all runners, the good experiences explored by any runner can benefit the learner. As we only have a single learner on GPU, the core task is to efficiently distribute multiple runners on CPUs. Here we utilize a powerful Python package named Ray~\cite{moritz2018ray}, a distributed framework designed for machine learning, to easily deploy parallel programs on multiple CPUs with little modification to the deep learning code. \paragraph{Curriculum learning} The ultimate goal of the learning model is to handle complex cases in a large environment with high obstacle density and many agents. However, it would be hard for the model to learn fast and stably if directly starting from a complicated training environment. As pointed in~\cite{bengio2009curriculum}, presenting training examples not randomly but in a meaningful order will benefit machine learning algorithms. Motivated by this idea, we design a training pipeline to gradually introduce more complex training cases to the model. Specifically, training starts with a task where only $1$ agent stays in a $10\times 10$ environment. Then if the success rate of the current task exceeds $0.9$, two new tasks are established for training. One is to increase the number of agents by $1$, and the other is to increase the size of the environment by $5$. The final task with $16$ agents in a $40\times 40$ environment will be reached as the training scale grows. \paragraph{Other training settings} For the environment setting, the obstacle density for each environment during training is sampled from a triangular distribution between $0$ and $0.5$ with a peak at $0.33$, which is the same as the obstacle setting in PRIMAL. The FOV size is $9\times 9$ ($10\times 10$ in PRIMAL, we make it odd) and the agent is in the middle of the FOV. The maximum step for the environment is $256$. For training setting, we train the model with a batch size of $128$ and a sequence length of $20$. The discount factor $\gamma=0.99$. The multi-step TD error defined in Equation 5 is computed with a length of $2$. The number of runners for distributed training is set to be $16$. \begin{figure}[tp] \begin{minipage}{.5\columnwidth} \centering\ \includegraphics[scale=.256]{pics/40_compare.png} \end{minipage}% \begin{minipage}{.5\columnwidth} \centering \includegraphics[scale=.256]{pics/80_compare.png} \end{minipage} \caption{Success rate of our method compared with PRIMAL and DHC in two different scenarios. } \label{fig:res_compare} \vspace{-0.17in} \end{figure} \begin{table}[tbp] \caption{Average steps in two types of environments with obstacle density $=0.3$} \label{table:avg_step} \begin{center} \resizebox{0.95\columnwidth}{!}{ \begin{tabular}{c|c|ccc} \hline \multicolumn{5}{c}{Average steps in $40\times 40$ maps} \\ \hline Agents & ODrM* & DCC & DHC & PRIMAL \\ \hline 4 & 50.00 & \textbf{48.575} &52.33 &79.08 \\ 8 & 52.17 & \textbf{59.60} &63.90 & 76.53 \\ 16 & 59.78 & \textbf{71.34} &79.63 & 107.14 \\ 32 & 67.39 & \textbf{93.54} &100.10 & 155.21 \\ 64 & 82.60 & \textbf{135.55} &147.26 & 170.48 \\ \hline \multicolumn{5}{c}{} \\ \hline \multicolumn{5}{c}{Average steps in $80\times 80$ maps}\\ \hline Agents & ODrM* & DCC & DHC & PRIMAL \\ \hline 4 & 93.40 & \textbf{93.89} &96.72 & 134.86\\ 8 & 104.92 & 109.89 &\textbf{109.24} & 153.20\\ 16 & 114.75 & \textbf{122.24} &122.54 & 180.74\\ 32 & 121.31 & \textbf{132.99} &138.32 & 250.07\\ 64 & 134.42 & \textbf{159.67} &163.50 & 321.63\\ 128 & 143.84 & \textbf{192.90} & 213.15 & 350.76 \\ \hline \end{tabular} } \end{center} \vspace{-0.17in} \end{table} \section{Experiments} The model is trained and tested in classical MAPF environments as discussed in Section~\ref{sec:env}. We compare DCC with one of the most well known RL baselines named PRIMAL~\cite{sartoretti2019primal}, and the most recent RL plus communication method named DHC~\cite{ma2021distributed} in terms of success rate and average step. For comparing communication overhead, we build a baseline model, which uses request-reply mechanism but with predefined communication scope. PRIMAL and DHC are not included in this evaluation because they are all-to-all communication (more costly than request-reply). \subsection{Success Rate and Average Step} Success rate measures the ability to complete a MAPF task within given time steps. Average step measures the average time step consumed to finish a task, where smaller value indicates a better policy. We average both successful and unsuccessful cases to calculate the average steps. We set up two types of maps, $40\times 40$ and $80\times 80$ for testing. The obstacle density is set to be $0.3$, the highest testing density in PRIMAL and DHC. We set up 200 test cases for each agent number in $\{4,8,16,32,64\}$. Additional agent number of $128$ is tested in $80\times 80$ maps due to a larger environment space. The maximum time step for $40\times40$ map is 256, and 386 for $80\times80$ map, the same as the PRIMAL’s setting. Fig.~\ref{fig:res_compare} shows the success rate of our method compared with PRIMAL and DHC in two types of environments. In general, DCC and DHC (RL plus communication) perform much better than PRIMAL (RL with expert guidance) in all cases. The performance of PRIMAL downgrades heavily in relatively larger environments ($80\times 80$) compared with smaller ones ($40\times 40$), which indicates the IL part of PRIMAL does not deliver good guidance to its RL component. Thus it suffers performance degradation on long-horizon task. In the environments where the agent density is low, such as $4$, $8$, $16$ agents in both $40\times 40$ and $80\times 80$ maps, the difference between the success rate of DCC and DHC is small. In these environments, agents have a lower chance to meet and communicate with others, so the difference between broadcast communication (DHC) and selective communication (DCC) is not very significant. However, the success rate of DHC drops rapidly when agent density further grows. In agent dense environments, agents have a higher chance of encountering each other, but agents will obtain irrelevant and redundant information from others due to broadcast communication, which harms the cooperation among agents. By selecting and gathering relevant and influential information for communication, the cooperation is enhanced by DCC. Table~\ref{table:avg_step} verifies that DCC learns higher quality policies with respect to average steps. We include ODrM*~\cite{wagner2015subdimensional}, a centralized planner, as a reference. Especially compared with DHC, learning selective communication by DCC leads to much shorter paths in agent dense environments. \subsection{Selective Communication vs. Predefined Scope} Generally, selective communication by DCC does not need to set a communication scope. Any neighboring agent inside the FOV is possible to be requested by the central agent for communication. Previous broadcast communication method DHC defines the communication scope as the nearest two neighboring agents inside the FOV in order to reduce temporal redundant information. Although it is reasonable to assume the nearest agents are most relevant and influential, we show that selective communication outperforms the predefined scope (nearest two agents) for MAPF in both success rate and communication overhead. To make a fair comparison, we develop a baseline model, named RR-N2 (request-reply, nearest two). The whole model architecture is similar to DCC. The only difference is that RR-N2 does not have the decision causal unit in Fig.~\ref{fig:model}, and in communication block, each agent only requests information from its two nearest agents inside the FOV. The training settings are the same as DCC as discussed in Section~\ref{subsec:training}. \begin{figure}[tp] \begin{minipage}{.5\columnwidth} \centering\ \includegraphics[scale=.256]{pics/40_self.png} \end{minipage}% \begin{minipage}{.5\columnwidth} \centering \includegraphics[scale=.256]{pics/80_self.png} \end{minipage} \caption{Success rate of our method compared with RR-N2 in two different scenarios. } \label{fig:res_self} \vspace{-0.17in} \end{figure} \begin{table}[tbp] \caption{Communication frequency in two different environments with obstacle density $=0.3$} \label{table:comm_freq} \begin{center} \resizebox{0.97\columnwidth}{!}{ \begin{tabular}{c|cc|cc} \hline Average Step &\multicolumn{2}{|c}{Map size $40\times 40$} & \multicolumn{2}{|c}{Map size $80\times 80$} \\ \hline Agents & DCC & RR-N2 & DCC & RR-N2\\ \hline 4 & 2.42 & 36.88 & 1.06 & 18.36 \\ 8 & 11.56 & 209.79 & 5.75 & 105.86\\ 16 & 60.47 & 959.38 & 24.98 & 469.58\\ 32 & 294.69 & 4111.57 & 126.685 & 2125.94\\ 64 & 1811.33 & 19490.09 & 562.11 & 8780.72\\ 128 & - & - & 2915.84 & 36560.30 \\ \hline \end{tabular} } \end{center} \vspace{-0.17in} \end{table} Fig.~\ref{fig:res_self} shows the success rate of our method compared with this baseline. The difference in success rate is significant in agent-dense environments, i.e., $64$ agents in $40\times 40$ map and $128$ agents in $80\times 80$ map, which implies the nearest two agents are not always the most relevant ones. One may think that DCC achieves a better performance due to unconstrained communication scope, where each agent may communicate with more than two agents inside its FOV and thus gathers more information than RR-N2. We show that this is not really the case and DCC actually learns succinct communication. In particular, we compute the average communication frequency in these test environments as shown in Table~\ref{table:comm_freq}. A pair of request and reply is counted as one time communication. The average communication overhead of RR-N2 is much more costly than DCC in all the testing cases, and is extremely expensive in agent-dense environments. By learning selective communication, DCC can greatly reduce communication by only focusing on relevant messages. Combining these two results, we can conclude that although communication can help multi-agent cooperation for MAPF, agents should learn to actively select relevant agents for communication, because even the most nearest agents are not the relevant ones. Communicating with only two agents can already lead to huge communication overhead. Thus, researchers should always devise a succinct communication mechanism in order to reduce the communication overhead for easy deployment to real world problems. {\bf Limitations:} There is an additional computational cost associated with selecting neighboring agents. In extreme cases, the cost is of order of $O(n\times p)$. $p$ is the FOV capacity. \section{Conclusion} We propose DCC to learn succinct communication for MAPF with classical MAPF environment settings. Our aim is to enable agents to actively select relevant and influential neighbors for communication, instead of broadcasting. The selection is learned via the local policy adjustment effect between agents, which captures the necessity of communication. Empirical results show that selective communication with relevant agents improves the policy learning process. Moreover, DCC also serves as a component for communication reduction, greatly downscaling the communication overhead. Future work entails extensions of DCC to centralized training frameworks and cooperative Markov Game tasks. Another direction is to explore how to directly exclude sets of neighbors during neighboring selection to reduce complexity, and also the maximal number of agents that DCC can handle in different size of maps. \bibliographystyle{./IEEEtran}
{'timestamp': '2021-12-24T02:22:13', 'yymm': '2109', 'arxiv_id': '2109.05413', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05413'}
arxiv
\section{INTRODUCTION} \label{introduction} Trajectory estimation and map building represent core aspects of many applications in robotics, such as autonomous driving. A great amount of simultaneous localization and mapping (SLAM) systems with 6 degree-of-freedom (6-DoF) have been proposed in literature in the last decades, with the goal of estimating accurate trajectories with real-time performances. These methods can be grouped in two main categories, vision-based and point cloud-based systems, depending on the main sensor used (camera or laser rangefinder, respectively). Point cloud-based systems, can capture and represent the environment with a high level of details, due to the density of the clouds, and they are not afflicted by the issues of vision-based methods, such as illumination and viewpoint changes. Moreover, tracking performed with point clouds is more accurate and stable than its visual counterpart, and it is generally preferred when data is available. However, achieving real-time performance, while keeping high accuracy, still remains an open quest. Indeed, the most critical aspect which minders real-time point cloud SLAM is the alignment of LiDAR scans. During the last decades, many algorithms have been created to find the relative motion between two point clouds, operation also known as scan matching. The most used and known method to perform scan matching is Iterative Closest Point (ICP) \cite{besl1992method} and its many variants. The idea behind these algorithms is to align two point clouds iteratively, until convergence or a stopping criterion is satisfied. Although ICP suffers from high computational cost, Generalized ICP \cite{segal2009generalized} and more recent parallel versions (e.g. VGICP \cite{koide2020voxelized}) are relatively faster, and can be used as alternatives. To overcome the computational shortcomings of full point clouds scan matching, different feature-based approaches have been proposed. Feature-based matching methods work similarly to standard scan matching, but require less resources. They can achieve so by extracting 3D features from the clouds, such as edges, planes or clusters, and then match them. A low-drift feature-based and real-time LiDAR odometry and mapping (LOAM) method is proposed in \cite{zhang2014loam}. LOAM performs 3D point feature to edge, and plane, scan matching to find correspondences between point clouds. The performance of LOAM deteriorates when resources are limited and no loop closure is performed, leading to large estimation errors on long trajectories, as we show in Section \ref{experiments}. Improving LOAM, the same authors proposed LeGO-LOAM \cite{shan2018lego}, a lightweight, real-time pose estimation and mapping system, composed by five modules: segmentation, feature extraction, LiDAR odometry, LiDAR mapping and transform integration. Speedup is achieved by filtering the input point clouds through image-based segmentation, performed on the 2D range projection of each scan. More recent variants of LeGO-LOAM have been proposed, optimizing it, namely A-LOAM and LeGO-LOAM-BOR. Feature-based systems are, in general, less accurate than methods which perform scan matching on whole clouds. For this reason, loop closure and trajectory optimization are mandatory steps in their pipeline. Nevertheless, these tasks can easily become computationally demanding as the size of a trajectory increases. To overcome this problem, graph SLAM systems have been proposed, such as \cite{mendes2016icp} and \cite{pierzchala2018mapping}, where the trajectory of the robot, estimated via scan matching, is modeled as a graph. There are multiple advantage of this approach, as described by Grisetti et. al. in \cite{grisetti2010tutorial}, such as the ability to introduce relationships between sensor data and/or observations from the environment, or a great availability of frameworks for efficient graph optimization, which translates in the optimization of the corresponding trajectory. A recent point cloud-based system which relies on a graph structure is HDL \cite{koide2018portable}, which consists of four steps. First, laser scans are pre-processed and filtered to reduce their size. Then, the filtered clouds are used to simultaneously perform tracking and to possibly detect the ground plane. Poses estimated through tracking, and floor coefficients extracted from the point clouds, are used to build a graph of the trajectory, i.e., a pose graph , which is later optimized. The system achieves superior performances, but it is slow, especially when dealing with large point clouds derived from outdoor environments. All the algorithms available in literature, being based on feature matching or full scan matching, either achieve high accuracy at the cost of computational time, or sacrifice the quality of the trajectory to obtain real-time performance. Moreover, these systems are monolithic and difficult to modify and adapt, and are usually bound to some existing framework (e.g., ROS \cite{quigley2009ros}), often hindering portability on different operative systems (e.g. Windows or macOS). For these reasons, in this paper we propose a new system, \textit{ART-SLAM}, to perform point cloud-based graph SLAM, inspired by HDL, with multiple contributions. ART-SLAM is able to achieve real-time performance, retaining high accuracy, even in scenarios without loops. The proposed system is also able to efficiently detect and close loops in the trajectory, using a three-phased algorithm. ART-SLAM presents a high degree of modularity, due to its architecture, described in Section \ref{artslam}, and can be easily integrated and improved. Lastly, it is not bound to any framework, making it portable on different operative systems and customizable. ART-SLAM is available open source at \url{https://github.com/MatteoF94/ARTSLAM}. \section{ART-SLAM} \label{artslam} \subsection{System overview} \begin{figure}[t] \centering \includegraphics[width=0.485\textwidth]{images/architecture.png} \caption{Architecture of the proposed system.} \label{system_architecture} \end{figure} An overview of the proposed framework is represented in Fig. \ref{system_architecture}. The system is composed by multiple distinct modules, which can be grouped into two main blocks. The first, mandatory (colored in gray), is the core of ART-SLAM, and it is formed by all the modules that perform SLAM on the input point clouds (orange, in figure). The other blocks of the proposed framework are optional, as they can be used to integrate the main system with data coming from different sensors or with re-processed inputs. Given an incoming laser scan, the first step is to process it, in the \textit{pre-filterer}, to reduce its size and remove noisy points. The filtered cloud is then sent simultaneously to two modules. The most important one, the \textit{tracker}, estimates the current displacement of the robot by performing scan-to-scan matching with previous filtered scans. The other, \textit{floor detector}, finds the robot pose w.r.t. the ground, adding height and rotational consistency to the trajectory. The current pose estimate is sent, along with its corresponding point cloud, to the \textit{loop detector} module, which tries to find loops between new and previous point clouds, again performing scan-to-scan matching. Moreover, poses, loops and floor coefficients (estimated by the floor detector module) are used to build the pose graph, representing the trajectory of the robot. Lastly, the pose graph is optimized, to increase the poses accuracy. \textit{IMU and GPS} data (pink in Fig. \ref{system_architecture}) can be integrated in the \textit{pose graph builder} module, to increase the accuracy of the estimated trajectory. Moreover, \textit{pre-computed odometry} (e.g., through a different sensor or system) can be fed to the tracker as initial guess for the scan matching. Lastly, a \textit{pre-tracker} module (green in Fig. \ref{system_architecture} performs multi-level scan-to-scan matching, to quickly estimate the motion of the robot before the tracking step: this estimate is broadcasted to the tracker, as initial guess of the scan-to-scan matching, to boost the accuracy and performance of the module. \subsection{System modularity} \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{images/modular.png} \caption{Inner structure of a single module. Observers capture data, dispatch queues store it, the core processes it and the notifiers broadcast the results.} \label{modularity} \end{figure} Differently to the majority of systems available in literature, our proposed framework is fully modular and its components work independently one from another. This is possible thanks to the \textit{register and dispatch} technique used to create the system. The structure of a module is represented in Fig. \ref{modularity}. It consists of one or multiple observers, one or multiple dispatch queues, one core, and one or multiple notifiers. Moreover, ART-SLAM is a zero-copy software, allowing the elaboration of large amount of data, while keeping it in memory. Observers allow a module to capture data as soon as it is available, independently of the type. As data can arrive at a different rates than the time required for its processing, the observers put the received data into one or multiple dispatch queues, i.e., FIFO structures with the purpose of avoiding loss of incoming data. The core of the module is its main characteristic: it elaborates one datum per queue at time, extracting it from the relative dispatch queue. As soon as the core finishes its task, it gives the byproducts of the module to the notifier, which broadcasts them to all the modules in need. The advantage of using dispatch queues is the possibility of performing the same core task in parallel, on multiple threads, if it does not require temporal coherence. This factory-like structure allows for an high degree of integration with auxiliary parts, improvements or third party modules. For example, if one would like to see the trajectory estimated by the tracker using its own implemented visualizer, it would only need to register the visualizer to the tracker and transform the broadcasted data in the desired way (data type conversion). Using this implementation brings multiple advantages over existing frameworks and middlewares, such as the possibility to execute in parallel independent core tasks, the portability (since it is embedded in ART-SLAM) and the high degree of customization. \subsection{Pre-filterer} The pre-filterer module has the purpose of reducing the size of the input point cloud and to remove noise and outliers. Data reduction, or downsampling, is essential because, as stated in the introduction, scan matching on full point clouds can become computationally demanding if the size of the cloud is large enough (more than 20K points already proves to be a bottleneck on old devices). Downsampling can reduce point clouds by a factor 5, or even more, if needed, while retaining the spatial structure and density of the initial scan. The clouds are then filtered, to remove outliers and noise points. This operation is more costly w.r.t. the downsampling task. To improve performances w.r.t. HDL \cite{koide2018portable}, we split the cloud into four pairs of octants and perform filtering on each separately, in parallel, obtaining a speedup of about $30\%$. After that, all the smaller clouds are combined together to form a larger, filtered point cloud, ready to be broadcasted to other modules. \subsection{Tracker} \label{sec:tracker} Short term data association, also known as pose tracking, establishes the motion between consecutive poses. The tracker adopts a keyframe-based approach to estimate the trajectory of the robot, performing scan-to-scan matching, using state-of-the-art algorithms (ICP \cite{besl1992method}, GICP \cite{segal2009generalized}, VGICP \cite{koide2020voxelized} and NDT \cite{biber2003normal}), depending on the user choice and the environment the robot is navigating. \textit{Keyframes} are data structures describing the motion of robot in selected locations of its trajectory. They are described by multiple variables, used to collect data associated to the pose of the robot. In ART-SLAM, each keyframe contains a point cloud and the pose (odometry) estimated by the tracker, data which is also used for loop closure detection, pose graph construction and map creation. Other useful information contained in a keyframe are the timestamp associated to the point cloud, the estimated accumulated distance from the beginning of the trajectory and, if available, acceleration and orientation coming from other sensors, such as IMU. To reduce the computational resources needed to perform SLAM, not all the filtered point clouds in input to the tracker become keyframes. With the exception of the first keyframe, which corresponds to the first point cloud received by the system, the other keyframes must satisfy at least one of the following criteria: \begin{itemize} \item Be distant from the previous keyframe of a user-defined translation $\Delta trans$ meters \item Be rotated from the previous keyframe of a user-defined angle $\Delta orientation$ radians \item Have a difference in timestamps of a user-defined interval $\Delta T$ seconds \end{itemize} The thresholds $\Delta trans$, $\Delta orientation$ and $\Delta T$ are depend on the dataset and the type of trajectory to be estimated, and should be tuned accordingly to obtain a reasonable number of keyframes, as too few would decrease the accuracy of the SLAM system, and too many would decrease its performances. In indoor scenes, for example, $\Delta trans$ could be set to $0.2$ meters, while in large scale urban environments $\Delta trans > 2$ meters. Given the cloud corresponding to the current keyframe $K_{n}$ and the available new filtered point cloud in input $c_{t}$, scan-to-scan matching is performed between them, to find their relative motion. The algorithm requires an initial guess of the motion, to boost performance and accuracy. There are two choices for the initial guess: either this is available through other means (e.g. from odometry estimated using the pretracker module), or a constant motion model is assumed, and the previous relative transformation is used (the one computed between the point cloud of the current keyframe $K_{n}$ and the previous filtered point cloud $c_{t-1}$). Usually, algorithms for point cloud-based tracking find the relative motion between consecutive clouds, $c_{t-1}$ and $c_{t}$, and then compose this transformation with the previous ones. This method may seem more accurate, but it accumulates error the more distant the clouds are from the current keyframe. In ART-SLAM, instead, the motion of the robot is always referred w.r.t. the keyframe closest in time, and the previous motion is taken into consideration only when estimating the guess for scan matching, as in the previous paragraph. This approach, which is unique to ART-SLAM (HDL does not have it) also enables the system to skip input clouds (meaning that no scan matching is performed) if pre-computed odometry is available. The latter, even if not completely accurate, allows to immediately check if the current point cloud is a candidate for the selection of a new keyframe. If it is not, the tracker does not perform scan matching, and the relative transformation between the current keyframe and the pre-computed odometry is saved to be used as motion guess in the next iteration. Skipping the scan matching step greatly benefits the performance of the tracker, as it allows to obtain accurate results in real-time. Once the tracker has detected a point cloud which satisfies the keyframe creation criteria described above, a new keyframe is built and it is broadcasted to the loop closure detection and pose-graph builder modules. \subsection{Pre-tracker} \label{sec:pretracker} Although temporally the pre-tracker module works in parallel with the pre-filterer, to understand its working principle we described first the pre-filterer and the tracker modules. Indeed, performing alignment between two full scale clouds would result in the best transformation estimate, as all the 3D points are accounted for. However, this approach is often unsuitable for real-time application, especially on low-end devices. Scan matching can be aided, as described in Subsection \ref{sec:tracker}, with an initial guess, already available, which can lower the time needed to reach matching convergence and increase the accuracy of the estimated transformation between two point clouds. To compute a viable initial guess to give the tracker, we created a pre-tracker module, which performs multi-scale scan matching, working as follows. First, the same point cloud given in input to the pre-filterer is fed to the pre-tracker. Here, it is heavily downsampled, reducing it to less than 10\% the number of its initial elements. The reduced point cloud is then used to perform scan-to-scan matching with a previously downsampled cloud. This alignment is fast, due to the reduced size of the point clouds, even if not as accurate as if it was done with non-downsampled clouds. If the number of elements of the initial point cloud is relatively large (greater than 60K 3D points), the transformation obtained through the step above is immediately broadcasted to the tracker, to be used as initial guess in the current scan matching. On the other hand, if the starting cloud size is relatively small, the whole procedure can be repeated with a different scale. The point cloud is downsampled with a scale factor lower than the one used in the first phase of the pre-tracker, to obtain a reduced cloud, with size greater than the one obtained through the first phase. Again, the obtained point cloud is used to perform scan-to-scan matching with a previously downsampled cloud, in order to obtain a fast result, but more accurate than the transformation obtained in the first phase. At this point, the relative motion resulting from the second phase is broadcasted to the tracker, to be used, as already stated, as initial guess in the current scan matching. The adoption of a pre-tracker proves to be beneficial not only in terms of accuracy, as it gives the tracker an initial guess close to the true transformation, but also in terms of performance, as it allows the tracker to skip some frames, which would not be unused anyway in the SLAM system, as described in Subsection \ref{sec:tracker}. \subsection{Floor detection} To enforce height and orientation consistency in the trajectory, filtered point clouds are processed to find the ground plane in them. This can be modeled as a four dimensional vector $GP(a,b,c,d)$ represented by the plane equation $a*x + b*y + c*z + d = 0$. Floor detection handles multiple scenarios, such as planar or planar-like motion (e.g., urban road), rough terrains (e.g. rocky paths) and environments with ascents and descents. While HDL \cite{koide2018portable} deals only with the planar motion, in ART-SLAM all the scenarios are considered. In the first case, planar motion, the floor detector module takes a point cloud and manipulates it in the following way. As, intuitively, the ground can be found within a small region of the input scan, the first step performed by the floor detector is clipping the cloud within an acceptable range of search. This step greatly reduces the cloud size, boosting performances when searching for the floor. Then, the clipped output is filtered to eliminate points whose normal is highly non-vertical. This is done to avoid possible mistakes due to planar-like surfaces in the environment, such as walls and buildings. Lastly, Random Sample Consensus (RANSAC) for plane detection is done on the filtered laser scan, to detect and estimate the ground plane coefficients. When dealing with rough terrains, a floor cannot be found in the previous way, as no planar structures can be detected with RANSAC. The input scan is further clipped, this time not vertically but horizontally: only the 3D points within a threshold distance from the center of the cloud are kept. This is done to trim the cloud to be as close as possible to the robot, to remove outlier objects such as big rocks, logs, or anything which is not planar-like. The few remaining points are then used to perform closed form plane fitting with the least squares method. Once, and if, the parameters $\{a,b,c,d\}$ are found, they are broadcasted, together with the timestamp associated to the corresponding point cloud, to the pose graph builder module. The last scenario is trickier to identify just by using a point cloud, as inclined planes are parallel to the robot wheels and cannot be distinguished from non-inclined planes by just using point clouds for detection. The process of discovery of inclined planes takes place in the pose-graph builder module. When a set of floor coefficient $\{a,b,c,d\}$ is associated to a keyframe, the builder checks if there is a noticeable change (user-defined) in vertical orientation w.r.t. the previous keyframe. If affirmative, it means that there has been a change in slope in the trajectory of the robot, and an inclined ground plane has been detected. \subsection{Loop closure} While moving, the robot may return to a place which was previously visited, forming a loop in its trajectory. Finding loops adds motion constraints in the estimated robot poses, correcting drifts and estimation errors. The hard part about loop closure is not asserting the presence of a loop, which can be accomplished via simple scan matching, but detecting when loop closure is even a possibility. To do this we need to decide when and where to look. In ART-SLAM, detection is performed in three consecutive steps, to efficiently search for loops within the collected keyframes. First, each time a keyframe $K_{query}$ is available, it is compared against all the previous existing keyframes, creating a query and candidates problem structure. Instead of performing scan-to-scan matching between all the possible pairs $\{K_{new}, K_{candidate}\}$, an odometry based selection is performed. If $K_{query}$ and $K_{candidate}$ are too close in terms of trajectory, meaning that they have a low accumulated distance, they cannot be considered candidates, as it is unlikely that two keyframes, corresponding to point clouds acquired shortly one from the other, would result in a loop. Moreover, the loop detector checks if the position, estimated through tracking, of $K_{candidate}$ is in the neighborhood of the pose corresponding $K_{query}$, within a threshold range, which accounts for drift errors induced by the tracker module. If $K_{query}$ and $K_{candidate}$ satisfy these constraints, meaning that they are sufficiently close in space and far in time, they can be considered a loop closure candidate pair, to be fed to the next phase. Once all the candidate pairs have been found, they must be further thinned down, to avoid unnecessary computation and wasted resources. The approach proposed in \cite{gkim-2018-iros} converts point clouds in 2D polar grids, and efficiently compares them using a KD-tree to select the $k$ most similar ones to a given point cloud query. The second phase for efficient loop closure detection in ART-SLAM adopts this method, by comparing the 2D polar grid of the point cloud associated to the query keyframe with the 2D polar grids corresponding to the candidate keyframes. At the end of this step, only $k$ candidate pairs for loop closure remains, ready to be used in the next, last step. The few number of candidates allows for scan-to-scan matching on each pair of point clouds, to obtain a set of relative motions. All the transformations are then compared to find the best one, i.e., the one computed with highest accuracy, and corresponding to the smallest distance between all the pairs $K_{query}$ and $K_{candidate}$. If a best match is found, a new loop has been detected, and it is added to the pose graph as a new constraint. Differently from HDL \cite{koide2018portable}, where only the first and last steps are performed, in ART-SLAM, the addition of the Scan Context method allows for scalable and efficient loop closure. Indeed, as the length of the trajectory to be estimated increases, the number of pairs to be checked for loop closures also grows in size, because more and more keyframes are added. However, the first two steps are very fast operations, with the former consisting mainly in a matrix multiplication and the latter being proved to be scalable in \cite{gkim-2018-iros}. Moreover, the 2D polar grids are pre-computed when inserting the keyframes in the pose graph, further decreasing the computation time needed by the loop closure module. At the end of the second phase, there will always be at most $k$ candidate pairs, independently from the number of keyframes to check, making this three-phased approach suitable for efficient loop closure detection. \subsection{Pose graph building and optimization} As mentioned in the introduction and in the description of the system, our framework is a form of graph SLAM \cite{grisetti2010tutorial}. In graph SLAM, the poses of the robot are modeled as nodes in a graph, named \textit{pose graph}, and labeled with their position in the environment. The nodes are connected with edges representing spatial constraints between poses, resulting from sensor measurements (e.g. IMU or GPS) or scene elements, as the floor coefficients in our case. Each node in the pose graph represents a robot position and a measurement (the point cloud) acquired at that position; moreover, each node is associated to the corresponding keyframe. An edge between two nodes consists in a probability distribution over the relative transformation of the robot poses corresponding to the nodes. These transformations are either odometry measurements given by the tracker module, between sequential positions, or are determined by aligning the sensor measurements acquired between two keyframes. Because of the noise corrupting the sensors and the drift in the robot odometry, the associated edges represent soft constraints and are not fixed. It is, however, possible to insert absolute constraints, which cannot be modified in any way. Examples of these constraints are floor coefficients, GPS or IMU data, although they can also be set, instead, as non-absolute constraints, to account for the uncertainty of the sensors or the measurement. Moreover, edges can be added when performing loop detection and closure, between non-consecutive nodes in the graph. \begin{table}[t] \vspace*{10pt} \caption{Parameters used for the experimental validation, for reproducibility, as described in \cite{amigoni2009insightful}.} \label{params} \begin{center} \begin{tabular}{|c||l||c|} \hline Module & Parameter name & Value\\ \hline \multirow{4}{*}{\textit{pre-filterer}} & Downsample method & VOXELGRID \\ & Downsample resolution & 0.25 [m] \\ & Outlier removal method & RADIUS \\ & Radius & 0.4 [m]\\ \hline \multirow{3}{*}{\textit{tracker}} & $\Delta$Trans keyframes & 5.0 [m] \\ & $\Delta$Angle keyframes & 0.25 [rad] \\ & $\Delta$Time keyframes & 1.0 [sec] \\ \hline \multirow{2}{*}{\textit{loop detector}} & Loop closure search radius & 40.0 [m] \\ & Loop closure min. distance & 25.0 [m] \\ \hline \multirow{3}{*}{\textit{scan matching}} & Registration method & FAST\_GICP \\ & Max. iterations & 64 \\ & Transformation epsilon & 0.1 \\ \hline \end{tabular} \end{center} \end{table} The structure of the pose graph is given to optimization algorithms to compute the optimal trajectory which satisfies all the sensors and motion constraints, giving high accuracy estimates, while elaborating a large number of poses. In our implementation, we use the g2o optimization framework \cite{grisetti2011g2o}, as it proves to be fast and accurate over long trajectories. Moreover g2o allows for the insertion of custom elements in the pose graph, and as such, it is an optimal solution for our modular system. The choice of modeling the trajectory of the robot as a graph is motivated by multiple reasons. First, the poses can be easily stored and visualized at any time, including also the additional information contained in the graph (edges, special nodes created from data of other sensors or ground). Furthermore, the ability of the g2o \cite{grisetti2011g2o} graph optimizer to calculate the optimal minimum cost function, to satisfy all the constraints, gives our system a high accuracy and consistency in the estimation technique for solving the SLAM problem. This is important in the case of autonomous driving, particularly in dealing with large scale environments. More details about the advantages of using graphs are in \cite{grisetti2010tutorial}. \section{Experimental validation of the system} \label{experiments} \subsection{Setup} The proposed system is compared with other methods for point cloud-based SLAM: LOAM \cite{zhang2014loam}, LeGO-LOAM \cite{shan2018lego}, A-LOAM, LeGO-LOAM-BOR and HDL \cite{koide2018portable}, with A-LOAM and LeGO-LOAM-BOR being two advanced versions of LeGO-LOAM (code improvement and re-engineering of LeGO-LOAM). We evaluate these systems in four scenarios: three coming from the KITTI dataset \cite{Geiger2012CVPR} \cite{Geiger2013IJRR}, corresponding to a short, a medium and a long sequences, respectively, and one from the RADIATE dataset \cite{sheeny2020radiate}, representing a medium sequence with no loops. \begin{figure}[t] \vspace*{10pt} \hspace{0.17em} \includegraphics[width=0.4\textwidth]{images/07_comp.png} \caption{Comparison between the trajectories estimated by LOAM \cite{zhang2014loam}, LeGO-LOAM \cite{shan2018lego}, A-LOAM, LeGO-LOAM-BOR, HDL \cite{koide2018portable} and the proposed system, on Sequence 07 of the KITTI odometry dataset \cite{Geiger2012CVPR}.} \label{07_comp} \end{figure} \iffalse \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{images/07_prop_error.png} \caption{Translation error distribution of the proposed system, on Sequence 07 of the KITTI odometry dataset \cite{Geiger2012CVPR}.} \label{07_error} \end{figure} \fi \begin{table}[t] \vspace*{10pt} \caption{ATE on Sequence 07 of KITTI odometry dataset \cite{Geiger2012CVPR}.} \label{07_table} \begin{center} \begin{tabular}{|c||c||c||c|} \hline ATE[m] & MEAN & RMSE & STD\\ \hline \textit{LOAM} & $>$10 & $>$10 & $>$10\\ \hline \textit{LeGO-LOAM} & 1.191 & 1.309 & 0.546\\ \hline \textit{A-LOAM} & 2.467 & 2.741 & 1.195\\ \hline \textit{LeGO-LOAM-BOR} & 1.604 & 1.807 & 0.832\\ \hline \textit{HDL} & 0.407 & 0.439 & \textbf{0.145}\\ \hline \textit{ART-SLAM (proposed)} & \textbf{0.405} & \textbf{0.435} & 0.157\\ \hline \end{tabular} \end{center} \end{table} LOAM, LeGO-LOAM, A-LOAM and LeGO-LOAM-BOR do not require particular parameter tuning, although they need a custom implementation of one of their modules, (point cloud projection), depending on the laser sensor used. In our tests, we changed such parameters accordingly to the sensor corresponding to the used datasets, as suggested by the authors of LeGO-LOAM. On the other hand, HDL and ART-SLAM share the same configuration parameters, e.g., keyframe selection thresholds and pre-filtering methods. Table \ref{params} shows the most important parameters used in the experiments, for both HDL and ART-SLAM, to allow reproducibility. As few systems only work on point clouds, for fair comparison, we perform SLAM only using point clouds, without exploiting data coming from other sensors, such as IMU or GPS. Experiments are tested on a 2012 Dell 64-bit laptop with Intel(R) Core(TM) i5-3337U CPU @ 1.80GHz x 4 cores, each with 3072Kb of cache size. \subsection{Comparison and results} To evaluate the systems we compute the absolute trajectory error (ATE). This metric measures the difference between points of the true and the estimated trajectory. As a pre-processing step, we associate the estimated poses with ground truth poses using the timestamps and point cloud indices. We also include a visual evaluation of the estimated trajectory and show the reconstructed 3D map in two out of the four considered scenarios. Nevertheless, all the systems run in real-time, meaning that they can process data at its acquisition rate, with the exception of HDL, which requires more time when performing both tracking and loop closure detection (about two to three times the acquisition rate). \begin{figure}[t] \vspace*{10pt} \hspace{0.15em} \includegraphics[width=0.40\textwidth]{images/026_comp.png} \caption{Comparison between the trajectories estimated by LOAM \cite{zhang2014loam}, LeGO-LOAM \cite{shan2018lego}, A-LOAM, LeGO-LOAM-BOR, HDL \cite{koide2018portable} and the proposed system, on city Sequence 05 of the KITTI raw dataset \cite{Geiger2013IJRR}.} \label{26_comp} \end{figure} \iffalse \begin{figure}[t] \centering \includegraphics[width=0.45\textwidth]{images/026_prop_error.png} \caption{Translation error distribution of the proposed system, on city Sequence 05 of the KITTI raw dataset \cite{Geiger2012CVPR}.} \label{26_error} \end{figure} \fi \begin{table}[t] \vspace*{10pt} \caption{ATE on the short city Sequence 05 of KITTI raw dataset \cite{Geiger2013IJRR}.} \label{26_table} \begin{center} \begin{tabular}{|c||c||c||c|} \hline ATE[m] & MEAN & RMSE & STD\\ \hline \textit{LOAM} & $>$5 & $>$5 & $>$5\\ \hline \textit{LeGO-LOAM} & 0.707 & 0.768 & 0.300\\ \hline \textit{A-LOAM} & 0.938 & 1.044 & 0.459\\ \hline \textit{LeGO-LOAM-BOR} & 1.094 & 1.169 & 0.409\\ \hline \textit{HDL} & \textbf{0.703} & 0.798 & 0.376\\ \hline \textit{ART-SLAM (proposed)} & \textbf{0.703} & \textbf{0.760} & \textbf{0.330}\\ \hline \end{tabular} \end{center} \end{table} Fig. \ref{07_comp} shows the estimated trajectories on Sequence 07 of the KITTI odometry dataset \cite{Geiger2012CVPR}. All the methods considered for comparison, with the exception of LOAM, accurately follow the ground truth trajectory, correctly finding the loop and optimizing the poses. LOAM, instead, quickly drifts apart from the true trajectory: this is caused by the fact that no loop closure is performed, differently from the other systems. Table \ref{07_table} further details the obtained results, as it represents the mean, root mean squared error (RMSE) and standard deviation (STD) of the absolute trajectory error, in meters. The proposed system has highest accuracy, along with HDL. It should not come as a surprise, since those methods rely on full point cloud scan-to-scan matching, while the other methods rely on tracking and matching 3D features extracted from point clouds. After having dealt with a large sequence with the presence of loops, we also evaluated the systems on a shorter sequence. As short datasets do not have a ground truth, we use, instead, GPS data, provided along with the point clouds. Fig. \ref{26_comp} shows the estimated trajectories on city Sequence 05 of the KITTI raw dataset \cite{Geiger2013IJRR}. As before, all the methods except for LOAM, accurately represent the ground truth, with small errors in the trajectory. It should not come as a surprise that the results are more or less the same, as for short trajectories tracking is performed a limited amount of times, and there is not enough distance to suffer from accumulated errors. Table \ref{26_table} shows the ATE statistics, in meters. As before, all the systems, with the exception of LOAM, show good results, accurately following the GPS signal, here used as ground truth due to its relatively high accuracy. \begin{figure}[t] \vspace*{10pt} \hspace{0.15em} \includegraphics[width=0.4\textwidth]{images/00_comp.png} \caption{Comparison between the trajectories estimated by LeGO-LOAM \cite{shan2018lego}, LOAM \cite{zhang2014loam}, HDL \cite{koide2018portable} and the proposed system, on sequence 00 of the KITTI odometry dataset \cite{Geiger2012CVPR}.} \label{00_comp} \end{figure} \iffalse \begin{figure}[t] \centering \includegraphics[width=0.4\textwidth]{images/00_prop_error.png} \caption{Translation error distribution of the proposed system, on city Sequence 00 of the KITTI raw dataset \cite{Geiger2012CVPR}.} \label{00_error} \end{figure} \fi \begin{table}[t] \vspace*{10pt} \caption{ATE on Sequence 00 of KITTI odometry dataset \cite{Geiger2012CVPR}.} \label{00_table} \begin{center} \begin{tabular}{|c||c||c||c|} \hline ATE[m] & MEAN & RMSE & STD\\ \hline \textit{LeGO-LOAM} & 9.537 & 11.666 & 6.718\\ \hline \textit{LeGO-LOAM-BOR} & 6.240 & 6.613 & 2.188\\ \hline \textit{HDL} & \textbf{1.078} & \textbf{1.224} & 0.579\\ \hline \textit{ART-SLAM (proposed)} & 1.119 & 1.352 & \textbf{0.539}\\ \hline \end{tabular} \end{center} \end{table} \begin{figure}[t] \centering \vspace*{10pt} \includegraphics[width=0.25\textwidth]{images/kitti_map.png} \caption{Map corresponding to Sequence 00 of the KITTI odometry dataset \cite{Geiger2012CVPR}, built by the proposed algorithm.} \label{00_map} \end{figure} \begin{figure}[t] \centering \vspace*{10pt} \includegraphics[width=0.28\textwidth]{images/kitti_detail.png} \caption{Detailed area of the map corresponding to Sequence 00 of the KITTI odometry dataset \cite{Geiger2012CVPR}, built by the proposed algorithm.} \label{00_detail} \end{figure} In Fig. \ref{00_comp}, we show the behavior of ART-SLAM on one of most complex sequences, i.e, Sequence 00 of the KITTI odometry dataset. In the comparison, we did not include LOAM and A-LOAM, which estimated trajectories are far off the ground truth, and would have cluttered the figure. Fig. \ref{00_map} and Fig. \ref{00_detail} show the map reconstructed by ART-SLAM and a detailed area of it, respectively. From Table \ref{00_table}, one can see the high degree of accuracy achieved by the proposed system, reaching low translation error almost on par with HDL. \iffalse \begin{figure*}[t] \centering \includegraphics[width=0.70\textwidth]{images/07_ukf.png} \caption{Translation error distribution of the proposed system, on Sequence 07 of the KITTI odometry dataset \cite{Geiger2012CVPR}, obtained with the aid of GPS and IMU.} \label{07_ukf} \end{figure*} \fi \begin{figure}[t] \centering \vspace*{10pt} \includegraphics[width=0.25\textwidth]{images/radiate_c01_map.png} \caption{Map corresponding to City Sequence 01 of the RADIATE dataset \cite{sheeny2020radiate}, built by the proposed algorithm.} \label{c01_map} \end{figure} \begin{figure}[t] \centering \includegraphics[width=0.25\textwidth]{images/radiate_c01_det.png} \caption{Detailed area of the map corresponding to City Sequence 01 of the RADIATE dataset \cite{sheeny2020radiate}, built by the proposed algorithm.} \label{c01_detail} \end{figure} \begin{figure}[t] \centering \vspace*{10pt} \includegraphics[width=0.48\textwidth]{images/rad_01_comp.png} \caption{Comparison between the trajectories estimated by LeGO-LOAM-BOR, HDL \cite{koide2018portable} and the proposed system, on City Sequence 01 of the RADIATE dataset \cite{sheeny2020radiate}.} \label{c01_comp} \end{figure} Lastly, we show a visual evaluation of the accuracy achieved by ART-SLAM on the City 01 Sequence of the RADIATE dataset \cite{sheeny2020radiate}. This sequence is relatively long and does not contain loop closures, increasing the difficulty of estimating the robot trajectory. As there is no ground truth, we perform a visual inspection of the created 3D map, to check for inconsistencies. The map obtained through ART-SLAM, completely visible in Fig. \ref{c01_map} and detailed in Fig. \ref{c01_detail}, shows a noticeable coherence with the structure of the road and the elements within it, once again proving the accuracy of the proposed system. Moreover, Fig. \ref{c01_comp} shows a comparison of the obtained trajectory with HDL and LeGO-LOAM-BOR (the other systems could not run the scenario), proving that ART-SLAM is accurate even when no loop closure is available. \section{Conclusions} \label{conclusions} We have proposed ART-SLAM, a fast and ground-optimized LiDAR odometry and mapping method, able to perform pose estimation of moving robots in complex environments. ART-SLAM, differently from state-of-the-art systems, is not bound to any framework, and can be easily ported on any device. It is also efficiently improvable and extendable, due the independent nature of its modules, and it includes many upgrades w.r.t. existing similar systems, such as pre-tracking, smart loop closure and optimized loop detection. The proposed method is evaluated on a series of datasets corresponding to outdoor environments, representing either short, medium or long sequences. The results show that ART-SLAM can achieve similar or better accuracy when compared with the state-of-the-art, with reduced computational cost w.r.t. high accuracy systems. The proposed system proves to be as fast as feature-based systems, meaning real-time or near real-time performance, and accurate as full point clouds scan matching methods. \addtolength{\textheight}{-0cm} \printbibliography \end{document}
{'timestamp': '2021-09-14T02:21:21', 'yymm': '2109', 'arxiv_id': '2109.05483', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05483'}
arxiv
\section{Data Collection Details} \label{appdx:data_collection_details} In our first annotation stage (Section~\ref{subsec:stage_1_annotation}), we provide a broad definition of hate speech grounded in Twitter’s hateful conduct policy \cite{twitterPolicy}, and detailed definitions for what constitutes explicit hate, implicit hate, and non-hateful content with examples from each class. We explain that explicit hate speech contains explicit keywords directed towards a protected entity. We define implicit hate speech as outlined in the paper and ground this definition in a quote from Lee Atwater on how discourse can appeal to racists without sounding racist: ``\textit{You start out in 1954 by saying, “N*gger, n*gger, n*gger.” By 1968 you can’t say “n*gger”—that hurts you, backfires. So you say stuff like, uh, forced busing, states’ rights, and all that stuff, and you’re getting so abstract}''. To ensure quality, we chose only AMT Master workers who (1) have approval rate >98\% and more than 5000 HITs approved, (2) scored $\geq90\%$ on our five-question qualification test where they must (a) identify the differences between explicit and implicit hate speech and (b) identify the hate target even if the target is not explicitly mentioned. Figures~\ref{fig:amt_stg_1_ui} and~\ref{fig:amt_instructions} depict snippets of the first stage annotation task and the instructions provided to guide the annotators, respectively. For the second-stage annotation (Section~\ref{subsec:stage_2_annotation}), we observed the following per-category kappa scores at the beginning/middle: (threatening, 1.00/0.66), (stereotypical, 0.67/0.55), (grievance, 0.61/0.63), (incitement, 0.63/0.53), (not hate, 0.55/0.54), (inferiority, 0.47/0.41), and (irony, 0.40/0.31). Even in the worst case, there was fair to moderate agreement. We will add these metrics to the Appendix. The total annotation cost for Stage 1 and 2 was \$15k. Limited by our budget, we chose to employ expert annotators to label independent portions of the data once we observed fair to substantial agreement among them. Figure~\ref{fig:amt_stg_2_ui} depicts a snippet of the hate target and implied statement data collection for each implicit hate speech post. \clearpage \begin{figure*}[htbp] \centering \includegraphics[width =\textwidth]{figures/stg_2_AMT_UI.png} \caption{Amazon Mechanical Turk interface used to collect the hate target and the implied statement per implicit hate speech post.} \label{fig:amt_stg_2_ui} \end{figure*} \clearpage \begin{figure*} \begin{subfigure}{\textwidth} \centering \includegraphics[width=0.9\textwidth]{figures/AMT_instruction_1.png} \label{fig:sfig1} \end{subfigure}\\% \\ \begin{subfigure}{\textwidth} \centering \includegraphics[width=.9\linewidth]{figures/AMT_instruction_2.png} \label{fig:sfig2} \end{subfigure} \begin{subfigure}{\textwidth} \centering \includegraphics[width=.9\linewidth]{figures/AMT_instruction_3.png} \label{fig:sfig3} \end{subfigure} \caption{Instructions and examples provided to Amazon Mechanical Turk workers. Our definition of hate speech is grounded in social media communities' rules.} \label{fig:amt_instructions} \end{figure*} \clearpage \begin{table*}[htbp] \resizebox{\textwidth}{!}{% \begin{tabular}{lcccccccccccccccc}\toprule & \multicolumn{4}{c}{\textbf{Macro}} & \phantom{abc} & \multicolumn{3}{c}{\textbf{Grievance}} & \phantom{abc} & \multicolumn{3}{c}{\textbf{Incitement}} & \phantom{abc} & \multicolumn{3}{c}{\textbf{Inferiority}} \\ \cmidrule{2-5} \cmidrule{7-9} \cmidrule{11-13} \cmidrule{15-17} & P & R & F & Acc && P & R & F && P & R & F && P & R & F \\ \midrule SVM (n-grams) & 48.8 & 49.2 & 48.4 & 54.2 && 65.6 & 53.6 & 59.0 && 53.7 & 55.8 & 54.7 && 49.7 & 46.4 & 48.0 \\ SVM (TF-IDF) & 53.0 & 51.7 & 51.5 & 56.5 && 66.9 & 56.7 & 61.4 && 60.4 & 56.2 & 58.2 && 46.0 & 45.3 & 45.6 \\ SVM (GloVe) & 46.8 & 48.9 & 46.3 & 51.3 && 63.7 & 48.6 & 55.1 && 55.2 & 46.7 & 50.6 && 45.8 & 39.7 & 42.5 \\ BERT & \textbf{59.1} & 57.9 & 58.0 & 62.9 && 65.4 & 63.9 & 64.6 && 62.4 & \textbf{56.6} & 59.4 && \textbf{65.4} & 57.9 & 61.4\\ BERT + Aug & 58.6 &\textbf{ 59.1} & \textbf{58.6} & \textbf{63.8} && 67.6 & \textbf{65.7} & \textbf{66.6} && \textbf{66.8} & 56.5 & \textbf{61.2} && 61.0 & 59.0 & 59.9\\ BERT + Aug + Wikidata & 53.9 & 55.3 & 54.4 & 62.8 && \textbf{68.8} & 63.0 & 65.8 && 62.7 & 55.9 & 59.1 && 60.3 & \textbf{60.8} & \textbf{60.4}\\ BERT + Aug + ConceptNet & 54.0 & 55.4 & 54.3 & 62.5 && 67.6 & 64.9 & 66.2 && 63.8 & 52.7 & 57.7 && 62.1 & 57.7 & 59.7\\ \bottomrule\\ \\ \end{tabular} } \resizebox{13.3cm}{!}{% \begin{tabular}{lccccccccccccc}\toprule & \multicolumn{3}{c}{\textbf{Irony}} & \phantom{abc} & \multicolumn{3}{c}{\textbf{Stereotypical}} & \phantom{abc} & \multicolumn{3}{c}{\textbf{Threatening}} & \phantom{abc} \\ \cmidrule{2-4} \cmidrule{6-8} \cmidrule{10-12} & P & R & F && P & R & F && P & R & F \\ \midrule SVM (n-grams) & 41.4 & 51.8 & 46.0 && 60.7 & 52.7 & 56.4 && 52.0 & 72.2 & 60.5 \\ SVM (TF-IDF) & 43.9 & 55.4 & 48.9 && 60.9 & 58.8 & 59.8 && 55.3 & 72.2 & 62.7 \\ SVM (GloVe) & 48.7 & 55.4 & 51.8 && 59.3 & 53.9 & 56.5 && 50.2 & 74.3 & 59.9 \\ BERT & \textbf{62.3} & \textbf{63.8} & \textbf{63.0} && 58.5 & 69.3 & 63.4 && \textbf{67.2} & 71.5 & 69.3\\ BERT + Aug & 62.0 & 62.3 & 62.1 &&\textbf{ 62.0} & \textbf{70.1} & \textbf{65.8} && 65.0 & \textbf{75.6} & \textbf{69.8}\\ BERT + Aug + Wikidata & 60.0 & 63.1 & 61.4 && 60.7 & 69.3 & 64.7 && 64.2 & 73.8 & 68.6\\ BERT + Aug + Conceptnet & 61.5 & 63.3 & 62.3 && 59.1 & 70.0 & 64.0 && 62.4 & 74.7 & 67.9\\ \bottomrule \end{tabular} } \caption{Fine-grained implicit hate classification performance, averaged across five random seeds. Macro scores are further broken down into category-level scores for each of the six main implicit categories, and we omit scores for \textit{other}. Again, the BERT-based models beat the linear SVMs on $F_1$ performance across all categories. Generally, augmentation improves recall, especially for two of the minority classes, \textit{inferiority} and \textit{threatening}, as expected. Knowledge graph integration (Wikidata, Conceptnet) does not appear to improve the performance. } \label{tab:impl_classwise_1} \end{table*} \clearpage \begin{table*}[t] \centering \footnotesize \resizebox{\textwidth}{!}{% \begin{tabular}{ccccccc} \toprule & \textbf{White Nationalist} & \textbf{Neo-Nazi} & \textbf{A-Immgr} & \textbf{A-MUS} & \textbf{A-LGBTQ} & \textbf{KKK} \\ \midrule \multirow{5}{1.5cm}{Nouns\\ (N)}& identity & adolf & immigration &islam& potus& ku\\ & evropa & bjp & sanctuary&jihad &democrats & klux\\ & activists & india & aliens&islamic & trump& hood\\ & alt-right & modi & border& muslim(s)&abortion & niggas\\ & whites & invaders &cities &sharia &dumbocrats & brother\\ \midrule \multirow{5}{1.5cm}{Adjectives (A)} & white &more& illegal& muslim & black & alive\\ & hispanic &non-white &immigrant &political & crooked& edgy\\ & anti-white & german&dangerous &islamic & confederate& white\\ & third &national-socialist &ice & migrant&fake & outed\\ & racial & white&criminal &moderate &racist & anonymous\\ \midrule \multirow{5}{1.5cm}{Hashtags (\#)}& \#projectsiege & \#swrm & \#noamnesty& \#billwarnerphd& \#defundpp& \#opkkk\\ & \#antifa & \#workingclass & \#immigration& \#stopislam&\#pjnet & \#hoodsoff\\ & \#berkrally & \#hitler&\#afire & \#makedclisten& \#unbornlivesmatter& \#mantears\\ & \#altright & \#freedom& \#fairblog&\#bansharia & \#religiousfreedom& \#kkk\\ & \#endimmigration & \#wpww&\#stopsanctuarycities & \#cspi&\#prolife & \#anonymous\\ \bottomrule \end{tabular} } \caption{Top five salient nouns, adjectives, and hashtags identified by measuring the log odds ratio informative Dirichlet prior~\cite{monroe2008fightin} for the following ideologies: White Nationalist, Neo-Nazi, Anti-Immigrant (A-Immgr), Anti-Muslim (A-MUS), Anti-LGBTQ (A-LGBTQ), and Ku Klux Klan (KKK). } \label{tab:hate_salient_kwds} \end{table*} \section{Introduction} Hate speech is pervasive in social media. Platforms have responded by banning hate groups and flagging abusive text \cite{klepper_2020}, and the research community has developed increasingly competitive hate speech detection systems \cite{fortuna2018survey,badjatiya2017deep}. While prior efforts have focused extensively on overt abuse or \textit{explicit hate speech} \cite{schmidt2017survey}, recent works have started to highlight the diverse range of \textit{implicitly} hateful messages that have previously gone unnoticed by moderators and researchers alike \cite{jurgens2019just,waseem2017understanding,qian2019learning}. Figure~\ref{fig:crownjewel} provides an example from each hate speech type (explicit vs. implicit). \begin{figure}[!tb] \centering \includegraphics[width=8cm, height = 6cm]{figures/crown_jewel.png} \caption{Sample posts from our dataset outlining the differences between explicit and implicit hate speech. Explicit hate is \textbf{direct} and leverages specific keywords while implicit hate is more \textbf{abstract}. Explicit text has been modified to include a star (*). } \label{fig:crownjewel} \end{figure} Implicit hate speech is defined by \textit{coded} or \textit{indirect} language that disparages a person or group on the basis of protected characteristics like race, gender, and cultural identity~\cite{nockleby2000hate}. Extremist groups have used this coded language to mobilize acts of aggression \cite{gubler2015violent} and domestic terrorism \cite{piazza2020politician} while also maintaining \textit{plausible deniability} for their actions \cite{denigot2020dogwhistles}. Because this speech lacks clear lexical signals, hate groups can evade keyword-based detection systems \cite{waseem2017understanding,wiegand2019detection}, and even the most advanced architectures may suffer if they have not been trained on implicitly abusive messages \cite{caselli2020feel}. The primary challenge for statistical and neural classifiers is the linguistic nuance and diversity of the implicit hate class, which includes indirect sarcasm and humor \cite{waseem2016hateful,fortuna2018survey}, euphemisms \cite{magu2018determining}, circumlocution \cite{gao2017detecting}, and other symbolic or metaphorical language \cite{qian2019learning}. The type of implicit hate speech also varies, from dehumanizing comparisons \cite{leader2016dangerous} and stereotypes \cite{warner2012detecting}, to threats, intimidation, and incitement to violence \cite{sanguinetti2018italian,fortuna2018survey}. Importantly, the field lacks a theoretically-grounded framework and a large-scale dataset to help inform a more empirical understanding of implicit hate in all of its diverse manifestations. To fill this gap, we establish new resources to sustain research and facilitate both fine-grained classification and generative intervention strategies. Specifically, we develop a 6-class taxonomy of implicit hate speech that is grounded in the social science literature. We use this taxonomy to annotate a new Twitter dataset with broad coverage of the most prevalent hate groups in the United States. This dataset makes three original contributions: (1) it is a large and representative sample of \textit{implicit} hate speech with (2) fine-grained \textit{implicit hate labels} and (3) natural language descriptions of the \textit{implied aspects} for each hateful message. Finally, we train competitive baseline classifiers to detect implicit hate speech and generate its implied statements. While state-of-the-art neural models are effective at a high level hate speech classification, they are not effective at spelling out more fine-grained categories with detailed explanations the implied message. The results suggest our dataset can serve as a useful benchmark for understanding implicit hate speech. \section{Related Work} Numerous hate speech datasets exist, and we summarize them in Table~\ref{tab:hate_speech_data}. The majority are skewed towards \textit{explicitly} abusive text since they were originally seeded with hate lexicons \cite{basile2019semeval,founta2018large,davidson2017automated,waseem2016hateful}, racial identifiers \cite{warner2012detecting}, or explicitly hateful phrases such as ``I hate \textit{<target>}''~\cite{silva2016analyzing}. Because of a heavy reliance on overt lexical signals, explicit hate speech datasets have known racial biases \cite{sap2019risk}. Among public datasets, all but one have near or above a 20\% concentration of profanity\footnote{We use the swear word list from https://bit.ly/2SQySZv, excluding ambiguous terms like \textit{bloody}, \textit{prick}, etc.} in the hate class (Table~\ref{tab:hate_speech_data}). A few neutrally-seeded datasets also exist \cite{burnap2014hate,de2018hate,warner2012detecting}. Although some may contain implicit hate speech, there are no \textit{implicit hate labels} and thus the distribution is unknown. Furthermore, these datasets tend to focus more on controversial events (e.g. the Lee Rigby murder; \citeauthor{burnap2014hate}) or specific hate targets (e.g. immigrants; \citeauthor{basile2019semeval}), which may introduce \textit{topic bias} and artificially inflate model performance on implicit examples \cite{wiegand2019detection}. Consider \citet{sap-etal-2020-social} for example: 31\% of posts take the form of the question leading up to a mean joke. There is still need for a representative and syntactically diverse implicit hate benchmark. Our contribution is similar to the Gab Hate Corpus of \citet{kennedy2018gab}, which provides both explicit and implicit hate and target labels for a random sample of 27K Gab messages. We extend this work with a \textit{theoretically-grounded taxonomy} and \textit{fine-grained labels for implicit hate speech} beyond the umbrella categories, Assault on Human Dignity (HD) and Call for Violence (CV). Following the work of \citet{sap-etal-2020-social}, we provide free-text annotations to capture messages' pragmatic implications. However, we are the first to take this framework, which was originally applied stereotype bias, and extend it to \textit{implicit} hate speech more broadly. Implicitly stereotypical language is just a subset of the implicit hate we cover, since we also include other forms of sarcasm, intimidation or incitement to violence, hidden threats, white grievance, and subtle forms of misinformation. Our work also complements recent efforts to capture and understand \textit{microaggressions} \cite{breitfeller2019finding}, a similarly elusive class that draws on subtle and \textit{unconscious} linguistic reflections of social bias, prejudice and inequality \cite{sue2010microaggressions}. Similar to \citet{breitfeller2019finding}, we provide a representative and domain-general typology and dataset, but ours are more representative of \textit{active hate groups} in the United States, and our definitions extend to \textit{intentionally} veiled acts of intimidation, threats, and abuse. \begin{table*}[t] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{L{35mm}L{18mm}L{30mm}rrccccc} \toprule \textbf{Work} & \textbf{Source}&\textbf{Domain / Scope}&\textbf{Size}&\textbf{Balance}&\textbf{Expletives}&\textbf{Public}&\textbf{Target}&\textbf{Implicit}&\textbf{Implied}\\ \midrule \citet{basile2019semeval} & Twitter & \href{https://github.com/msang/hateval/blob/master/keyword_set.md}{Misogynistic, \newline anti-immigrant} & 19,600 & Unknown & Unknown & \href{https://competitions.codalab.org/competitions/19935}{\ding{51}} & \ding{51} & & \\ \hline \citet{burnap2014hate} & Twitter & Lee Rigby murder & 1,901 & 11.7\% & Unknown & & & \\ \hline \citet{davidson2017automated} & Twitter & HateBase terms & 24,802 & 5.0\% & 69.8\% & \href{https://github.com/t-davidson/hate-speech-and-offensive-language/tree/master/data}{\ding{51}} & & & \\ \hline \citet{djuric2015hate} & Yahoo \newline Finance & Unknown & 951,736 & 5.9\% & Unknown & & & \\ \hline \citet{founta2018large} & Twitter & Offensive terms & 80,000 & 7.5\% & 73.9\% & \href{https://github.com/ENCASEH2020/hatespeech-twitter}{\ding{51}} & & \\ \hline \citet{gao2017detecting} & Fox News \newline Comments & Unknown & 1,528 & 28.5\% & Unknown & & & \\ \hline \citet{de2018hate} & Stormfront & One hate group & 9,916 & 11.3\% & 7.8\% & \href{https://github.com/Vicomtech/hate-speech-dataset}{\ding{51}} & & \\ \hline \citet{kennedy2018gab} & Gab & Random sample & 27,665 & 9.1\% & 28.2\% & \href{https://osf.io/edua3/}{\ding{51}} & \ding{51} & \ding{51} \\ \hline \citet{sap-etal-2020-social} & Compilation & Mixed & 44,671 & 44.8\% & 28.5\% & \href{https://homes.cs.washington.edu/~msap/social-bias-frames/}{\ding{51}} & \ding{51} & & \ding{51} \\ \hline \citet{warner2012detecting} & Yahoo + \newline Web & Anti-semitic & 9,000 & Unknown & Unknown & \ding{51} & & \\ \hline \citet{waseem2016hateful} & Twitter & Sexist, racist terms & 16,914 & 31.7\% & 17.6\% & \href{https://github.com/ZeerakW/hatespeech}{\ding{51}} & & & \\ \hline \citet{zampieri2019predicting} & Twitter & Political phrases & 14,000 & 32.9\% & Unknown & \href{https://competitions.codalab.org/competitions/20011\#learn_the_details}{\ding{51}} & \ding{51} & & \\ \hline \textsc{Implicit Hate Corpus} (ours) & Twitter & Hate groups & 22,584 & 39.6\% & 3.2\% & \ding{51} & \ding{51} & \ding{51} & \ding{51} \\ \hline \bottomrule \end{tabular}% } \caption{Summary of English hate speech datasets in terms of \textit{Domain / Scope}, \textit{Size}, hate class \textit{Balance} ratio, the proportion of \textit{Expletives} in the hate class, and the inclusion of \textit{Target} demographic, binary \textit{Implicit} hate speech labels, and \textit{Implied} statement summaries. Most datasets cover a narrow subset of hate speech like anti-semitism or sexism, and do not include implicit hate labels. Ours is the first to include a fine-grained implicit hate taxonomy. } \label{tab:hate_speech_data} \end{table*} \section{Taxonomy of Implicit Hate Speech} \label{section:theory} Implicit hate speech is a subclass of hate speech defined by \textit{the use of coded or indirect language} such as sarcasm, metaphor and circumlocution to disparage a protected group or individual, or to convey prejudicial and harmful views about them \cite{gao2017recognizing,waseem2017understanding}. The NLP community has not yet confronted, in a consistent and unified manner, the multiplicity of subtle challenges that implicit hate presents for online communities. To this end, we introduce a new typology for characterizing and detecting different forms of implicit hate, based on social science and relevant NLP literature. Our categories are not necessarily mutually exclusive, but they represent principle axes of implicit hate, and while they may not be collectively exhaustive, we find they cover 98.6\% of implicit hate in a representative sample of the most prevalent hate ideologies in the U.S. \textbf{White Grievance} includes frustration over a minority group's perceived privilege and casting majority groups as the real victims of racism \citep{berbrier2000victim,bloch2020playing}. This language is linked to extremist behavior and support for violence \citep{miller2020hate}. An example is \textit{Black lives matter and white lives don't? Sounds racist.} \textbf{Incitement to Violence} includes flaunting in-group unity and power or elevating known hate groups and ideologies \cite{somerville2011violence}. Phrases like \textit{`white brotherhood} operate in the former manner, while statements like \textit{Hitler was Germany -- Germans shall rise again!} operate in the latter, elevating nationalism and Nazism. Article 20 of the UN International Covenant on Civil and Political Rights \cite{assembly1966international} states that speech which incites violence shall be prohibited by law. \textbf{Inferiority Language} implies one group or individual is inferior to another \cite{nielsen2002subtle}, and it can include dehumanization (denial of a person's humanity), and toxification (language that compares the target with disease, insects, animals), both of which are early warning signs of genocide \cite{leader2016dangerous,neilsen2015toxification}. Inferiority language is also related to \textit{assaults on human dignity} \cite{kennedy2018gab}, \textit{dominance} \cite{saha2018hateminers}, and \textit{declarations of superiority of the in-group} \cite{fortuna2018survey}. For example, \textit{It's not a coincidence the best places to live are majority white}. \textbf{Irony} refers to the use of sarcasm \cite{waseem2016hateful,justo2014extracting}, humor \cite{fortuna2018survey}, and satire \cite{sanguinetti2018italian} to attack or demean a protected class or individual. For example, in the context of one hate group, the tweet \textit{Horrors... Disney will be forced into hiring Americans} works to discredit Disney for allegedly hiring only non-citizens or, really, non-whites. Irony is not exempt from our hate speech typology, since it is commonly used by modern online hate groups to mask their hatred and extremism \citep{dreisbach_2021}. \textbf{Stereotypes and Misinformation} associate a protected class with negative attributes such as crime or terrorism \cite{warner2012detecting,sanguinetti2018italian} as in the rhetorical question, \textit{Can someone tell the black people in Chicago to stop killing one another before it becomes Detroit?} This class also includes misinformation that feeds stereotypes and vice versa, like holocaust denial and other forms of historical negationism \cite{belavusau2017hate,cohen2009holocaust}. \textbf{Threatening and Intimidation} convey a speaker commitment to a target's pain, injury, damage, loss, or violation of rights. While explicitly violent threats are well-recognized in the hate speech literature \cite{sanguinetti2018italian}, here we highlight threats related to implicit violation of rights and freedoms, removal of opportunities, and more subtle forms of intimidation, such as \textit{All immigration of non-whites should be ended.} \section{Data Collection and Annotation} \label{section:data_collection} We collect and annotate a benchmark dataset for implicit hate language using our taxonomy. Our main source of data uses content published by online hate groups and their followers on Twitter for two reasons. First, as modern hate groups have become more active online, they provide an increasingly vivid picture of the more subtle and coded forms of hate that we are interested in. Second, the problem of hateful misinformation is compounded on social media platforms like Twitter where around 3 out of 4 users get their news \cite{shearer2017news}. This motivates a representative sample of \textit{online} communication exchanged on \textit{Twitter} between members of the \textit{most prominent U.S hate groups}. We focus on the eight largest ideological clusters of U.S. hate groups as given by the \citet{splc2019} report. These ideological classes are \textit{Black Separatist} (27.1\%), \textit{White Nationalist} (16.4\%), \textit{Neo-Nazi} (6.2\%), \textit{Anti-Muslim} (8.9\%), \textit{Racist Skinhead} (5.1\%), \textit{Ku Klux Klan} (5.0\%), \textit{Anti-LGBT} (7.4\%), and \textit{Anti-Immigrant} (2.12\%). Detailed background and discussion on each hate ideology can be found at the the SPLC Extremist Files page \cite{splc2020}. \subsection{Data Collection and Filtering}\label{sec:data_collection} We matched all SPLC hate groups with their corresponding Twitter accounts using the account names and bios. Then, for each ideological cluster above, we selected the three hate group accounts with the most followers, since these were likely to be the most visible and engaged. We collected all tweets, retweets, and replies from the timelines of our selected hate groups between January 1, 2015 and December 31, 2017, for a total of 4,748,226 tweets, giving us with an broad sample of hate group activity before many accounts were banned. Hateful content is semantically diverse, with different hate groups motivated by different ideologies. Seeking a representative sample, we identified group-specific salient content from each ideology by performing part of speech (POS) tagging on each tweet. Then we computed the log odds ratio with informative Dirichlet prior~\cite{monroe2008fightin} for each noun, hashtag, and adjective to identify the top 25 words per ideology. After filtering for tweets that contained one of the salient keywords, we ran the 3-way HateSonar classifier of \citet{davidson2017automated} to remove content that was likely to be explicitly hateful. Specifically, we removed all tweets that were classified as \textit{offensive}, and then ran a final sweep over the \textit{neutral} and \textit{hate} categories, removing tweets that contained any explicit keyword found in NoSwear \cite{noSwearing} or Hatebase \cite{hatebase2020}. \subsection{Crowdsourcing and Expert Annotation} \label{subsection:annotation} To acquire implicit hate speech labels with two different resolutions, we ran two stages of annotation. First, we collected high-level labels, \textit{explicit hate, implicit hate,} or \textit{not hate}. Then, we took a second pass through the implicit hate tweets with expert annotation over the fine-grained implicit hate taxonomy from Section~\ref{section:theory}. \subsubsection{Stage 1: High Level Categorization} \label{subsec:stage_1_annotation} Amazon Mechanical Turk (MTurk) annotators completed our high-level labeling task. We provided them with a definition of hate speech \cite{twitterPolicy} and examples of explicit, implicit, and non-hateful content (See Appendix~\ref{appdx:data_collection_details}), and required them to pass a short five-question qualification check for understanding with a score of at least 90\% in accordance with crowdsourcing standards~\cite{sheehan2018crowdsourcing}. We paid annotators a fair wage above the federal minimum. Three workers labeled each tweet, and they reached majority agreement for 95.3\% of tweets, with perfect agreement on 45.6\% of the data. The Intraclass Correlation for one-way random effects between $k=118$ raters was $ICC(1, k) = 0.616$, which indicates moderate inter-rater agreement. Using the majority vote, we obtained consensus labels for 19,112 labeled tweets in total: 933 \textit{explicit hate}, 4,909 \textit{implicit hate}, and 13,291 \textit{not hateful} tweets. \subsubsection{Stage 2: Fine-Grained Implicit Hate} \label{subsec:stage_2_annotation} To promote a more nuanced understanding of our 4,909 implicit hate tweets, we labeled them using our fine-grained category definitions in Section~\ref{section:theory}, adding \textit{other} and \textit{not hate} to take care of any other situations. Since these fine-grained categories were too subtle for MTurk workers,\footnote{We saw less than 30\% agreement when we ran this task over three batches of around 200 tweets each on MTurk.} we hired three research assistants to be our expert annotators. We trained them over multiple sessions by walking them through seven small pilot batches and resolving disagreements after each test until they reached moderate agreement. On the next round of 150 tweets, their independent annotations reached a Fleiss' Kappa of 0.61. Each annotator then continued labeling an independent partition of the data. Halfway through this process, we ran another attention check with 150 tweets and found that agreement remained consistent with a Fleiss' Kappa of 0.55. Finally, after filtering out tweets marked as \textit{not hate}, there were 4,153 labeled implicit hate tweets remaining. The per-category statistics are summarized in the \textit{\# Tweets Pre Expn.} column of Table~\ref{tab:impl_class_distr}. \subsubsection{Corpus Expansion} Extreme class imbalance may challenge implicit hate classifiers. To address this disparity, we expand the minority classes, both with bootstrapping and out-of-domain samples. For bootstrapping, we trained a 6-way BERT classifier on the 4,153 implicit hate labels in the manner of Section~\ref{subsection:experimental_settings} and ran it on 364,300 unlabeled tweets from our corpus. Then we randomly sampled 1,800 tweets for each of the three minority classes according to the classifications \textit{inferiority}, \textit{irony}, and \textit{threatening}. Finally, we augmented this expansion with out-of-domain (OOD) samples from \citet{kennedy2018gab} and \citet{sap-etal-2020-social}. By drawing both from OOD and bootstrapped in-domain samples, we sought to balance two key limitations: (1) bootstrapped samples may be inherently easier, while (2) OOD samples contain artifacts that allow models to benefit from spurious correlations. Our expert annotators labeled this data, and by adding the minority labels from this process, we improved the class balance for a total of 6,346 implicit tweets shown in the \textit{\#~Tweets~Post~Expn.} column of Table~\ref{tab:impl_class_distr}. \begin{table}[t] \centering \small \begin{tabular}{L{1.8cm}R{1.3cm}R{1.4cm}R{1.4cm}} \toprule \textbf{\newline Label} & \textbf{\# Tweets \newline Pre Expn} & \textbf{\# Tweets \newline Post Expn} & \textbf{\% \newline Post Expn} \\ \midrule Grievance & 1,455 & 1,538 & 24.2\% \\ Incitement & 1,176 & 1,269 & 20.0\%\\ Inferiority & 241 & 863 & 13.6\%\\ Irony & 134 & 797 & 12.6\% \\ Stereotypical & 1,032 & 1,133 & 17.9\% \\ Threatening & 57 & 666 & 10.5\% \\ Other & 58 & 80 & 1.2\% \\ \midrule Total & 4,153 & 6,346 & 100\% \\ \bottomrule \end{tabular} \caption{Implicit hate category label distribution before and after the expansion stage} \label{tab:impl_class_distr} \end{table} \subsubsection{Hate Targets and Implied Statement} \label{section:implied_annotation} For each of the 6,346 implicit hate tweets, two separate annotators provided us with the message's \textit{target demographic group} and its \textit{implied statement} in free-text format. Implied statements were formatted as Hearst-like patterns~\cite{indurkhya2010handbook} of the form \textit{<target> \{do, are, commit\} <predicate>}, where \textit{<target>} might be phrases such as \textit{immigrants, black folks}. \begin{table*}[t] \centering \scriptsize \resizebox{1.0\textwidth}{!}{% \begin{tabular}{lccccccccc} \toprule & \multicolumn{4}{c}{\textbf{Binary Classification}} & \phantom{abc} & \multicolumn{4}{c}{\textbf{Implicit Hate Categories}} \\ \cmidrule{2-5} \cmidrule{7-10} \textbf{Models} & P & R & F & Acc & & P & R & F & Acc \\ \midrule Hate Sonar & 39.9 & 48.6 & 43.8 & 54.6 && - & - & - & - \\ Perspective API & 50.1 & 61.3 & 55.2 & 63.7 && - & - & - & - \\ \midrule SVM (n-grams) & 61.4 & 67.7 & 64.4 & 72.7 && 48.8 & 49.2 & 48.4 & 54.2 \\ SVM (TF-IDF) & 59.5 & 68.8 & 63.9 & 71.6 && 53.0 & 51.7 & 51.5 & 56.5 \\ SVM (GloVe) & 56.5 & 65.3 & 60.6 & 69.0 && 46.8 & 48.9 & 46.3 & 51.3 \\ BERT & \textbf{72.1} & 66.0 & 68.9 & \textbf{78.3} && \textbf{59.1} & 57.9 & 58.0 & 62.9 \\ BERT + Aug & 67.8 & \textbf{73.2} & \textbf{70.4} & 77.5 && 58.6 & \textbf{59.1} & \textbf{58.6} & \textbf{63.8} \\ BERT + Aug + Wikidata & 67.6 & 72.3 & 69.9 & 77.3 && 53.9 & 55.3 & 54.4 & 62.8 \\ BERT + Aug + ConceptNet & 68.6 & 70.0 & 69.3 & 77.4 && 54.0 & 55.4 & 54.3 & 62.5 \\ \bottomrule \end{tabular} } \caption{Classification performance metrics averaged over five random seeds. (\textit{Left}) \textbf{Binary Classification}. Performance metrics for implicit hate vs. not hate classification. (\textit{Right}) \textbf{Implicit Hate Categories}. Macro performance metrics for \textit{fine-grained category} classification via implicit hate taxonomy. Best performance is bolded. } \label{tab:results_macro} \end{table*} \section{Implicit Hate Speech Classification} We experiment with two classification tasks: (1) distinguishing implicit hate speech from non-hate, and (2) categorizing implicit hate speech using one of the 6 classes in our fine-grained taxonomy. \subsection{Experimental Setup} \label{subsection:experimental_settings} Using a 60-20-20 split for each task, we trained, validated, and tested SVM and BERT baselines. We tried standard unigrams, TF-IDF, and Glove embedding \cite{pennington2014glove} features and tuned linear SVMs with $C \in \{0.1, 1, 10, 100, 1000\}$. Next, we fine-tuned BERT with the learning rate in \{2e-5, 3e-5, 5e-5\} and the number of epochs in $\{1, 2, 3, 4\}$.\footnote{We kept $\epsilon=1.0 \times10^{-8}$ and the batch size fixed at 8} We also balanced the training data (\textbf{BERT + Aug}) with back-translation from Russian via FairSeq \cite{gehring2017convs2s}, using a grid search over the sampling temperature in \{0.5, 0.7, 0.9\}. Finally, we supplemented the previous methods with knowledge-based features to learn implicit associations between entities. In detail, we matched tweets to entities like \emph{white people}, \emph{Islam}, and \emph{antifa} from Wikidata Knowledge Graph ~\cite{vrandevcic2014wikidata} (\textbf{BERT + Aug + Wikidata}) and ConceptNet numberbatch~\cite{speer2016conceptnet} (\textbf{BERT + Aug + ConceptNet}) by string-matching unigrams, bigrams, and trigrams. Then we averaged across the pre-trained entity embeddings matched for each message.\footnote{11,163 / 22,584 tweets $(\approx54\%)$ were matched to one Wikidata entity (none were matched to more than one); 22,554 / 22,584 tweets $(>99\%)$ were matched to at least one ConceptNet entity, and the average number of matches per tweet was 14.} Finally, we concatenated the 768-dimensional BERT final layer with the 200-dimensional Wikidata (or 300-dimensional ConceptNet) embeddings, and fed this representation into an MLP with two hidden layers of dimension 100 and ReLU activation between them, using categorical Cross Entropy loss. \subsection{Implicit Hate Classification Results} \label{subsection:experimental_results} In binary implicit hate speech classification on the left side of Table~\ref{tab:results_macro}, baseline SVM models offer competitive performance with $F_1$ scores up to 64.4, while the fine-tuned neural models gain up to 6 additional points. The BERT-base model achieves significantly better macro precision than the linear SVMs (72.1 vs. at most 61.4), demonstrating a compositional understanding beyond simple keyword-matching. When we look at our best \textbf{BERT + Aug} model, the implicit category most confused with non-hate was \textit{Incitement} (36.3\% of testing examples were classified as not hate), followed by \textit{White Grievance} (29.6\%), \textit{Stereotypical} (23.3\%), \textit{Inferiority} (12.3\%), \textit{Irony} (9.3\%), and \textit{Threatening} (5.5\%). In our 6-way classification task on the right of Table~\ref{tab:results_macro}, we find that the BERT-base models again outperform the linear models. Augmentation does not significantly improve performance in either task since our data is already well-balanced and representative. Interestingly, integrating Wikidata and ConceptNet did not lead to any performance boost either. This suggests detecting implicit hate speech might require more compositional reasoning over the involved entities and we urge future work to investigate this. For additional comparisons, we consider a zero-shot setting where we test Google's Perspective API\footnote{\url{https://www.perspectiveapi.com/}} and the HateSonar classifier of \citet{davidson2017automated}. Our fine-tuned baselines significantly outperform both zero-shot baselines, which were trained on explicit hate. \begin{table*}[!tbh] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{rccccccccc} \toprule & \multicolumn{4}{c}{\textbf{Target Group}} & \phantom{abc} & \multicolumn{4}{c}{\textbf{Implied Statement}} \\ \cmidrule{2-5} \cmidrule{7-10} \textbf{Models} & BLEU & BLEU$^*$ & Rouge-L & Rouge-L$^*$ & \phantom{abc} & BLEU & BLEU$^*$ & Rouge-L & Rouge-L$^*$\\ GPT-gdy & 43.7 & 65.2& 42.9 &63.3 &\phantom{abc} & 41.1 & 58.2& 31 & 45.3\\ GPT-top-p& 57.7 & 76.8& 55.8 &74.6 &\phantom{abc} & 55.2 & 69.4& 40 & 53.9\\ GPT-beam & 59.3 & 81 & 57.3 &78.6 &\phantom{abc} & 57.8 & 73.8 & 46.5 & 63.4\\ \hline GPT-2-gdy & 45.3 & 67.6& 44.6 &66 &\phantom{abc} & 42.3 & 59.3& 32.7 & 47.4\\ GPT-2-top-p& 58.0 & 76.9& 56.2 &74.8 &\phantom{abc} & 55.1 & 69.3& 39.6 & 53.1\\ GPT-2-beam & \textbf{61.3} & \textbf{83.9}& \textbf{59.6} &\textbf{81.8} &\phantom{abc} & \textbf{58.9} & \textbf{75.3}& \textbf{48.3} & \textbf{65.9}\\ \bottomrule \end{tabular} } \caption{Evaluation of the generation models for Target Group and Implied Statement. (*) denotes the maximum versus the average score (without asterisk). gdy: greedy decoding, beam: beam search with 3 hypotheses, and top-p: nucleus sampling with $p = 0.92$} \label{tab:generation_metrics} \end{table*} \subsection{Challenges in Detecting Implicit Hate} To further understand the challenges of implicit hate detection and promising directions for future work, we investigated 100 randomly sampled false negative errors from our best model in the binary task (BERT+Aug) and found a set of linguistic classes it struggles with.\footnote{For robustness check, we also labeled 100 false positives from the BERT base model and found the distribution of errors remains similar.} \textbf{(1) Coded hate symbols} \cite{qian2019learning} such as \textit{\#WPWW} (white pride world wide), \textit{\#NationalSocialism} (Nazism), and \textit{(((they)))} (an anti-Semitic symbol) are contained in 15\% of instances, and our models fail to grasp their semantics. While individual sentences appear harmless, implicit hate can occur in \textbf{(2) discourse relations} \cite{de2018hate} (19\% of instances) like the implied causal relation between the conjunction \textit{I like him} and \textit{he's white}. Additionally, misinformation \cite{islam2020deep} and out-group \textbf{(3) entity framing} \cite{phadke2020many} (25\%) can be context-sensitive, as in the headline \textit{three Muslims convicted}. Even positive framing of a negative entity can be problematic, like describing a Nazi soldier as \textit{super cool}. Inferiority statements like \textit{POC need us and not the other way around} also require a deep understanding of \textbf{(4) commonsense} (11\%) surrounding social norms (e.g. \textit{a dependant is inferior to a supplier}) \cite{forbes2020social}. Other challenge cases contain highly \textbf{(5) metaphorical language} (7\%), like the animal metaphor in \textit{a world without white people : a visual look at a mongrel future}. \textbf{(6) Colloquial or idiomatic speech} (17\%) appears in subtle phrases like \textit{infrastructure is the white man's game}, and \textbf{(7) Irony} (15\%) detection \cite{waseem2016hateful} may require pragmatic reasoning and understanding, such as in the phrase \textit{hey kids, wanna replace white people.} When we sample false positives, we find our models are prone to \textbf{(8) identity term bias} \cite{dixon2018measuring}. Given the high density of identity terms like \textit{Jew} and \textit{Black} in hateful contexts, our models overclassified tweets with these terms as \textit{hateful}, and particularly \textit{stereotypical} speech. In a similar manner, our model also incorrectly associated \textit{white grievance} with all \textit{diversity}-related discourse, \textit{incitement} with controversial topics like \textit{war} and \textit{race}, and \textit{inferiority language} with value-laden terms like \textit{valid} and \textit{wealth}. To sum up, our dataset contains rich linguistic phenomena and an array of subtleties that challenge current state-of-the-art baselines, which can serve as a useful benchmark and offer multiple new directions for future work. \section{Explaining Implicit Hate Speech} This section presents our generation results for natural language explanations of both (1) who is being targeted and (2) what the implied message is for each implicitly hateful tweet. Generating such explanations can help content moderators better understand the severity and nature of automatically-flagged messages. Additionally, we echo efforts from social media companies (e.g., Instagram~\cite{bryant2019instagram}) where the application alerts the user when the post is flagged ``offensive,'' and asks them if they really want to post it. This strategy has proven successful in deterring hurtful comments. Our work could inspire a similar strategy for implicit hate speech. By showing the user the implied meaning of their post before it is posted, we would enable them to recognize the severity of their words and possibly reconsider their decision to post. \begin{table*}[t] \resizebox{\textwidth}{!}{ \begin{tabular}{llll} \toprule \textbf{Post} & \textbf{Type} & \textbf{Target Group} & \textbf{Implied Statement} \\ \midrule \multirow{2}{*}{(a) white revolution is the only solution} & \multirow{2}{*}{incitement} & non-white people & non-white people are inferior \\ & & \textit{white people} & \textit{white people are superior to other races} \\ \midrule \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}(b) yes you are fine in a white majority country. how is mexico doing these days? people \\ come here because you couldn't build it.\end{tabular}} & \multirow{3}{*}{inferiority} & mexican people & \begin{tabular}[c]{@{}l@{}}mexican people do not build things \end{tabular} \\ & & \textit{mexicans} & \textit{mexicans are incompetent} \\ \midrule \multirow{3}{*}{\begin{tabular}[c]{@{}l@{}}(c) black people only seem to thrive in white \\ countries. how strange\end{tabular}} & \multirow{3}{*}{irony} & black people & \begin{tabular}[c]{@{}l@{}}black people are inferior \end{tabular} \\ & & \textit{black people} & \textit{\begin{tabular}[c]{@{}l@{}}black people can't survive without \\ white people\end{tabular}} \\ \midrule \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}(d) soon white people will not be a majority \\ anywhere. you believe\end{tabular}} & \multirow{2}{*}{grievance} & whites & whites have been driven out of the country \\ & & \textit{minorities} & \textit{minorities want to take over the world} \\ \midrule \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}(e) muslims are always wanting to kill \\ someone! its their duty to kill the infidel.\end{tabular}} & \multirow{2}{*}{stereotypical} & muslims & muslims are killers \\ & & \textit{muslims} & \textit{muslims are violent} \\ \midrule \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}(f) oh how i wish a man with a gun was \\there! wake up white people! they hate us\end{tabular}} & \multirow{2}{*}{threatening} & white people & white people are hated \\ & & \textit{non-whites} & \textit{non-whites hate whites} \\ \bottomrule \end{tabular}} \caption{Example posts from our dataset along with their implicit category labels, the GPT-2 generated target and implied statements (first row of each block), and the ground truth target and implied statements (final row of each block, in \textit{italics}). Generated implied statements are semantically similar to the ground truth statements.} \label{tab:posts_generation_examples} \end{table*} \subsection{Task Formulation} Our goal is to develop a natural language system that, given a post, generates a hateful post's intended target and hidden implied meanings. Therefore, we formulate the problem as a conditional generation task (i.e., conditioned on the post content). During training, the generation model takes a sequence of tokens as input: \begin{align*} \begin{split} \textbf{x} = & \{[STR], t_1, t_2, ....., t_n, [SEP], \\ & t_{[G1]}, t_{[G2]}, ...., [SEP], t_{[S1]}, t_{[S2]}, ...., [END]\} \end{split} \end{align*} with start token [STR], tweet tokens $t_1:t_n$, target group $t_{[Gi]}$, and implied statement $t_{[Si]}$, and minimizes the cross-entropy loss $-\sum_l \log P(\tilde{t}_l|t_{<l})$. During inference, our goal is to mimic real-world scenarios when only the post is available. Therefore, the input to the model only contains post tokens $t_1:t_n$ and we experiment with multiple decoding strategies: greedy search (gdy), beam search, and top-p (nucleus) sampling to generate the explanations $t_{[G_i]}$ and $t_{[S_i]}$. \subsection{Experiment Setup} Our ground-truth comes from the free-text \textit{target demographic} and \textit{implied statement} annotations that we collected for all 6,346 implicit hate tweets in Section~\ref{section:implied_annotation}, with 75\% for training, 12.5\% for validation, and 12.5\% for testing. Since we collect multiple annotations for each post (2 per tweet), we ensure that each post and its corresponding annotations belongs only to one split. Following recent work on social bias inference and commonsense reasoning \cite{sap-etal-2020-social,forbes2020social,sharma2020computational,bosselut2019comet}, we fine-tune Open-AI's GPT~\cite{radford2018improving} and GPT-2~\cite{radford2019language} pre-trained language models to the task and evaluate using BLEU \cite{papineni2002bleu} and ROUGE-L \cite{lin2004rouge}. We pick BLEU since it is standard for evaluating machine translation models and ROUGE which is used in summarization contexts; both have been adopted extensively in prior literature. These automatic metrics indicate the quality of the generated target group and implied statement compared to our annotated ground-truth in terms of n-grams and the longest common sequence overlaps. Since there are two ground truth annotations per tweet, we measure both the averaged metrics across both references, and the maximum metrics (BLEU$^*$ and ROUGE-L$^*$). We tuned hyperparameters and selected the best models based on their performance on the development set, and we reported evaluation results on the test.\footnote{We fine-tune for $e \in {\{1, 2, 3, 5\}}$ epochs with a batch size of 2 and learning rate of $5 \times 10^{-5}$ with linear warm up} For decoding, we generate one frame for greedy decoding and three hypotheses for beam search and top-p (nucleus) sampling with $p=0.92$ and choose the highest scoring frame. \subsection{Generation Results} In Table~\ref{tab:generation_metrics} we find that, GPT-2 outperforms GPT in both \textit{target group} and \textit{implied statement} generation. This difference is likely because GPT-2 was trained on English web text while GPT was trained on fiction books and web text is more similar to our domain. The BLEU and ROUGE-L scores are higher for the \textit{target group} (e.g., 83.9 BLEU) than for the \textit{implied statement} (e.g., 75.3 BLEU), consistently across both averaged and maximum scores. This is likely because the implied statement is longer, more nuanced, and less likely to be contained in the text itself. Additionally, beam search achieves the highest performance for both GPT and GPT-2, followed by top-p. This is not surprising since both decoding strategies consider multiple hypotheses. Since BLEU and ROUGE-L measure word overlap and not semantics, it is possible that the results in Table~\ref{tab:generation_metrics} are overly pessimistic. The GPT-2 generated implied statements in Table~\ref{tab:generation_metrics} actually describe the complement (a,d), generalization (b), extrapolation (c), or paraphrase (e,f) of the ground truth, and are thus aligned, despite differences in word choice. Overall, our generation results are promising. Transformer-based models may play a key role in explaining the severity and nature of online implicit hate. \section{Conclusion} In this work, we introduce a theoretical taxonomy of implicit hate speech and a large-scale benchmark corpus with fine-grained labels for each message and its implication. As an initial effort, our work enables the NLP communities to better understand and model implicit hate speech at scale. We also provide several state-of-the-art baselines for detecting and explaining implicit hate speech. Experimental results show these neural models can effectively categorize hate speech and spell out more fine-grained implicit hate speech and explaining these hateful messages. Additionally, we identified eight challenges in implicit hate speech detection: coded hate symbols, discourse relations, entity framing, commonsense, metaphorical language, colloquial speech, irony, and identity term bias. To mitigate these challenges, future work could explore deciphering models for coded language~\cite{kambhatla2018decipherment,qian2019learning}, lifelong learning of hateful language~\cite{qian2021lifelong}, contextualized sarcasm detection, and bias mitigation for named entities in hate speech detection systems~\cite{xia2020demoting} and their connection with our dataset. We demonstrate that our corpus can serve as a useful research benchmark for understanding implicit hate speech online. Our work also has implications towards the emerging directions of countering online hate speech~\cite{citron2011intermediaries,mathew2019thou}, detecting online radicalization~\cite{ferrara2016predicting} and modeling societal systematic racism, prejudicial expressions, and biases~\cite{davidson-etal-2019-racial,manzini-etal-2019-black,blodgett2020language}. \section*{Ethical Considerations} This study has been approved by the Institutional Review Board (IRB) at the researchers' institution. For the annotation process, we included a warning in the instructions that the content might be offensive or upsetting. Annotators were also encouraged to stop the labeling process if they were overwhelmed. We also acknowledge the risk associated with releasing an implicit hate dataset. However, we believe that the benefit of shedding light on the implicit hate phenomenon outweighs any risks associated with the dataset release. \section*{Acknowledgments} The authors would like to thank the members of SALT lab and the anonymous reviewers for their thoughtful feedback. The annotation process was funded through the School of Interactive Computing at Georgia Tech and the Institute for Data Engineering and Science (IDEAS) Data Curation Award to ElSherief and Yang. The work is supported in part by Russell Sage Foundation. \bibliographystyle{acl_natbib}
{'timestamp': '2021-09-14T02:14:44', 'yymm': '2109', 'arxiv_id': '2109.05322', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05322'}
arxiv
\section{Introduction} Successive relaying (SR) is a well known technique in wireless communication, where two half-duplex (HD) relays simultaneously assist the transmission between a source and destination nodes utilizing the full bandwidth, and thus imitating full-duplex (FD) operation \cite{fan2007recovering}. The main idea is that at a given time-instant, the source transmits data to one relay, and simultaneously, the other relay forwards the data that it received from the source in the previous transmission time-instant to the destination. Hence, it becomes quite clear that a main challenge in realizing such a scheme is inter-relay interference (IRI). Thus far, authors have adopted different approaches to deal with IRI, such as channel ordering and rate adaptation \cite{chen2014cao}, relay interference cancellation and precoding \cite{wicaksana2009af}, or by neglecting IRI assuming fixed directional relays or large distance between active relays \cite{ikhlef2012mimicking}. \par However, the recently proposed reconfigurable intelligent surfaces (RISs) can be a game changer for many wireless applications, including SR as we will demonstrate in this paper. Thanks to their ability in tweaking the wireless environment while maintaining low cost and power requirements, RISs have gained much attention as a strong candidate for future wireless networks \cite{tan2016increasing, rajatheva2020white, chowdhury20206g, kisseleff2020reconfigurable}. In principle, RISs are similar to FD amplify-and-forward relaying, with the former providing passive beamforming without the need to include active power amplifiers or radio-frequency chains, while the latter has the ability to provide active amplification at the cost of increased hardware complexity and power consumption. \par Instead of dealing with conventional active relaying and RISs as two separate technologies, few works have demonstrated the benefits of integrating RISs in active relaying networks. In particular, the works in \cite{abdullah2020hybrid, abdullah2020optimization, wang2021joint, yildirim2021hybrid, obeed2021joint} have shown that RISs can considerably improve the effective rates of conventional relay-based networks. However, in all of these works the authors considered a conventional relay network with a single relay node aided by an RIS, and no SR or IRI was considered in any of these works. In contrast, in this work we investigate the performance of SR networks with the help of two RISs, where we jointly design the passive beamforming weights for the two RISs to provide a spatial (on the air) suppression of the IRI while maximizing the desired signals gains. Our contributions can be summarized as follows: \begin{itemize} \item We propose a new successive decode-and-forward (DF) relaying network with two RISs, and investigate its effective rate performance. The corresponding max-min optimization problem is formulated and solved via a semidefinite programming (SDP) approach. \item In addition, as SDP schemes are known to suffer from a high computational complexity, we propose an efficient evolutionary scheme based on particle swarm optimization (PSO) \cite{kennedy1995particle} to tackle the joint phase-shift design for both RISs. Furthermore, modifications of the PSO are proposed exploiting the structure of the problem to guarantee stability and control the speed and accuracy of convergence. \item Our results demonstrate that RISs can suppress IRI arising from the SR, and a large gain in achievable rates is obtained compared to the cases where only relays or RISs are utilized. Moreover, the proposed PSO scheme is shown to be highly efficient and can achieve a near-optimal performance when compared to the SDP solution. \end{itemize}It is worth highlighting that our proposed PSO scheme is novel in the sense that it was designed specifically to tackle the RIS passive beamforming with guaranteed stability and controlled convergence behavior. \par The rest of this paper is organized as follows: The adopted system model is introduced in Section \ref{section2}. Section \ref{section3} deals with the SDP-based beamforming design, while the PSO-based scheme is introduced and explained in detail in Section \ref{section4}. Numerical results are presented and discussed in Section \ref{section5}. Finally, conclusions are drawn in Section \ref{section6}. \par \textit{Notations}: Matrices and vectors are denoted by uppercase and lowercase boldface letters, respectively. $(.)^\ast,\ (.)^T,\ \text{and}\ (.)^H$ denote the conjugate, transpose, and Hermitian transpose operators, respectively. In addition, $\boldsymbol a_i$, $\left[\boldsymbol A\right]_{:,j}$, and $\left[\boldsymbol A\right]_{i,j}$ are the $i$th row, $j$th column, and $i$th element of the $j$th column of $\boldsymbol A$, respectively, while $\left[\boldsymbol x\right]_i$ and $x_i$ both represent the $i$th element of $\boldsymbol x$ and used interchangeably as appropriate. $\boldsymbol 0_{N\times M}$ and $\boldsymbol I_N$ are the $N\times M$ all-zero and $N\times N$ identity matrices, respectively. Furthermore, $\text{diag}\{\boldsymbol a\}$ is a diagonal matrix whose diagonal is the elements of $\boldsymbol a$, while $\text{diag}\{\boldsymbol A\}$ is a vector whose elements are the diagonal elements of $\boldsymbol A$. The trace of $\boldsymbol A$ is denoted by $\text{tr}(\boldsymbol A)$, while $\boldsymbol A \succeq 0$ indicates that $\boldsymbol A$ is a positive semidefinite matrix. Finally, $\left|.\right|$ and $\mathbb E\{.\}$ denote the absolute and expectation operators, respectively. \section{System model} \label{section2} We consider a time-division duplex scenario where a source node ($S$) transmits data to a destination node ($D$). Two HD-DF relays $R_1$ and $R_2$, located between $S$ and $D$, assist the communication by adopting SR to exploit the full bandwidth. Furthermore, two RISs denoted by $I_1$ and $I_2$, located near $R_1$ and $R_2$, respectively, are utilized to enhance the communication quality and suppress the IRI arising from the SR operation. We assume that each of $S$, $D$, $R_1$ and $R_2$ are equipped with a single omni-directional antenna, while $I_1$ and $I_2$ each has $M$ reflective elements. \par At any given transmission-time slot, one of the two relays operates as a receiver (Rx) to receive the new block of data from $S$, while the other relay operates as a transmitter (Tx) to forward the decoded message received from $S$ in the previous time instant to $D$; see Fig. \ref{system}.\footnote{Note that during the first and last transmission time slots, only a single relay will be active and no IRI will be present. However, in this work we focus on the case where both relays are active.} Focusing on the case where $R_1$ operates as an Rx, and assuming that signals reflected from each RIS more than once have very low powers and thus can be neglected, we can write the received signal at $R_1$ as: {\small \begin{align} y_{r_1} & = \sqrt{p_s} \left(h_{sr_1}+\boldsymbol{h}_{i_1r_1}^T\boldsymbol \Theta_1\boldsymbol{h}_{si_1}+ \boldsymbol{h}_{i_2r_1}^T\boldsymbol \Theta_2\boldsymbol{h}_{si_2}\right)x \nonumber \\ & + \sqrt{p_{r_2}} \left(h_{r_2r_1}+\boldsymbol{h}_{i_1r_1}^T\boldsymbol \Theta_1\boldsymbol{h}_{r_2i_1}+ \boldsymbol{h}_{i_2r_1}^T\boldsymbol \Theta_2\boldsymbol{h}_{r_2i_2}\right)\tilde{x} + w_{r_1}, \end{align}}where $p_s$ and $p_{r_2}$ are the transmit powers of $S$ and $R_2$, respectively, $\boldsymbol \Theta_1\in \mathbb C^{M\times M}$ and $\boldsymbol \Theta_2\in \mathbb C^{M\times M}$ are the diagonal reflection matrices of $I_1$ and $I_2$, respectively, while $h_{sr_1}\in\mathbb C$, $h_{r_2r_1}\in\mathbb C$, $\boldsymbol h_{i_1r_1} \in \mathbb C^{M\times 1}$, $\boldsymbol h_{si_1} \in \mathbb C^{M\times 1}$, $\boldsymbol h_{i_2r_1} \in \mathbb C^{M\times 1}$, $\boldsymbol h_{si_2} \in \mathbb C^{M\times 1}$, $\boldsymbol h_{r_2i_1} \in \mathbb C^{M\times 1}$, and $\boldsymbol h_{r_2i_2} \in \mathbb C^{M\times 1}$ denote the channels between $S\rightarrow R_1$, $R_2\rightarrow R_1$, $I_1\rightarrow R_1$, $S\rightarrow I_1$, $I_2\rightarrow R_1$, $S\rightarrow I_2$, $R_2\rightarrow I_1$, and $R_2\rightarrow I_2$, respectively.\footnote{The different narrowband fading channels adopted in this work will be explained in detail in Section \ref{section5}.} Moreover, $x$ and $\tilde{x}$ are the information symbols transmitted from $S$ and $R_2$, respectively, with $\mathbb E\{|x|^2\} = \mathbb E\{|\tilde x|^2\}=1$, and $w_{r_1} \sim \mathcal {CN} (0, \sigma^2)$ is the additive white Gaussian noise (AWGN) at $R_1$.\footnote{Throughout this work, we assume perfect channel state information (CSI) is available similar to \cite{wu2019intelligent} and \cite{huang2019reconfigurable}. Moreover, we assume a centralized processing such that all channels are known to either $S$ or $D$ in order to perform the joint phase-shift design.} \par For more convenience, we express the effective channels between each node ($S$, $R_1$, and $R_2$) and the two RISs in a single vector. Specifically, we define $\small \boldsymbol h_{si} = \begin{bmatrix} \boldsymbol h_{si_1}\\ \boldsymbol h_{si_2} \end{bmatrix} \in\mathbb C^{2M\times 1}$, $\small \boldsymbol h_{ir_1} = \begin{bmatrix} \boldsymbol h_{i_1r_1}\\ \boldsymbol h_{i_2r_1} \end{bmatrix} \in\mathbb C^{2M\times 1}$, $\small \boldsymbol h_{r_2i} = \begin{bmatrix} \boldsymbol h_{r_2i_1}\\ \boldsymbol h_{r_2i_2} \end{bmatrix} \in\mathbb C^{2M\times 1}$, $\small \boldsymbol \theta = \begin{bmatrix} \boldsymbol \theta_1 \\ \boldsymbol \theta_2 \end{bmatrix} \in\mathbb C^{2M\times 1}$, where $\boldsymbol \theta_j = \text{diag}\{\boldsymbol \Theta_j\} \ (j\in\{1,2\})$. Hence, the signal-to-interference plus noise ratio (SINR) at $R_1$ can be expressed as follows: \begin{figure}[t] \centering \hspace*{0.25cm} {\includegraphics[width=8cm,height=6.5cm, trim={0cm 0cm 0cm 0cm},clip]{Fig1.pdf}} \caption{The proposed RIS-enhanced SR scheme when $R_1$ operates as an Rx while $R_2$ operates as a Tx.} \label{system} \end{figure} \begin{equation} \label{gamma_r} \small \gamma_{r_1} = \frac{p_s \left|h_{sr_1} + \boldsymbol h_{ir_1}^T \boldsymbol \Theta \boldsymbol h_{si}\right|^2}{p_{r_2} \left|h_{r_2r_1}+\boldsymbol h_{ir_1}^T\boldsymbol \Theta \boldsymbol h_{r_2i} \right|^2 + \sigma^2}, \end{equation}where $\boldsymbol \Theta = \text{diag}\{\boldsymbol \theta\} \in \mathbb C^{2M\times 2M}$. On the other hand, we can write the received signal at $D$ (assuming no direct link between $S$ and $D$ exists except through the RISs) as follows: \begin{equation} \small y_d = \sqrt{p_{r_2}} \left( h_{r_2d} + \boldsymbol h_{id}^T \boldsymbol \Theta \boldsymbol h_{r_2i}\right)\tilde{x} + \sqrt{p_{s}} \left( \boldsymbol h_{id}^T \boldsymbol \Theta \boldsymbol h_{si}\right){x} + w_d, \end{equation}where $\small \boldsymbol h_{id} = \begin{bmatrix} \boldsymbol h_{i_1d}\\ \boldsymbol h_{i_2d} \end{bmatrix} \in\mathbb C^{2M\times 1}$ is a vector containing the channel coefficients between $D$ and both RISs, $h_{r_2d}$ is the channel coefficient between $R_2$ and $D$, and $w_d \sim \mathcal{CN} (0, \sigma^2)$ is the AWGN at $D$. Noting that $x$ represents interference to the destination in this case, we can write the SINR at $D$ as: \begin{equation}\label{gamma_d} \small \gamma_d = \frac{p_{r_2} \left|h_{r_2d} + \boldsymbol h_{id}^T \boldsymbol \Theta \boldsymbol h_{r_2i}\right|^2}{p_s \left| \boldsymbol h_{id}^T \boldsymbol \Theta \boldsymbol h_{si}\right|^2 + \sigma^2}. \end{equation}In the subsequent time-instant, $S$ will transmit a new block of data to $R_2$ which will operate as an Rx, whereas $R_1$ will forward its received signal from $S$ in the current time-slot, assuming successful decoding, to $D$. Note that if the distances between $\{S,D\}$ and $\{R_i, I_i\}$ were the same for both $i\in \{1,2\}$, then the system is symmetric, and thus it is sufficient to consider only a single phase to evaluate the achievable rate (in this case $R_1$ is the Rx while $R_2$ is the Tx). Therefore, as we adopt a symmetric system model in this work \cite{zhang2009achievable}, we can write the effective rate at $D$, in bits/s/Hz, as follows: \begin{equation} \label{rate} \small \mathcal R = \min \left\{\log_2\left(1+\gamma_{r_1}\right), \ \log_2 \left(1+\gamma_d\right)\right\}. \end{equation}It is clear from (\ref{gamma_r}) and (\ref{gamma_d}) that the achievable rate depends on the reflection matrix $\boldsymbol \Theta$. In the next section, we formulate and solve the joint passive beamforming design problem by utilizing an SDP approach. \section{Passive Beamforming Design via Semidefinite Programming} \label{section3} In this section, we aim to maximize the achievable rate in (\ref{rate}) via an SDP approach. We start by formulating the corresponding optimization problem as follows: \begin{subequations} \label{OP1} \small \begin{align} & \hspace{.75cm}\underset{\boldsymbol \Theta}{\text{maximize}} \hspace{.3cm} \min \left\{\log_2\left(1+\gamma_{r_1}\right), \ \log_2 \left(1+\gamma_d\right)\right\} \hspace{1cm} (\ref{OP1}) \nonumber \\ &\hspace{.75cm}\text{subject to} \nonumber \\ & \hspace{.75cm} \big|[\boldsymbol{\Theta}]_{m,m}\big| =1, \hspace{0.3cm}\forall m\in\mathcal M, \label{6a} \end{align} \end{subequations}where $\mathcal M = \{1, 2, ..., 2M\}$. Due to the interference terms in (\ref{gamma_r}) and (\ref{gamma_d}), and the unit-modulus constraint on $\boldsymbol \Theta$ in (\ref{6a}), problem (\ref{OP1}) is non-convex and cannot be solved in its current form in polynomial time. Therefore, in the following we adopt change of variables and introduce exponential slack variables to overcome the non-convexity of (\ref{OP1}). \par Let $\small \boldsymbol q_{sr_1} = \begin{bmatrix} \text{diag}\{\boldsymbol h_{ir_1}\} \boldsymbol h_{si}\\ h_{sr_1} \end{bmatrix}$, $\small \boldsymbol q_{r_2r_1} = \begin{bmatrix} \text{diag}\{\boldsymbol h_{ir_1}\} \boldsymbol h_{r_2i}\\ h_{r_2r_1} \end{bmatrix}$, $\small \boldsymbol q_{r_2d} = \begin{bmatrix} \text{diag}\{\boldsymbol h_{id}\} \boldsymbol h_{r_2i}\\ h_{r_2d} \end{bmatrix}$, $\small \boldsymbol q_{sd} = \begin{bmatrix} \text{diag}\{\boldsymbol h_{id}\} \boldsymbol h_{si}\\ 0 \end{bmatrix}$, and $\small \boldsymbol v = \begin{bmatrix} \boldsymbol \theta \\ 1 \end{bmatrix}$. Moreover, by defining $\boldsymbol Q_{sr_1} = \boldsymbol q_{sr_1}\boldsymbol q_{sr_1}^H$, $\boldsymbol Q_{r_2r_1} = \boldsymbol q_{r_2r_1}\boldsymbol q_{r_2r_1}^H$, $\boldsymbol Q_{r_2d} = \boldsymbol q_{r_2d}\boldsymbol q_{r_2d}^H$, $\boldsymbol Q_{sd} = \boldsymbol q_{sd}\boldsymbol q_{sd}^H$, and $\boldsymbol V = \boldsymbol v^\ast \boldsymbol v^T$, we can now equivalently represent $\gamma_{r_1}$ and $\gamma_d$ as follows: \begin{subequations} \begin{equation} \small \gamma_{r_1} = \frac{p_s \text{tr}\left(\boldsymbol V \boldsymbol Q_{sr_1}\right)}{p_{r_2} \text{tr}\left(\boldsymbol V \boldsymbol Q_{r_2r_1}\right) + \sigma^2}, \end{equation} \begin{equation} \small \gamma_{d} = \frac{p_{r_2} \text{tr}\left(\boldsymbol V \boldsymbol Q_{r_2d}\right)}{p_s \text{tr}\left(\boldsymbol V \boldsymbol Q_{sd}\right) + \sigma^2}. \end{equation} \end{subequations}However, even with relaxing the rank-one constraint on $\boldsymbol V$, formulating the max-min optimization problem with the current formulations of $\gamma_{r_1}$ and $\gamma_{d}$ would still result in a non-convex objective function. Nonetheless, this can now be dealt with by introducing additional slack variables \cite{zhao2015robust}. In particular, let $\boldsymbol s = [s_1\ \ s_2]^T$ and $\boldsymbol u = [u_1\ \ u_2 ]^T$ be exponential slack variables such that \begin{subequations} \begin{equation} \small p_s \text{tr}\left(\boldsymbol V \boldsymbol Q_{sr_1}\right) + p_{r_2} \text{tr}\left(\boldsymbol V \boldsymbol Q_{r_2r_1}\right) + \sigma^2 = e^{s_1}, \end{equation} \begin{equation} \small p_{r_2} \text{tr}\left(\boldsymbol V \boldsymbol Q_{r_2r_1}\right) + \sigma^2 = e^{u_1}, \end{equation} \begin{equation} \small p_{r_2} \text{tr}\left(\boldsymbol V \boldsymbol Q_{r_2d}\right) + p_s \text{tr}\left(\boldsymbol V \boldsymbol Q_{sd}\right) + \sigma^2 = e^{s_2}, \end{equation} \begin{equation} \small p_s \text{tr}\left(\boldsymbol V \boldsymbol Q_{sd}\right) + \sigma^2 = e^{u_2}. \end{equation} \end{subequations}Subsequently, and after dropping the rank-one constraint on $\boldsymbol V$ via semidefinite relaxation \cite{luo2010semidefinite}, we can introduce the following optimization problem\footnote{It is worth highlighting that $\frac{1}{\ln(2)}$ is omitted from the objective function without any loss of optimality.} \begin{subequations} \label{OP2} {\small \begin{align} & \hspace{.85cm}\underset{ \substack {s_1,\ s_2,\ u_1, \\ u_2, \ \boldsymbol V}}{\text{maximize}} \hspace{.5cm} \underset{i\in\{1,2\}}{\min} \hspace{.5cm} \left\{s_i - u_i\right\} \hspace{2.5cm} (\ref{OP2}) \nonumber \\ &\hspace{.85cm}\text{subject to} \nonumber \\ &\hspace{.85cm} p_s \text{tr}\left(\boldsymbol V \boldsymbol Q_{sr_1}\right) + p_{r_2} \text{tr}\left(\boldsymbol V \boldsymbol Q_{r_2r_1}\right) + \sigma^2 \ge e^{s_1}, \label {9a}\\ &\hspace{.85cm} p_{r_2} \text{tr}\left(\boldsymbol V \boldsymbol Q_{r_2r_1}\right) + \sigma^2 \le e^{u_1}, \label {9b} \\ &\hspace{.85cm} p_{r_2} \text{tr}\left(\boldsymbol V \boldsymbol Q_{r_2d}\right) + p_s \text{tr}\left(\boldsymbol V \boldsymbol Q_{sd}\right) + \sigma^2 \ge e^{s_2}, \label {9c} \\ &\hspace{.85cm} p_s \text{tr}\left(\boldsymbol V \boldsymbol Q_{sd}\right) + \sigma^2 \le e^{u_2}, \label {9d} \\ &\hspace{.8cm} \left[\boldsymbol V \right]_{m,m} =1, \ \ m \in \{1, 2, ...., 2M+1\}, \label {9e} \\ &\hspace{.85cm} \boldsymbol V \succeq 0. \label {9f} \end{align}}\end{subequations}The only non-convex constraints at this stage are (\ref{9b}) and (\ref{9d}). To overcome this drawback, a first-order Taylor approximation is applied to convert these constraints into convex ones. In particular, we define $\bar {\boldsymbol u} = [\bar u_1 \ \ \bar u_2]^T$, where $\bar u_1$ and $\bar u_2$ are the points around which the linearization is made such that $e^{u_i} \approx e^{\bar u_i}(u_i - \bar u_i + 1)$. Hence, we can recast problem (\ref{OP2}) as \begin{subequations} \label{OP3} {\small \begin{align} & \hspace{.85cm}\underset{ \substack {s_1,\ s_2,\ u_1, \\ u_2, \ \boldsymbol V}}{\text{maximize}} \hspace{.5cm} \underset{i\in\{1,2\}}{\min} \hspace{.5cm} \left\{s_i - u_i\right\} \hspace{2.5cm} (\ref{OP3}) \nonumber \\ &\hspace{.85cm}\text{subject to} \nonumber \\ &\hspace{.85cm} p_{r_2} \text{tr}\left(\boldsymbol V \boldsymbol Q_{r_2r_1}\right) + \sigma^2 \le e^{\bar u_1}(u_1 - \bar u_1 + 1), \\ &\hspace{.85cm} p_s \text{tr}\left(\boldsymbol V \boldsymbol Q_{sd}\right) + \sigma^2 \le e^{\bar u_2}(u_2 - \bar u_2 + 1), \\ &\hspace{.85cm}\text{and constraints (\ref{9a}), (\ref{9c}), (\ref{9e}), and (\ref{9f})}. \end{align}}\end{subequations}It follows that all constraints and objective function at this stage are convex, and problem (\ref{OP3}) can be solved iteratively using software tools such as CVX. However, we firstly initialize $\bar u_1$ and $\bar u_2$ as follows \begin{subequations} \begin{equation} \small \bar u^{(0)}_1 = \ln \left( p_{r_2} \text{tr}\left(\tilde{\boldsymbol V} \boldsymbol Q_{r_2r_1}\right) + \sigma^2 \right), \end{equation} \begin{equation} \small \bar u^{(0)}_2 = \ln \left( p_s \text{tr}\left(\tilde {\boldsymbol V} \boldsymbol Q_{sd}\right) + \sigma^2\right), \end{equation} \end{subequations}where $\tilde{\boldsymbol V}$ is any feasible (i.e. random) solution. Once the algorithm has converged, there is no guarantee that the rank of $\boldsymbol V^\star$ is equal to $1$. In such case, the value of the objective function corresponding to $\boldsymbol V^\star$ represents an upper-bound. Nonetheless, one can apply eigenvalue decomposition (EVD) with Gaussian randomization to approximate a rank-$1$ near optimal solution \cite{wu2018intelligent}. The details are omitted here for brevity, however, it is worth pointing out that such approximation guarantees a minimum accuracy of $\pi/4$ of the optimal objective value \cite{zhang2006complex}. The steps of the proposed scheme are given in Algorithm \ref{Algorithm1}. \begin{algorithm}[t] \caption{Proposed SDP algorithm for phase-shifts design} \label{Algorithm1} \begin{algorithmic}[1] \STATE \textbf{input} $\mathbf Q_{sr_1}$, $\mathbf Q_{r_2r_1}$, $\mathbf Q_{r_2d}$, $\mathbf Q_{sd}$, $p_s$, $p_{r_2}$, $\sigma^2$, $\bar u^{(0)}_1$, $\bar u^{(0)}_2$, $\epsilon = 10^{-3}$ (accuracy), $k=1$ (iteration index), \STATE \textbf{define} $\small {\text{err}^{(k)}} \overset {\Delta}{=} \sum_{i=1}^{2}\big|u^{(k)}_i - \bar{u}^{(k-1)}_i\big|$ \STATE \textbf{repeat} \STATE \ \ \ \ \textbf{solve} $(\ref{OP3})$ and then \textbf{evaluate} $\text{err}^{(k)}$, \STATE \ \ \ \ \textbf{if} $\text{err}^{(k)} <\epsilon$ \STATE \ \ \ \ \ \ \ \ \textbf{break}; \STATE \ \ \ \ \textbf{else} update $\bar{u}^{(k)}:= u^{(k)}$, and then \textbf{increment} $k := k + 1$, \STATE \textbf{until} convergence \end{algorithmic} \end{algorithm} \section{Particle Swarm Optimization-based Beamforming Design} \label{section4} The main drawback for the SDP approach is that it suffers from a complexity order of $\mathcal O\left((2M+1)^{3.5}\right)$ \cite{cui2019secure}, and hence, it becomes unsuitable when dealing with large optimization problems. Therefore, in this section we propose a lower-complexity evolutionary method to tackle the phase-shift design, which is based on PSO \cite{kennedy1995particle}. \par We start by generating an initial population of $N$ particles $\boldsymbol F = \big[\boldsymbol f_1, \ \boldsymbol f_2, \ ...\ , \ \boldsymbol f_N\big]^T \in \mathbb R^{N\times 2M}$ with entries (or phase-shifts) drawn randomly in the interval $[-\pi, \pi]$. We evaluate the fitness of the $n$th particle ($\lambda_n$) as follows: \begin{equation} \small \lambda_n = \min \Big\{\gamma_{r_1} \left(\boldsymbol f_n\right), \gamma_d \left(\boldsymbol f_n\right) \Big\}, \ \ \ \forall n \in \{1, ..., N\}, \end{equation}where $\gamma_{r_1} \left(\boldsymbol f_n\right)$ and $\gamma_d \left(\boldsymbol f_n\right)$ are the SINR values at $R_1$ and $D$ given in (\ref{gamma_r}) and (\ref{gamma_d}), respectively, such that {\small\begin{align} \gamma_i(\boldsymbol f_n) = \left\{\gamma_i \middle| \boldsymbol \Theta = \text{diag}\big\{e^{\jmath \boldsymbol f_n}\big\} \right\}, i\in\{r_1, d\}. \end{align}}Then, we find the \textit{local best} and \textit{global best} solutions. Specifically, the \textit{global best} solution for the $m$th element of each particle is the $m$th entry of the particle that has the highest fitness value in the population. Thus, the vector of global best solutions is in fact the particle that has the highest fitness in the population, which we denote as $\boldsymbol f_{\text{max}}$. \par In contrast, the \textit{local best} solution for the $m$th element of $\boldsymbol f_n$, denoted by $\left[\boldsymbol L\right]_{n,m}$ ($\boldsymbol L \in \mathbb R^{N\times 2M}$), is the $m$th entry of the particle with the highest fitness value among only the neighbouring particles of $\boldsymbol f_n$, which are $\boldsymbol f_{n+1}$ and $\boldsymbol f_{n-1}$.\footnote{We adopt a ring topology, thus, the nighbouring particles for $\boldsymbol f_1$ are $\boldsymbol f_2$ and $\boldsymbol f_N$, while the neighbours of $\boldsymbol f_N$ are $\boldsymbol f_1$ and $\boldsymbol f_{N-1}$.} \par Furthermore, the velocities that control the direction of each particle, which we initialize as $\boldsymbol X = \boldsymbol 0_{N\times 2M}$, are updated at each iteration as follows \cite{kennedy1995particle} {\small \begin{align} \label{vel} \left[\boldsymbol X^{(t+1)}\right]_{n,m} & = \left[\boldsymbol X^{(t)}\right]_{n,m} + w_1r_1 \Big(\left[\boldsymbol L\right]_{n,m}-\left[\boldsymbol F^{(t)}\right]_{n,m}\Big) \nonumber \\ & + w_2r_2 \Big(\left[\boldsymbol f_{\text{max}}\right]_m - \left[\boldsymbol F^{(t)}\right]_{n,m}\Big), n\in \mathcal N, m\in \mathcal M. \end{align}}where $w_1$ and $w_2$ are learning factors, $r_1$ and $r_2$ are random numbers drawn from a uniform distribution with values between $0$ and $1$, and $\mathcal N =\{1, ..., N\}$. To ensure a stable convergence,\footnote{Note that performing the normalization in (\ref{norm}) is crucial, and without it the values of $\boldsymbol X$ can become extremely large (or small) after many iterations, preventing the algorithm from finding any good solution.} we normalize each column of $\boldsymbol X^{(t+1)}$ as \begin{equation}\label{norm} \small \left[\boldsymbol X^{(t+1)}\right]_{:,m} := \mu \times \frac{ \left[\boldsymbol X^{(t+1)}\right]_{:,m}} {\max \left\{\left|\left[\boldsymbol X^{(t+1)}\right]_{:,m}\right|\right\}}, \end{equation} where $\mu \in (0, \pi]$ is an introduced (auxiliary) parameter. Then, the phase-shifts are updated as \begin{equation} \label{update} \small \boldsymbol F^{(t+1)} = \boldsymbol F^{(t)} + \boldsymbol X^{(t+1)}. \end{equation} It is worth to highlight that the value of $\mu$ in (\ref{norm}) controls the speed and accuracy of convergence, and it represents the highest possible phase-shift difference per reflecting element between any two successive iterations. Finally, we re-adjust the entries of $\boldsymbol F^{(t+1)}$ that are either greater than $\pi$ or less than $-\pi$. Due to the circular symmetry of phase-shifts, the re-adjustment can be carried out as follows \begin{equation} \label{adjust} \small \left[ \boldsymbol F^{(t+1)} \right]_{n,m} := \begin{cases} \left[ \boldsymbol F^{(t+1)} \right]_{n,m} + 2\pi, \ \ \ \ \text{if} \left[ \boldsymbol F^{(t+1)} \right]_{n,m} < -\pi \\ \left[ \boldsymbol F^{(t+1)} \right]_{n,m} - 2\pi, \ \ \ \ \text{if} \left[ \boldsymbol F^{(t+1)} \right]_{n,m} > \pi. \end{cases} \end{equation}As shown in Algorithm \ref{Algorithm2}, the same procedure (i.e. fitness evaluation, obtaining \textit{local best and global best} solutions, update of velocities followed by normalization, update of phase-shifts of the population, and re-adjustment) will be repeated in subsequent iterations until a maximum number of iterations is reached, and the particle that achieves the highest fitness value in all $t\in\{0, 1, ..., T-1\}$ iterations will be selected as the final solution. \par When it comes to the per-iteration complexity of the proposed PSO scheme, we can observe that the (fitness evaluation, update of velocity, normalization, update of population, and adjustment), each has a complexity order of $\mathcal O (2MN)$. Thus, and compared to the SDP approach, the PSO becomes particularly attractive when dealing with a large number of reflecting elements, as its complexity scales only linearly with the size of optimization problem. \begin{algorithm}[t] \caption{Proposed PSO algorithm for phase-shifts design} \label{Algorithm2} \begin{algorithmic}[1] \STATE \textbf{input} $\boldsymbol F$ (initial population), $\boldsymbol X$ (initial velocities), $t = 0$, $T$ (maximum number of iterations), and $\mu$, \STATE \textbf{while} $t \le T$ \STATE \ \ \ \ \textbf{evaluate} the fitness of each particle in $\boldsymbol F$, \STATE \ \ \ \ \textbf{find} \textit{global best} and \textit{local best} solutions, \STATE \ \ \ \ \textbf{update} the velocities according to (\ref{vel}), \STATE \ \ \ \ \textbf{normalize} the new velocities according to (\ref{norm}), \STATE \ \ \ \ \textbf{update} the population according to (\ref{update}), \STATE \ \ \ \ \textbf{adjust} the new population according to (\ref{adjust}), \STATE \ \ \ \ \textbf{increment} $t := t + 1$, \STATE \textbf{end while} \STATE \textbf{output}: particle with highest fitness value. \end{algorithmic} \end{algorithm} \section{Results and Discussion} \label{section5} We start by introducing the different narrowband channels and parameters involved in this paper. All channels from and to each RIS are assumed to follow Rician distribution with both line-of-sight (LoS) and non-LoS (NLoS) links, such that $\boldsymbol h_j = \sqrt{\frac{k_r}{k_r+1}} \boldsymbol h^{\text{los}}_j + \sqrt{\frac{1}{1+k_r}} \boldsymbol h^{\text{nlos}}_j$, where $k_r$ is the Rician $K$ factor, $\boldsymbol h^{\text{los}}_j \in\mathbb C^{M\times 1}$ is the deterministic LoS channel vector for the $j$th link, with each element having an absolute value of $1/d_j^{{\alpha_{\text{los}}}/2}$ and a random phase between $0$ and $2\pi$, $\boldsymbol h^{\text{nlos}}_j \sim \mathcal {CN}(\boldsymbol 0_{M\times 1}, \boldsymbol I_M d_j^{-{\alpha}_{\text{nlos}}})$ is the Rayleigh distributed NLoS channel vector, where $d_j$ is the distance between the nodes associated with the $j$th link, $j \in \{si_1, i_1r_1, r_2i_1, i_1d, si_2, i_2r_1, r_2i_2, i_2d\}$, while $\alpha_{\text{los}}$ and $\alpha_{\text{nlos}}$ represent the path-loss exponents for LoS and NLoS links, respectively. In contrast, $h_i \sim \mathcal {CN} (0, d_i^{-\alpha_{\text{nlos}}})$ represents the channel coefficient with Rayleigh distribution for links that do not involve any of the RISs, i.e. $i\in\{sr_1, r_2d\}$. However, for the IRI link, $h_{r_2r_1}$, we consider Rician channel to demonstrate the efficiency of RISs in suppressing the interference even when a strong LoS channel exists. \par The locations of different nodes are set as: $(x_s, y_s) = (0,0)$, $(x_d, y_d) = (100, 0)$, $(x_{r_1}, y_{r_1}) = (50, 25)$, $(x_{r_2}, y_{r_2}) = (50, -25)$, $(x_{i_1}, y_{i_1}) = (50, 30)$, and $(x_{i_2}, y_{i_2}) = (50, -30)$, all in meter units, see Fig. \ref{Fig4}. In addition, we set $w_1 = w_2 = 2$, $\sigma^2 = 1$, $k_{r} = 5$ dB, $ \alpha_{\text{los}} = 2.3$, and $\alpha_{\text{nlos}} = 3.5$. Equal power allocation was utilized and thus $p_s = p_{r_2} = \frac{1}{2}p$, and we define the transmit signal-to-noise ratio (SNR) as $p/\sigma^2$. \par Our simulations compare between the following schemes: \begin{itemize} \item \textbf{RISs-assisted SR (upper-bound)}: This refers to the results obtained by SDP without performing EVD with Gaussian randomization, hence, the term upper-bound. Rician fading is assumed for the IRI channel (i.e. $h_{r_2r_1}$). \item \textbf{SR without RISs}: This case demonstrates the results for SR utilizing only the two relays without the RISs. Rayleigh fading is adopted for all different channels including the IRI link. \item \textbf{RISs only}: In this case, we only have two RISs (therefore no SR) and we optimize their phase-shifts to reflect the signal from $S$ toward $D$, where the former transmits with a power budget of $p$ Watts. \item \textbf{RISs-assisted SR (PSO)}: This case shows the performance of our proposed PSO scheme, assuming Rician-fading for the IRI link. \end{itemize} \begin{figure}[t] \hspace{1.2cm} {\includegraphics[width=7.8cm,height=5.6cm, trim={-1cm -1cm -1cm -1cm},clip]{Fig4.pdf}} \caption{A top-view of the adopted simulation setup.} \label{Fig4} \end{figure} \begin{figure}[t] \centering {\includegraphics[width=6.5cm,height=6.5cm, trim={5.3cm 8.2cm 5.3cm 8.2cm},clip]{Fig2.pdf}} \caption{Achievable rate vs transmit SNR for different schemes when $N = 100$, $T = 200$, and $\mu = \pi/8$.} \label{Fig2} \end{figure} \begin{figure}[t] \centering {\includegraphics[width=6.5cm,height=6.5cm, trim={5.3cm 8.2cm 5.3cm 8.2cm},clip]{Fig3.pdf}} \caption{Convergence behavior of the proposed PSO when $N = 50$, and transmit $\mathrm {SNR} = 50$ dB.} \label{Fig3} \end{figure} \par In Fig. \ref{Fig2}, we depict the achievable rate vs. SNR curves. The RISs-assisted SR notably outperforms both cases of RISs-only scheme and the SR case without RISs. In particular, to achieve an effective rate of $4$ bits/s/Hz, a gain of $15$ dB in transmit SNR can be obtained for the proposed RISs-assisted SR over the RISs-only approach, given that the number of reflecting elements per RIS is $32$. In contrast, the SR case without RISs shows a very poor performance, which highlights the sever impact of the IRI. Moreover, one can also observe from Fig. \ref{Fig2} that there is only a negligible performance gap between the low-complexity PSO scheme and the more complex SDP approach. \par In Fig. \ref{Fig3}, we show the convergence behavior of the proposed PSO scheme for different number of reflecting elements and different values of the auxiliary parameter $\mu$. Regardless of the number of reflecting elements, setting $\mu$ to a small value (in this case $\pi/8$) is preferable as it allows the proposed algorithm to converge toward better solutions that are close to the optimal points. In contrast, larger values of $\mu$ enable faster exploration of new and more diverse populations, and thus they are preferable when the number of optimization iterations is small. However, they are more likely to fail in finding near optimal solutions due to the rapid velocity changes of candidate particles, especially when the number of reflecting elements is relatively large. \section{Conclusion} \label{section6} In this work, a new RIS-aided relay network architecture was proposed with SR, where two RISs were deployed near the two HD-DF relays to provide a spatial suppression of IRI while maximizing the gain of desired signals. An upper bound solution for the achievable rate was obtained via the SDP technique without performing Gaussian randomization and EVD. Subsequently, a lower-complexity beamforming design based on PSO with controlled convergence speed was proposed, and a new normalization step was introduced which guaranteed the stability of the designed scheme. Numerical results demonstrated that RISs can provide large improvements on the rate performance of SR networks, even when a strong line-of-sight link for the IRI existed. Finally, the proposed PSO scheme showed its capability in obtaining near optimal solutions. \section*{Acknowledgment} This work was supported by the Luxembourg National Research Fund (FNR) under the CORE project RISOTTI. \bibliographystyle{IEEEtran}
{'timestamp': '2021-09-14T02:14:33', 'yymm': '2109', 'arxiv_id': '2109.05316', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05316'}
arxiv
\section{\Large{Introduction}} \label{s:intro} Consider a set of $n$ points in the plane, called \textit{sites}. Each site $S_i$ supplies a quantity $q_i$ of a certain unit-priced product that needs to be collected and has an operating time window of $[s_i, e_i]$, where $0 \leq s_i \leq e_i \leq T$, for some constant $T > 0$, $\forall{i = 1, \dots, n}$. The distance $d_{i,j}$ between sites $s_i$ and $s_j$ is the euclidean distance. We are also given a fleet of $m$ vehicles $V = \{v_1, \dots, v_m\}$, each having the same capacity $Q$. All vehicles are assumed to travel at unit speed and have unit fuel consumption per distance travelled. Only one vehicle may visit any given site and all vehicles must start and end their tour at the same given depot $D(x_D, y_D)$. The goal is to compute, for every vehicle $v_k$, a route $r_k$ that collects a quantity $q^k_i$ of the good such that the total profit of all routes is maximized, where the profit of a route $r_k$ is the total quantity collected $\sum_{s_i \in r_k}{q^k_i}$ (called \textit{reward}) minus the total distance travelled via $r_k$ (called \textit{costs}). We call this problem the Maximum Profit pick-up Routing Problem (MPRP). \hspace{5mm}MPRP was introduced in \cite{Armaselu-arXiv-2016, Armaselu-PETRA}, which focuses on the case with fixed quantities and only one vehicle per site. In this paper, we consider the case where multiple vehicles may visit one site. We first study the MPRP problem with Multiple Vehicles Per Site and fixed quantities (MPRP-M), in which $q_i$'s are constant in time. We also consider the MPRP problem with Multiple Vehicles Per Site and Time-Variable Quantities supplied (MPRP-MVS), in which $q_i(t)$'s are 0 for $t \notin [s_i, e_i]$ and linearly increasing in time for $t \in [s_i, e_i]$. Compared to the single vehicle versions, this adds the availability constraint that $\sum_{j, u \leq t}{q_{iju}} \leq q_i(t), \forall{i, t}$. However, a vehicle may not visit a site more than once. \hspace{5mm}MPRP is known to be strongly NP-hard \cite{Armaselu-PETRA}. By extensions, all the variants proposed above are also strongly NP-hard. That is, they have no algorithm running in time polynomial in the value of the input unless P = NP. \hspace{5mm}Applications of the results presented in this paper include public transportation in various settings, such as cities \cite{Armaselu-PETRA}, inter-city railway transportation, domestic or international flight, etc. Another important application is in for-profit waste pick-up, in which the reward is proportional to the amount of waste collected. \subsection{\large{Related work}} \label{ss:related-work} General graph TSP is proven to be hard to approximate within any constant factor \cite{Sahni}. However, TSP on special graphs, such as complete graphs with metric distances ane euclidean distances, do have approximation algorithms. For instance, general metric TSP has a $O(n^3)$ time $1.5$-approximation algorithm by Christofides \cite{Christofides}. Euclidean metric TSP even has a PTAS achieving $1 + \epsilon$ performance ratio via Arora's $O(n (\log n)^{O(1/\epsilon)})$ time algorithm \cite{Arora}. On the other hand, metric TSP was shown to be APX-complete by Papadimitriou et. al \cite{Papadimitriou} and, to date, the best known lower bound is $123/122$ by Karpinski et. al \cite{Karpinski}. \hspace{5mm}Various generalizations of TSP have also been considered. Bansal et. al introduced the Deadline-TSP and the Time Window-TSP problems \cite{Bansal}. In Deadline-TSP, every site $S_i$ has a deadline $D_i$, while in Time Window-TSP, every site $S_i$ has a time window $[s_i, e_i]$. Both of these problems associate every site $S_i$ with a reward $q_i$ and ask for a single tour that maximized the total reward collected. For Deadline-TSP, they provide an $O(\log n)$-approximation algorithm, while for Time Window-TSP they describe an $O(\log^2 n)$-approximation. \hspace{5mm}There are also variants involving multiple vehicles. Fisher introduced the Vehicle Routing Problem with capacity constraint (VRP), in which a fleet of $m$ vehicles is given, and each customer $S_i$ has a demand $q_i$ of a certain product \cite{Fisher94}. Their solution uses an iterative lagrangian relaxation of the constraints. Later, Fisher et. al introduced the Vehicle Routing Problem with Time Windows and capacity constraints (VRPTW), in which customers have a demand $q_i$ of the product, as well as operating time windows, and the $m$ vehicles have non-uniform capacity constraints \cite{Fisher95}. They solve this problem using a linear programming approach. \hspace{5mm}Golden et. al studied the Capacitated Arc Routing Problem (CARP) with uniform vehicle capacity where edges, rather than vertices, have customer demands, and the goal is to minimize the travelled distance subject to meeting all demands. They prove that CARP can be approximated within a constant factor when the triangle inequality is satisfied \cite{Golden}. Later, van Bevern extended the result to general undirected graphs \cite{Bevern}. \hspace{5mm}Wang et. al considered the Multi-Depot Vehicle Routing Problem (MDVRPTW) with Timw Windows and Multi-type Vehicle Number Limits \cite{Wang}. The main difference to our problem is that the goal is to minimize the number of vehicles used (if feasible) or maximize the number of visited customers (if infeasible). Although they solve the problem using a genetic algorithm approach, their algorithm is iterative and has no performance guarantee with respect to the approximation factor. \hspace{5mm}Versions of vehicle routing with multiple vehicles per customer have also been considered. In \cite{Drexl}, Drexl does a comprehensive survey of variations of vehicle routing with multiple synchronization constraints (VRPMS), e.g. in which a customer may be visited by two vehicles (VRPTT) \cite{Bredstrom}, or by 3 or more vehicles \cite{Burckert}. \hspace{5mm}Armaselu and Daescu solved the fixed-supply, single vehicle version of MPRP \cite{Armaselu-arXiv-2016, Armaselu-PETRA}. They provide two APXs for MPRP, both running in $O(n^{11})$ time, assuming $q_i(l_i) \leq \alpha q_j(l_j), \forall{i, j = 1, \dots, n}$, for some constant $\alpha > 1$. The best performance ratio, $15 \log T$, among the two algorithms, is achieved by an approach involving well-separated pair decompositions. \subsection{\large{Our contributions}} \label{ss:structure} We give a constant-factor approximation algorithm for MPRP-M and MPRP-MVS, which uses clever reductions to some known problems. Specifically, we solve MPRP-M in $O(n^{11})$ time for an approximation ratio of $\simeq 44 \log T$ and MPRP-MVS in $O((\frac{n}{\epsilon})^{11})$ time within an approximation ratio of $44 \log T (1 + \epsilon)(1 + \frac{1}{1 + \sqrt{m}})^2$. \hspace{5mm}The rest of the paper is structured as follows. In Section \ref{s:mprp-m}, we describe our MPRP-M algorthm, and then, in Section \ref{s:mprp-mvs}, we describe our solution to MPRP-MVS. Finally, in Section \ref{s:conclusion}, we conclude and list some future directions. \section{\Large{MPRP-M}} \label{s:mprp-m} We come up with a reduction from MPRP-M to MPRP. \hspace{5mm}Let $d(0, i) = d(i, 0)$ be the distance from the depot to site $S_i, \forall{i: 1 \leq i \leq n}$. \hspace{5mm}An instance $I$ of MPRP (or MPRP-M) can be described as a set $I = (S = \{S_i: 1 \leq i \leq n\}, D = (x_0, y_0), d = \{d(i, j): 0 \leq i < j \leq n\}, T, Q, m)$, where $S_i = (x_i, y_i, s_i, e_i, q_i)$. \hspace{5mm}A solution $Sol$ to $I$ is a set $Sol = (R, P)$. Here $R$ is a routing function assigning, to every pair of sites or depot $(i, j), 0 \leq i, j \leq n$, a number $k(i, j): 0 \leq k(i, j) \leq m$, denoting the index of the vehicle operating the path from $S_i$ to $S_j$, or 0 if no such vehicle exists. $P$ is a pickup function assigning, to every site $S_i$ on vehicle $v_k$'s route, a quantity $q_{k,i} \leq q_i, Q$ to be picked up by $v_k$. \hspace{5mm}A solution $Sol'$ to $I'$ is a routing function with the same properties as the function $R$ in$Sol$. \hspace{5mm}Denote by $MPRP$ (resp., $MPRP-M$) the set of MPRP (resp., MPRP-M) instances. \hspace{5mm}Starting from $I = (\{(x_i, y_i, s_i, e_i, q_i): 1 \leq i \leq n\}, (x_0, y_0), \{d_{i,j}: 0 \leq i < j \leq n\}, T, Q, m) \in MPRP-M$, let $I' = (\{(x_i, y_i, s_i, e_i, q_i): 1 \leq i \leq n\}, (x_0, y_0), \{d_{i,j}: 0 \leq i < j \leq n\}, T, Q, m) \in MPRP$. That is, $I'$ has \textit{the same nodes and distances} as $I$. We solve $I'$ using the algorithm in \cite{Armaselu-PETRA} and denote by $Sol'$ the solution. \hspace{5mm}We transform the solution $Sol'$ to an MPRP instance $I'$, into a solution $Sol$ to an MPRP-M instance $I$, as follows. For every vehicle $v_k$ of $I'$, let $Q_k$ be the total quantity collected by $v_k$ from its assigned tour $\tau'_k \in Sol'$. It may be possible that some sites in $\tau'_k$ need to be visited multiple times in $I$, producing a new tour $\tau_k \in Sol$. To figure out which ones need to, we look at tuples of sites $(S_u, S_{u'}, S_i, S_{i'}, S_j, S_{j'}) \in S^2 \times (S \cup D)^4$ in $I'$ where \begin{equation} \begin{cases} S_u \in \tau'_k\\ S_{u'} \in \tau'_{k'}\\ S_i, S_j$ consecutive in $\tau'_k\\ S_{i'}, S_{j'}$ consecutive in $\tau'_{k'} \end{cases} \end{equation} \hspace{5mm}The goal is to maximize the total amount picked up from $\tau'_k$ and $\tau'_{k'} \cup \{S_u\}$. Denote by $q_{u', k'}$ the quanity assigned to be picked up by $v_{k'}$ from $S_{u'}$, by $q_{u', k}$ the quanity assigned to be picked up by $v_{k}$ from $S_{u'}$, and by $q_{u, k}$ the quanity assigned to be picked up by $v_{k}$ from $S_{u}$. We have \begin{equation} \begin{cases} Q_k + q_{u, k} + q_{u', k} - q_{u'} \leq Q\\ Q_{k'} + q_{u', k'} \leq Q\\ q_{u', k} + q_{u', k'} \leq q_{u'}\\ q_{u, k} \leq q_u \end{cases} \end{equation} \hspace{5mm}and our goal is to maximize $q_{u', k} + q_{u', k'} + q_{u, k}$. To do that, we set $x = q_{u, k}, y = q_{u', k}, z = q_{u', k'}$, and we come to the following linear program. \begin{center} Minimize $x + y + z$ s.t. \end{center} \begin{equation} \begin{cases} x \leq q_u\\ y + z \leq q_{u'}\\ z \leq Q - Q_{k'} \end{cases} \end{equation} \hspace{5mm}After solving the linear program, we check the additional constraint $x + y \leq Q - Q_k + q_{u'}$. If it is satisfied, we assign $v_{k'}$ to pickup $z^*$ from $S_{u'}$, and $v_k$ to pickup $x^*$ from $S_u$ and $y^*$ from $S_{u'}$ in $Sol$, where $(x^*, y^*, z^*)$ is a solution to the linear program. In order for $Sol$ to achieve a better profit than $Sol'$ through this re-assignment, the following need to hold. Let $S_u < S_v$ denote that $S_u$ is visited before $S_v$ in $\tau'_{k'}$. \begin{equation} \begin{cases} x^* + y^* + z^* - q_{u'} > d(i', i) + d(i, i'') - d(i', i'')\\ d(i', i) + d(i, i'') - d(i', i'') \leq \min\{t_{k', v'} - s_{v'}: S_{v'} < S_{i'}\} + \min\{e_{w'} - t_{k', w'}: S_{j'} < S_{w'}\} \end{cases} \end{equation} where $t_{k, i}$ is the time when $v_k$ visits $S_i$. That is, insertion of $S_i$ into $\tau_{k'}$ in $Sol$ does not introduce time window violations \hspace{5mm}See Figure 2 for an illustration of this re-assignment. \begin{figure} \label{fig:reduction-option1} \begin{center} \includegraphics[scale=0.4]{reduction-option1.png} \caption{Tours of $Sol'$ are depicted in solid lines and tours of $Sol$ are depicted using dashed lines. $v_k$ is assigned to pickup 35 from $S_u$ and 20 from $S_{u'}$, while $v_{k'}$ is assigned to pickup 35 from $S_{u'}$. Since time windows are not violated, $Sol$ is more profitable than $Sol'$.} \end{center}` \end{figure} \hspace{5mm}For each vehicle $v_k$ and site $S_{u'} \in \tau'_k$, we look at all possible tuples $(S_u, S_i, S_{i'}, S_j, S_{j'}) \in S \times (S \cup D)^4$ satisfying the abovementioned additional constraints and solve the linear program to find the optimal quantities to pickup, then select the tuples that maximize the profit gain after re-assignment, and then perform the re-assignment. \hspace{5mm}One arising concern is that the order in which the pairs $(v_k, S_{u'})$ are selected produces different results. However, while this may happen, it may not impact the optmiality of the re-assignment by more than a constant factor, as we shall see below. \begin{lemma} Let $O$ be an ordering of the pairs $(v_k, S_{u'})$ and let $\Delta(k, u')$ be the gain obtained through re-assignment when selecting pair $(v_k, S_{u'})$ (or 0, if re-assignment is infeasible). Then $\sum_{k, S_{u'} \in \tau'_k} \Delta(k, u') = \Delta \in [C, 4 C]$, where $C$ does not depend on $O$. \end{lemma} \begin{proof} From (4), it follows that \[ \Delta(k, u') = \max\{0, x^* + y^* + z^* - q_{u'} - d(i', i) - d(i, i'') + d(i', i'')\} \] \[ \geq \max\{0, x^* + y^* + z^* - q_{u'}\} \] \[ + \max\{-t_{k', v'} + s_{v'}: S_{v'} < S_{i'}\} \] \[ + \max\{-e_{w'} + t_{k', w'}: S_{w'} > S_{j'}\} \tag{5} \label{eq5} \] where $S_i < S_j$ indicates that $S_i$ is before $S_j$ in $\tau'_{k'}$. \bigskip \hspace{5mm}Since $x^* = q_{u, k}, y^* = q_{u', k}, z^* = q_{u', k'}$, we get \[ \Delta = \sum_{k, S_{u'} \in \tau'_k} \Delta(k, u') \] \[ \geq \sum_{k, S_{u'} \in \tau'_k} \max\{0, q_{u, k} + q_{u', k} + q_{u', k'} - q_{u'}\} \] \[ + \sum_{k, S_{u'} \in \tau'_k} \max\{-t_{k', v'} + s_{v'}: S_{v'} < S_{i'}\} \] \[ + \sum_{k, S_{u'} \in \tau'_k} \max\{-e_{w'} + t_{k', w'}: S_{w'} > S_{j'}\} \tag{6} \label{eq6} \] \hspace{5mm}We have \[ \sum_{k, S_{u'} \in \tau'_k} q_{u', k} = \sum_{k, S_{u'} \in \tau'_k} q_{u'} = \sum_{k, S_i \in \tau'_k} q_i, \tag{7} \label{eq7} \] \[ \sum_{k, S_{u'} \in \tau'_k} \max\{-t_{k', v'} + s_{v'}: S_{v'} < S_{i'}\} \geq \sum_k (s_i - t_{k, i}: i \in \tau_k), \tag{8} \label{eq8} \] \[ \sum_{k, S_{u'} \in \tau'_k} \max\{-e_{w'} + t_{k', w'}: S_{w'} > S_{j'}\} \geq \sum_k (t_{k, i} - e_i: i \in \tau_k). \tag{9} \label{eq9} \] \bigskip \hspace{5mm}Let $Q^* = \sum_{\tau'_k, S_i \in \tau'_k} q_i, Q^s = \sum_k (s_i - t_{k, i}: i \in \tau_k), Q^e = \sum_k (t_{k, i} - e_i: i \in \tau_k)$. Since $\sum_{k, S_{u'} \in \tau'_k} \max\{0, q_{u, k} + q_{u', k}\} \geq Q^*$, it follows that \[ \Delta \geq Q^* + Q^s+ Q^e. \tag{10} \label{eq10} \] Moreover, note that $Q^s + Q^e = \sum_k(s_i - t_{k, i} + t_{k, i} - e_i) = \sum_k(s_i - e_i)$. That is, $\Delta \geq C = Q^* - \sum_k(e_i - s_i)$, where $C$ does not depend on $O$. \bigskip \hspace{5mm}Note that \[ x^* + y^* + z^* - q_{u'} \leq 2 (d(i', i) - d(i, i'') + d(i', i'')), \forall{u', i, i', i''}, \tag{11} \label{eq11} \] since otherwise one would be able to create an optimal metric-space MST-based tour of cost $> 2 C$, which is a contradiction of the result in \cite{Christofides}. \hspace{5mm}Thus, \[ \Delta \leq 2 (\sum_{k, S_{u'} \in \tau'_k} \max\{0, q_{u, k} + q_{u', k} + q_{u', k'} - q_{u'}\} \] \[ + \sum_{k, S_{u'} \in \tau'_k} \max\{-t_{k', v'} + s_{v'}: S_{v'} < S_{i'}\} \] \[ + \sum_{k, S_{u'} \in \tau'_k} \max\{-e_{w'} + t_{k', w'}: S_{w'} > S_{j'}\}). \tag{12} \label{eq12} \] \hspace{5mm}Since \[ \max\{-t_{k', v'} + s_{v'}: S_{v'} < S_{i'}\} + \max\{-e_{w'} + t_{k', w'}: S_{w'} > S_{j'}\} \] \[ \leq 2 \max{s_{v'} - e_{w'}} \leq 2 T, \] for sufficiently large $\frac{\min{q_i}}{2 T}$, which is reasonable since $T$ is constant, we get \[ \Delta \leq 4 \sum_{k, S_{u'} \in \tau'_k} \max\{0, q_{u, k} + q_{u', k} + q_{u', k'} - q_{u'}\} \] \[ \leq 4 (Q^* + Q^s+ Q^e). \tag{13} \label{eq13} \] \hspace{5mm}That is, $\Delta \leq 4 C$. \end{proof} Thus, we first run a MPRP solver to obtain a routing $\tau'$ and then select the pairs $(v_k, S_{u'})$ in the order given by each $\tau'_k$ for every $k$. For each of the $O(m n)$ pairs, we inspect all possible $O(n^5)$ tuples in $O(n)$ time per tuple, which is the time required to verify constraint 2. That is, our reduction is done in $O(m n^7)$ time. \hspace{5mm}As for the correctness of the reduction, suppose there exists a routing $\tau''$ for $I'$ yielding a profit increased by more than a factor of 4 compared to $\tau'$. In order to do that, $\tau''$ must pickup a quantity $q''_{u'} >4 q_{u'}$ from some $S_{u'}$. However, this implies that either $S_{u'}$ is not re-assigned in $\tau$ and thus gives an increased profit for $I'$, or is re-assigned to one of $S_u, S_i, S_{i'}, S_j, S_{j'}$ and thus gives an increased profit for one of these sites. Both options lead to a contradiction. Now suppose there exists a routing $\tau''$ for $I$ yielding an increased profit compared to $\tau$. In order for that to happen, either some site $S_{u'}$ that was never added or involved in a re-assignment picks up a quantity $q''_{u', k} > q_{u', k}$ , implying an increased profit for $q''_{u'} > 4 q'_{u'}$ for $S_{u'}$ in $\tau'$, or some site $S_{u'}$ involved in a re-assignment with $(S_u, S_i, S_{i'}, S_j, S_{j'})$ picks up a quantity $q''_{u', k} > 4 q_{u', k}$ , implying a quantity was picked up from some site (wlog assumed to be $S_u$) in $\tau''$ which is more than 4 times the one picked from the samee site in $\tau'$. In both cases, a contradiction follows due to Lemma 1. Hence, we have reduced MPRP-M to MPRP within an approximation ratio of 4 in $O(m n^7)$ time. \hspace{5mm}By using the $\simeq 11 \log T$-approximation for MPRP in \cite{Armaselu-PETRA} for $O(n^{11})$ time, we thus solve MPRP-M in $O(n^{11})$ time. \hspace{5mm}We have proved the following result. \begin{theorem} MPRP-M can be solved in $O(n^{11})$ time for an approximation ratio of $\simeq 44 \log T$. \end{theorem} \section{\Large{MPRP-MVS}} \label{s:mprp-mvs} In MPRP-MVS, quantities $q_i$ supplied at sites vary linearly as a function of time, i.e. $q_i(t) = q_i(e_i) \frac{t - s_i}{e_i - s_i}$. \hspace{5mm}We adapt the algorithm in \cite{Armaselu-arXiv-2020} for solving MPRP-VS, to work in our case, by using a similar reduction as the one from MPRP-M to MPRP described in the previous section, to reduce MPRP-MVS to MPRP-VS. \hspace{5mm}Given an instance $I = (S = \{S_i: 1 \leq i \leq n\}, D = (x_0, y_0), d = \{d(i, j): 0 \leq i < j \leq n\}, T, Q, m)$ of MPRP-MVS, we apply the reduction in \cite{Armaselu-arXiv-2020} to obtain an instance $I'' \in MPRP-M$, and then solve MPRP-M using the algorithm in Section \ref{s:mprp-m}. Again, this is not straightforward since the approach in \cite{Armaselu-arXiv-2020} depends on single vehicle assignment which is not the case here. Thus, we need a more insightful construction of $I''$ than directly applying the algorithm in \cite{Armaselu-arXiv-2020}. \hspace{5mm}For each site $S_i$, we split $[s_i, e_i]$ into $N = 1 + \frac{\ln(1/\alpha)}{\epsilon}$ intervals, for some $\epsilon > 0$, where $\alpha > 1$ is the smallest constant such that $q_i(e_i) \leq \alpha q_j(e_j), \forall{i, j}$. Denote these intervals by $L_{i, l}: 1 \leq l \leq N$, i.e. $L_{i,l} = [s_i + \frac{e_i - s_i}{(1+\epsilon)^{N-l+1}}, s_i + \frac{e_i - s_i}{(1+\epsilon)^{N-l}}]$. After performing this split, we construct a set of sites $S'$ where, for each original site $S_i$, $S'$ contains $N$ sites $S''_{i, \tau}, 1 \leq \tau \leq N$. To each newly constructed site $S''_{i, l}$, we assign a quantity $q'_{i, l} = q_i(e_i) \frac{l - 0.5}{N - 1}$ and a time window $I_{i,l}$. We then run the MPRP-M Option 1 algorithm described in Section \ref{s:mprp-m} on the transformed instance $I'' = (S'', D, d, T, Q, m)$ (note that $I'' \in MPRP-M$ since the sites in $S''$ now supply constant quantities). \hspace{5mm}Denote by $\tau''$ the routing obtained by running the MPRP-M algorithm on $I''$. We now analyze the properties of $\tau''$ in order to put a bound on its performance ratio. \hspace{5mm}We know from \cite{Armaselu-arXiv-2020} that an optimal MPRP algorithm run on $S'$ may collect a quantity at least $\frac{1}{1 + \epsilon}$ as much as an optimal MPRP-VS algorithm run on $S$. Since for $m = 1$, an instance of MPRP-M also belongs to MPRP, and an instance of MPRP-MVS is also an instance of MPRP-VS, we get the following. \begin{lemma} For $m = 1$, an optimal MPRP-M algorithm when run on $S''$ may collect a quantity at least $\frac{1}{1 + \epsilon}$ as high as an optimal MPRP-MVS algorithm when run on $S$. \end{lemma} \begin{lemma} \cite{Armaselu-arXiv-2020} Let $A$ be an algorithm for a MPRP (resp., MPRP-M) and let $P(I)$ be the profit obtained by $A$ when run on an instance $I$ with one vehicle. Then, on an instance $I'$ with $m$ vehicles, the profit obtained by $A$ is $P(I') \geq \frac{P(I)}{(1 + \frac{1}{1 + \sqrt{m}})^2}$. \end{lemma} \hspace{5mm}By running the $\frac{1}{44 \log T}$-optimal MPRP-M algorithm in Section \ref{s:mprp-m} on $I''$, we get the following a profit at least $\frac{1}{44 \log T (1 + \frac{1}{1 + \sqrt{m}})}$ as high as an optimal MPRP-MVS algorithm when run on $I$. \hspace{5mm}Since travel costs are less than the rewards generated by the quantities collected, a performance ratio of $\frac{1}{1 + \epsilon}$ in the quantities induces a performance ratio of $\frac{1}{1 + \epsilon}$ in the profits as well. Putting this together with the lemma above, we get the following. \begin{lemma} When run on $I''$, the MPRP-M algorithm in Section \ref{s:mprp-m} may obtain a profit at least $\frac{1}{44 \log T (1 + \epsilon)(1 + \frac{1}{1 + \sqrt{m}})^2}$ as high as an optimal MPRP-MVS algorithm when run on $I$. \end{lemma} \hspace{5mm}Note that the reduction described before Lemma 2 takes $O(\frac{n}{\epsilon})$ time. Then, running MPRP-M on $I''$ which has $|S''| = O(\frac{n}{\epsilon})$ sites, takes $O((\frac{n}{\epsilon})^{11})$ time. Thus, we have proved the following result. \begin{theorem} MPRP-MVS can be solved in $O((\frac{n}{\epsilon})^{11})$ time within an approximation ratio of $44 \log T (1 + \epsilon)(1 + \frac{1}{1 + \sqrt{m}})^2$. \end{theorem} \section{\Large{Conclusions and Future Work}} \label{s:conclusion} We solve the Multiple Vehicles per Site versions of the Maximum-Profit Routing Problem, specifically, the Fixed-Supply version and the Time-Variable Supply version. \hspace{5mm}We leave for future consideration probablisitc approaches for all versions of MPRP, e.g. algorithmic solutions whose output is, with high probability, within a certain bound of the optimum for the given instance. Proving negative results or lower bounds, e.g. inaproximability within a certain ratio, would also be of interest.
{'timestamp': '2021-09-14T02:18:16', 'yymm': '2109', 'arxiv_id': '2109.05404', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05404'}
arxiv
\section{Abstract} The utilization of prior knowledge about anomalies is an essential issue for anomaly detections. Recently, the visual attention mechanism has become a promising way to improve the performance of CNNs for some computer vision tasks. In this paper, we propose a novel model called Layer-wise External Attention Network (LEA-Net) for efficient image anomaly detection. The core idea relies on the integration of unsupervised and supervised anomaly detectors via the visual attention mechanism. Our strategy is as follows: (i) Prior knowledge about anomalies is represented as the anomaly map generated by unsupervised learning of normal instances, (ii) The anomaly map is translated to an attention map by the external network, (iii) The attention map is then incorporated into intermediate layers of the anomaly detection network. Notably, this layer-wise external attention can be applied to any CNN model in an end-to-end training manner. For a pilot study, we validate LEA-Net on color anomaly detection tasks. Through extensive experiments on PlantVillage, MVTec AD, and Cloud datasets, we demonstrate that the proposed layer-wise visual attention mechanism consistently boosts anomaly detection performances of an existing CNN model, even on imbalanced datasets. Moreover, we show that our attention mechanism successfully boosts the performance of several CNN models. \section{1. Introduction} \label{sec:introduction} \begin{figure}[ht \centering \captionsetup{justification=raggedright, singlelinecheck=off} \includegraphics[width=\hsize]{figure/Overview_ver3.pdf} \caption{Overview of the color anomaly detection.} \label{fig:Overview} \end{figure} Anomaly detection is a technique to identify irregular or unusual patterns in datasets. Especially, anomaly detection for imaging data is a powerful and core technology for various kinds of real-world problems including medical diagnosis~\cite{rezvantalab2018dermatologist,cao2018deep}, plant healthcare~\cite{Ferentinos_2018}, production quality controls, and disaster detection~\cite{Minhas,8995282}. Over the last decade, many researchers have shown great interest in establishment of automatic anomaly detection techniques for a huge image dataset driven by breakthroughs in deep learning. Based on types of machine learning, these anomaly detection techniques can be roughly classified into three categories: supervised, semi-supervised, and unsupervised approaches. Although there are advantages and disadvantages with each approach, the fundamental challenge that should be overcome is on how we detect anomalies efficiently based on limited numbers of anomalous instances. Convolutional neural network (CNN) is a commonly used artificial network for various computer vision tasks including image recognition and image segmentation. Using a huge dataset of labeled images, CNNs have realized a state-of-the-art image anomaly detection in a real-world applications~\cite{Hughes_2016, Minhas}. However, anomaly detectors based on CNN suffer from a lack of labeled images and low anomaly instances. Some studies have proposed ideas for overcoming this point by improving learning efficiency of CNN. In particular, one introduced active learning~\cite{goernitz2013} and the other employed transfer learning~\cite{Minhas} for that purpose. Approaches based on unsupervised learning are the most popular way for anomaly detection, because they do not require labeled anomalous instances to train anomaly detectors. The simple strategy of unsupervised image anomaly detections relies on a training of reconstruction processes for normal images using a deep convolutional autoencoder~\cite{haselmann2018anomaly}. However, the autoencoder sometimes fails to reconstruct fine structures. Consequently, it outputs immoderate blurry structures. Recently, generative adversarial networks (GAN) have been used for image anomaly detection to overcome this point. AnoGAN~\cite{Schlegl2017} firstly employed GAN to image anomaly detection. In applications of medical image processing, AnoGAN and its extensions~\cite{Zenati_2018, Akcay_2018} realized to detect minute anomalies. More recently, the idea of AnoGAN was extended in terms of color reconstructability to realize sensitive detection of color anomalies~\cite{Katafuchi2021}. It is a common procedure in unsupervised anomaly detection to define the difference between the original image and the reconstructed image as {\it Anomaly Score}. Although unsupervised anomaly detectors can eliminate the labeling cost of anomalous instances for a training step, there are some drawbacks. First, they tend to overlook small and minute anomalies because {\it Anomaly Score} is defined based on the distance of the normal images and test images. In other words, the detection performance strongly depends on whether we can design a good {\it Anomaly Score} for each purpose. Also, we should tune carefully the appropriate threshold of {\it Anomaly Score} for successful classifications of normal and anomalous instances. In most practices, this process requires painful trial and error. Nowadays, the technique called visual attention mechanism is attracting much attention in computer vision~\cite{Zhao2020}. Attention Branch Network (ABN) is a CNN with a branching structure called {\it Attention Branch}~\cite{Fukui}. Attention map that output from {\it Attention Branch} represent visual explanations, which enables humans to understand the decision-making process of CNN. Further, the authors reported that the attention map contributes to improving the performances of CNN for several image classification tasks. Since then, researchers in computer vision have attempted to build the technique that finely induces the attention of CNN to informative regions in images. For the last several years, it has been shown that such technique is promising for improving the performance of CNN for several computer vision tasks involving image classification and segmentation~\cite{Fukui,emami2020spa}. Inspired by these studies, one may think to introduce the visual attention mechanism to image anomaly detection. However, visual attention modules including ABN basically relies on self-attention mechanisms~\cite{Hu2020,Woo2018}. Accordingly, the attention quality of the modules strongly depends on the performance of the network itself, which means that existing visual attention mechanisms would not be able to boost the performance of anomaly detectors directly. In this paper, we propose Layer-wise External Attention Network (LEA-Net) to boost CNN-based anomaly detectors. As we mentioned above, purely unsupervised anomaly detectors do not utilize anomalous instances at all for training. As a result, they tend to overlook small and minute anomalies, or conversely, incur high false positives. On the other hand, purely supervised approaches suffer from lack of labeled images, especially from lack of anomalous instances. We tackle these problems by integrating supervised and unsupervised anomaly detectors via visual attention mechanism. Recent progress in visual attention mechanism strongly implies that there must be a way to utilize prior knowledge for anomaly detection. Our expectation is that the anomaly map that generated from an unsupervised anomaly detector is powerless by itself for efficient anomaly detection but useful to boost supervised anomaly detectors. Moreover, we expect that such a boosting approach contributes to reduce developing cost of anomaly detectors because we can divert existing image classifiers for image anomaly detection. Our overall strategy is as follows: (i) Prior knowledge on anomalies is represented as the anomaly map, which is generated through unsupervised learning of normal instances, (ii) The anomaly map is translated to an attention map by the external network, (iii) The attention map is then incorporated into intermediate layers of the anomaly detection network. We note that this layer-wise external attention can be applied to any CNN model with an end-to-end training manner. For a pilot study, we focus on color anomaly detection tasks because color anomalies are comparatively easy to represent based on CIEDE2000 color difference~\cite{Katafuchi2021}. We examined the effectiveness of LEA-Net through extensive experiments using real-world publicly available datasets including PlantVillage, MVTec AD, and Cloud datasets. The results demonstrated that the proposed layer-wise visual attention mechanisms consistently boost performances of anomaly detectors even on imbalanced datasets. Moreover, it was shown that the attention mechanism works well for multiple feed-forward CNN models. Our contributions are as follows: \begin{itemize} \item We propose a novel anomaly detection model called Layer-wise External Attention Networks (LEA-Net) for efficient image anomaly detection with a limited number of anomalous instances. \item We showed that our layer-wise external attention mechanism successfully boosts the performance of the color image anomaly detectors, even for small and imbalanced training datasets. \item We found that the layer-wise external attention mechanism is effective for existing feed-forward CNN models. \item We provide our code and models as open source at https://github.com/RxstydnR/LEA-Net. \end{itemize} \section{2. Related Work} The proposed approach is an integration of unsupervised image translation and supervised anomaly detection. Most recently, a simpler approach was adopted in a task of automatic identification for thyroid nodule lesions in X-ray computed tomography images~\cite{Li2021}. The technique uses binary segmentation results obtained from U-Net as inputs for supervised image classifiers. The authors showed that the binary segmentation as a preprocessing for an image classification contributes to improving anomaly detection in a real-world problem. Looking for a somewhat similar setting, Convolutional Adversarial Variational autoencoder with Guided Attention (CAVGA) uses an anomaly map in a weakly supervised setting to localize anomalous regions~\cite{venkataramanan2020attention}. Through experiments for image anomaly detection using MVTec AD, CAVGA achieved SOTA results. These two studies imply that the introduction of a visual attention map has a great potential for image anomaly detection. A visual attention mechanism typically refers to the process of refinement or enhancement of image features for recognition tasks. The human perceptual system tends to preferentially capture information relevant to the current task, rather than processing all information~\cite{reynolds2004attentional,chun2011taxonomy}. Visual attention mechanisms basically imitate this for image classification~\cite{Hu2020,Wang2017,Woo2018,Lee2019,Wang2020,yang2021simam}. Most image classifiers with visual attention adopt a self-attention module that works in plug-and-play to existing models. In such specifications, the effectiveness of visual attention strongly depends on the performance of the main body of the model: this is a limitation of self-attention approaches. Attention Branch Network (ABN)~\cite{Fukui} overcame this problem by interactive edit of attention map. It enabled us to induce focus points of CNN to more informative regions on images through the correction of attention map. Another similar visual attention mechanism is Attention Transfer based on knowledge distillation~\cite{Zagoruyko2017}. In knowledge distillation, a smaller network called student network receives prior knowledge from a larger network called teacher network~\cite{hinton2015distilling}. The idea of Attention Transfer relies on an assumption that a teacher network tends to focus on a more informative area than does a student network. We designed LEA-Net inspired by ABN and Attention Transfer Network with several points of improvement. Our method does not require any user-interaction to control focus points of CNN. The training of LEA-Net goes on fully automatically through a collaboration of two networks that we call external network and anomaly detection network. The external network adjusts the strength of attention with progress of training to avoid excessive effects of visual attention mechanism in the early stage of training. Also, we note that the effectiveness of the layer-wise external attention mechanism is not constrained by the teacher network unlike Attention Transfer Network. \section{3. Proposed Method} \begin{figure*}[t] \centering \captionsetup{justification=centering, labelfont=bf} \includegraphics[width=0.8\hsize]{figure/CAAN_AttentionMechanism_ver3.pdf} \caption{Overall structure of LEA-Net.} \label{fig:AttentionMechanism} \end{figure*} As we mentioned in Section~1, we focus on color anomaly detection tasks for a pilot study. In Fig.\ref{fig:Overview}, we illustrate the overview of our color anomaly detection. The procedure can be divided into two steps: (a) color anomaly map generation and (b) color anomaly detection. Details will be described below. \subsection{3-1. Color Anomaly Map Generation} In step~(a), a grayscale image is firstly obtained from the input color image represented in $L^{*}a^{*}b^{*}$ color space. Then, the grayscale image is reconverted to a color image using U-Net~\cite{ronneberger2015u}. To supplement, the color information $a^{*}b^{*}$(chrominance) is predicted based on $L^{*}$ (luminance) information in the $L^{*}a^{*}b^{*}$ color space. Second, the predicted $a^{*}b^{*}$ is combined with the $L^{*}$ of input to produce the resulting colored image in $L^{*}a^{*}b^{*}$ color space. The U-Net learns in advance the process of color reconstruction with normal instances only. Then, a color anomaly map is generated by calculating CIEDE2000~\cite{Sharma_2005} color difference between the reconstructed image and the original image. For details of the color anomaly generation, see~\cite{Katafuchi2021}. Here we consider data augmentation because the concern of this study is on anomaly detection with comparatively few training data. Empirically, the color reconstruction often fails for quite bright or dark images. Hence, we use Fancy PCA image augmentation~\cite{krizhevsky2012imagenet} to amplify the variation of image luminances. \subsection{3-2. Color Anomaly Attention Network~(CAAN)} We describe the detail of Fig.~\ref{fig:Overview}(b): Anomaly detection step. In this step, we use two different image classifiers. One is Color Anomaly Attention Network~(CAAN), which converts the anomaly map to an attention map. Except for color anomaly detection, we call the network {\it External Network}. The other is Anomaly Detection Network~(ADN), which outputs the final decision for anomaly detection. It is desirable that CAAN is a lightweight and effective model to work in plug-and-play without a massive increase in parameters. To that purpose, architectures of CAAN were designed based on MobileNet and ResNet. Detailed structures of CAAN are described in Table~\ref{tab:CAAN}. The structure of MobileNet-based CAAN is exactly same as MobileNetV3-Small \cite{howard2019searching}. Besides, the structure of ResNet-based CAAN is configured by simply stacking five residual blocks~\cite{he2016deep}. We note that these two models are generic for image classifiers. Therefore, they can be replaced easily by other networks. \subsection{3-3. Anomaly Detection Network~(ADN)} The role of ADN is to make the final decision for image anomaly detection utilizing prior knowledge received from CAAN. We adopted ResNet18 and VGG16 for ADN, both of which are well-known and widely-used CNN for image classifications. The number of downsampling points in ADN should be the same or larger than that of CAAN due to the reasons described below. \begin{table}[t] \captionsetup{labelfont=bf} \caption{Structures of CAAN: MobileNet-based network and ResNet-based network. The convolution layers are denoted as $\{$conv2d, $\langle$receptive field$\rangle$x$\langle$receptive field$\rangle$, $\langle$number of channels$\rangle$$\}$. ''bneck'' denotes bottleneck structure; see \cite{howard2019searching}. } \label{tab:CAAN} \centering \scalebox{0.8}[0.8]{ \renewcommand{\arraystretch}{1.5} \begin{tabular}{c|c|c} \hline block name & \begin{tabular}{c} ResNet-based \\ CAAN \end{tabular}& \begin{tabular}{c} MobileNet-like \\ CAAN \end{tabular} \\ \hline \hline \multicolumn{3}{c} { input (256$\times$256$\times$1 Anomaly map) } \\ \hline block 1 & conv2d, 7x7, 64 & conv2d, 3x3, 16 \\ \hline \multicolumn{3}{c} { Attention Output Point 1 } \\ \hline block 2 & \begin{tabular}{l} conv2d, 3x3, 64 \\[-5pt] conv2d, 3x3, 64 \end{tabular} & bneck, 3x3, 16 \\ \hline \multicolumn{3}{c} { Attention Output Point 2 } \\ \hline block 3 & \begin{tabular}{l} conv2d, 3x3, 128 \\[-5pt] conv2d, 3x3, 128 \end{tabular} & [bneck, 3x3, 24] $\times$ 2 \\ \hline \multicolumn{3}{c} { Attention Output Point 3 } \\ \hline block 4 & \begin{tabular}{l} conv2d, 3x3, 256 \\[-5pt] conv2d, 3x3, 256 \end{tabular} & \begin{tabular}{l} [bneck, 5x5, 40] $\times$ 3 \\[-5pt] {[bneck, 5x5, 48]} $\times$ 2 \end{tabular} \\ \hline \multicolumn{3}{c} { Attention Output Point 4 } \\ \hline block 5 & \begin{tabular}{l} conv2d, 3x3, 512 \\[-5pt] conv2d, 3x3, 512 \end{tabular} & [bneck, 5x5, 96]$\times$3 \\ \hline \multicolumn{3}{c} { Attention Output Point 5 } \\ \hline block 6 & \begin{tabular}{c} average pool \\[-5pt] 2-d fc \\[-6pt] sigmoid \end{tabular} & \begin{tabular}{c} conv2d, 1x1, 576 \\ [-5pt] average pool \\[-5pt] conv2d, 1x1, 1280 \\[-5pt] conv2d, 1x1, 2 \\[-5pt] sigmoid \end{tabular} \\ \hline Params & 4.491M & 3.042M \\ \hline \end{tabular} \renewcommand{\arraystretch}{1} } \end{table} \subsection{3-4. The overall structure of LEA-Net} In Fig.~\ref{fig:AttentionMechanism}, we illustrate the overall structure of LEA-Net. As shown in Fig.~\ref{fig:AttentionMechanism}, CAAN has five feature extraction blocks. In other words, CAAN has five alternatives for outputting attention maps for layer-wise visual attention. Simultaneously, ADN can have attention points up to five. In this study, the attention point in ADN is limited to one to avoid the performance deterioration of ADN. In the training process, both CAAN and ADN are optimized by passing through the gradients of the CAAN and ADN network during back propagation. Let us denote the $i$th original input image by ${\mathbf x}_{i} \in \mathbb{R}^{H \times W \times 3}$. Let ${\mathbf x}^{Att}_{i} \in \mathbb{R}^{H \times W}$ be the $i$th color anomaly map. Also, let $y_{i}\in \left \{0, 1\right \} $ be a corresponding ground-truth label. Further, let $L_{Att}$ and $L_{AD}$ be loss functions for CAAN and for ADN, respectively. The loss function for the entire classification network can be expressed as a sum of the two loss functions as: % \begin{eqnarray} \label{eq:Loss} L &=& L_{Att}+L_{AD} \nonumber \\ &=& BCE(g({\mathbf{x}_i^{Att}}),y_{i})+BCE(f({\mathbf{x}_i}),y_{i}). \end{eqnarray} % Here, $g(\cdot)$ and $f(\cdot)$ denote the output of CAAN and that of ADN, respectively. Also, $BCE(\cdot)$ denotes the binary crossentropy. We designed the loss function expecting that CAAN modifies attention maps more effectively during training likewise ABN. \subsection{3-5. Attention Mechanism} Let us denote the $p$-th attention point in ADN by \\ $A_p~(p \in \{1,2,3,4,5\})$. Also, let $M_p~\in~\mathbb{R}^{H_p \times W_p}$ be the attention map at $A_p$. The concept of layer-wise external attention is illustrated in the lower half of Fig.~\ref{fig:AttentionMechanism}. Let $g_{p}(\mathbf{x}^{Att}_i) \in \mathbb{R}^{H_p \times W_p \times C_{p}}$ be the feature tensor at attention point $p$ in CAAN for input image $\mathbf{x}^{Att}_i$. Then, $M_p$ is generated by % \begin{equation} \label{eq:AttentionMap} M_p = \sigma(\phi(g_p(\mathbf{x}^{Att}_i))), \end{equation} % where $\phi(\cdot)$ denotes channel-wise average pooling on the extracted features. Also, $\sigma(\cdot)$ denotes a sigmoid function. By a channel-wise average pooling on the extracted features, we obtain the single-channel feature map $\phi_(g_{p}(\mathbf{x}^{Att}_i)) \in \mathbb{R}^{H_p\times W_p}$. We adopted channel-wise average pooling rather than a $1 \times 1$ convolution layer, expecting the effect reported in~\cite{Woo2018}. A sigmoid layer $\sigma(\cdot)$ normalizes the feature map $\phi(g_{p}(\mathbf{x}^{Att}_i))$ within a range of $[0, 1]$. It was reported that the normalization of the attention map is effective to highlight informative regions effectively~\cite{Wang2017}. In addition, the sigmoid function prevents ADN features after attention from the reversal of importance by multiplying negative values. Then, we obtain the attention map $M_{p}(\mathbf{x}_{i}^{Att}) \in \mathbb{R}^{H_p \times W_p}$. The role of the attention mechanism is to highlight the informative regions on feature maps, rather than erasing other regions~\cite{Wang2017}. To reduce the risk that an informative region is erased by attention maps, we incorporate the attention map into ADN as follows: % \begin{equation} \label{eq:AttentionMechanism} \hat{f_p}(\mathbf{x}_{i}) = (1\oplus M_p) \otimes f_p(\mathbf{x}_{i}), \end{equation} % where $\oplus$ denotes element-wise sum, $\otimes$ denotes element-wise product, and $\hat{f_{p}}(\cdot)$ is the updated feature tensor at point $p$ in ADN after the layer-wise external attention. Our attention strategy described in Eq.~\ref{eq:AttentionMechanism} is also intended to avoid the Dying Relu Problem~\cite{Lu_2020}. The problem is that many parameters with negative values become zero when they pass through the Relu function, which will cause the vanishing gradient problem. In most cases, CAAN and ADN have significantly different feature maps. In addition, as the layers get deeper, the feature maps typically tend to be sparser. If such sparse features are simply multiplied at attention points, the performance of ADN will degrade seriously. This is the other reason why we adopt the attention strategy in Eq.~\ref{eq:AttentionMechanism} rather than simply multiplying the attention map. \section{4. Experiment} In this section, we evaluate the performance of LEA-Net using several datasets for image anomaly detections. Our experiments involve three main parts. In the first part, we verify the effect of the layer-wise external attention for boosting the performance of existing image classifiers using four real-world datasets. In the second part, we examine the performance of LEA-Net on more imbalanced settings. Finally, we attempt to visualize feature maps at all attention points before and after the layer-wise external attention to understand intuitively the effects of our attention mechanism. \begin{figure*}[t \hspace{-2.5em} \centering \captionsetup{justification=raggedright, singlelinecheck=off, labelfont=bf} \includegraphics[width=0.8\hsize]{figure/Dataset_ver3.pdf} \caption{Examples of datasets. For each dataset, the original and colored image and the anomaly map calculated from the two images are shown for Positive and Negative. } \label{fig:Dataset} \end{figure*} \subsection{4-1. Datasets} Datasets used here are shown in Fig.~\ref{fig:Dataset}. We performed the experiment for image anomaly detection using DR2 \cite{Pires2016}, PlantVillage \cite{Hughes_2016}, MVTec \cite{Bergmann_2019}, and Cloud \cite{cloud} datasets. DR2 contains $435$ publicly available retina images with sizes of $857 \time 569$ pixels. It consists of normal (negative) and Diabetic Retinopathy (positive) instances. PlantVillage contains images of healthy and diseased leaves of several plants. Among them, we used \textit{Potato} dataset here. MVTec AD contains defect-free and anomalous images of various objects and texture categories. From this dataset, we used \textit{Leather} and \textit{Wood}, whose anomalies are strongly reflected in color. Cloud dataset contains images without clouds (negative) and with clouds (positive). The lowest panels in Fig.~\ref{fig:Dataset} represent anomaly maps. We see that anomalous regions in the Positive images were failed to reconstruct and highlighted in the color anomaly maps. All images were resized to $256 \times 256$ pixels before experiments. To evaluate the performance on such practical dataset, we randomly extracted images from each dataset to construct imbalanced datasets. The details of datasets are shown in Table~\ref{tab:Dataset}. \begin{table}[t] \captionsetup{labelfont=bf} \caption{Imbalanced experimental datasets reconstructed by random sampling.} \label{tab:Dataset} \scalebox{1}[1]{ \renewcommand{\arraystretch}{1.2} \hspace{-1.0em} \begin{tabular}{c|c c c c} Dataset Name & Positive & Negative & \begin{tabular}{c} P to N \\[-0.5em] Ratio \end{tabular} & Total \\ \hline Retina \scriptsize{(DR2)} & 98 & 337 & 0.291 & 435 \\ Potato \scriptsize{(PlantVillage)} & 50 & 152 & 0.329 & 202 \\ Cloud & 100 & 300 & 0.333 & 400 \\ Leather \scriptsize{(MVTec)} & 92 & 277 & 0.332 & 369 \\ Wood \scriptsize{(MVTec)} & 60 & 266 & 0.226 & 326 \\ \end{tabular} \renewcommand{\arraystretch}{1} } \end{table} \subsection{4-2. Experimental Setup} We briefly describe the experimental setup for training. Parameters of U-Net were optimized by Adam optimizer with a learning rate of $0.001$. Momentums were set to $\beta_1 = 0.9$ and $\beta_2 = 0.999$. The total number of iterations to update the parameters was $500$ epochs, and the batch size was set to $16$. To reduce the computational time, early stopping was used. In the anomaly detection experiment, we performed stratified five-fold cross-validation on each dataset without data augmentation. Parameters of ResNet18 were optimized by Adam optimizer with a learning rate of $0.0001$ and those of VGG16 were optimized by Adam optimizer with a learning rate of $0.00001$. The total number of iterations to update the parameters was set to $100$ epochs, and the batch size was $16$. All computations were performed on a GeForce RTX 2028 Ti GPU based on a system running Python $3.6.9$ and CUDA $10.0.130$. \subsection{4-3. Performance on Anomaly Detection} In LEA-Net, the attention map is incorporated into the intermediate layers of ADN via CAAN, which is the main idea of the layer-wise external attention mechanism. To evaluate the effectiveness of our attention mechanism, we compared the anomaly detection performance of LEA-Net with several settings: (i) baseline models (ResNet18, RestNet50, VGG16 and VGG19), (ii) ADN that receives anomaly map as inputs (\textit{Anomaly Map input}), (iii) ADN that receives 4-channel images consist of RGB images and anomaly maps as inputs (\textit{4ch input}), (iv) ADN that receives attention maps generated from RGB images and anomaly maps according to Eq.~\ref{eq:AttentionMechanism} as inputs~(\textit{Attentioned input}), (v) ADN with the layer-wise external attention at the attention point without CAAN (\textit{Direct Attention}). The averages of $F_1$ scores with a standard deviation in each experiment are shown in Table~\ref{tab:Performance}. The best and second-best performances are emphasized by bold type. The values given in parentheses indicate attention point of the best $F_1$ score. As mentioned above, the layer-wise external attention was applied at only one point in each experiment although the ADN has five attention points. For $F_1$ scores of models with the layer-wise external attention, we described the result of the best attention point score. The results in Table~\ref{tab:Performance} clearly show that the layer-wise external attention mechanism consistently increased the $F_1$ scores. In most of the cases, the layer-wise external attention with CAAN demonstrated better performance compared to that without CAAN. Surprisingly, for \textit{Potato} dataset, the layer-wise external attention increased the $F_1$ score of ResNet18 by $0.304$. However, the performances were comparatively low in cases where the anomaly map was directly incorporated into ADN. Interestingly, we must mention here that the most effective attention point disagrees depending on the models and datasets. \begin{table*}[t] \captionsetup{labelfont=bf} \caption{Comparison of $F_1$ scores on Retina, Potato, Cloud, Leather, Wood datasets} \label{tab:Performance} \scalebox{0.8}[0.8]{ \renewcommand{\arraystretch}{1.5} \begin{tabular}{l|c||c|c|c|c|c} ADN Model & Params & Retina & Potato & Cloud & Leather & Wood \\ \hline \small{ResNet18} & 11.2M & 0.642 $\pm$ 0.097 & 0.767 $\pm$ 0.164 & 0.642 $\pm$ 0.081 & 0.756 $\pm$ 0.147 & 0.560 $\pm$ 0.230 \\ \small{ResNet50} & 23.6M & 0.544 $\pm$ 0.155 & 0.425 $\pm$ 0.315 & 0.635 $\pm$ 0.147 & 0.631 $\pm$ 0.152 & 0.546 $\pm$ 0.146\\ \small{ResNet18 (AnomalyMap input)} & 11.2M & 0.412 $\pm$ 0.005 & 0.779 $\pm$ 0.181 & 0.476 $\pm$ 0.058 & 0.551 $\pm$ 0.300 & 0.329 $\pm$ 0.137 \\ \small{ResNet18 (4ch input)} & 11.2M & 0.443 $\pm$ 0.054 & 0.850 $\pm$ 0.102 & 0.529 $\pm$ 0.050 & \textbf{0.883 $\pm$ 0.066} & 0.495 $\pm$ 0.322\\ \small{ResNet18 (Attentioned input)} & 11.2M & 0.616 $\pm$ 0.108 & 0.823 $\pm$ 0.157 & 0.532 $\pm$ 0.050 & 0.752 $\pm$ 0.035 & 0.544 $\pm$ 0.22\\ \small{ResNet18 + Direct Attention} & 11.2M & \textbf{0.718 $\pm$ 0.047(3)} & 0.884 $\pm$ 0.045(4) & \textbf{0.670 $\pm$ 0.084(3)} & 0.823 $\pm$ 0.055(3) & \textbf{0.697 $\pm$ 0.061(4)}\\ \small{\textbf{ResNet18 + MobileNet-small CAAN}} & 13.5M & 0.707 $\pm$ 0.037(1) & \textbf{0.870 $\pm$ 0.094(4)} & \textbf{0.707 $\pm$ 0.131(2)} & 0.826 $\pm$ 0.062(1) & \textbf{0.719 $\pm$ 0.247(2)} \\ \small{\textbf{ResNet18 + ResNet-based CAAN}} & 16.1M & \textbf{0.737 $\pm$ 0.045(1)} & \textbf{0.948 $\pm$ 0.039(4)} & 0.664 $\pm$ 0.067(4) & \textbf{0.828 $\pm$ 0.052(4)} & 0.621 $\pm$ 0.142(1)\\ \hline \small{VGG16} & 165.7M & 0.709 $\pm$ 0.119 & 0.906 $\pm$ 0.061 & 0.575 $\pm$ 0.046 & 0.862 $\pm$ 0.089 & 0.652 $\pm$ 0.142\\ \small{VGG19} & 171.0M & 0.692 $\pm$ 0.068 & 0.941 $\pm$ 0.04 & \textbf{0.794 $\pm$ 0.041} & 0.758 $\pm$ 0.08 & 0.597 $\pm$ 0.338\\ \small{VGG16 (AnomalyMap input)} & 165.7M & 0.399 $\pm$ 0.012 & 0.899 $\pm$ 0.093 & 0.438 $\pm$ 0.023 & \textbf{0.907 $\pm$ 0.039} & 0.397 $\pm$ 0.111\\ \small{VGG16 (4ch input)} & 165.7M & 0.458 $\pm$ 0.031 & 0.823 $\pm$ 0.073 & 0.479 $\pm$ 0.092 & \textbf{0.925 $\pm$ 0.033} & 0.575 $\pm$ 0.042\\ \small{VGG16 (Attentioned input)} & 165.7M & 0.726 $\pm$ 0.056 & \textbf{0.947 $\pm$ 0.039} & 0.576 $\pm$ 0.119 & 0.877 $\pm$ 0.053 & 0.593 $\pm$ 0.269\\ \small{VGG16 + Direct Attention} & 165.7M & \textbf{0.754 $\pm$ 0.060(5)} & 0.927 $\pm$ 0.030(1) & \textbf{0.596 $\pm$ 0.072(4)} & 0.877 $\pm$ 0.102(3) & \textbf{0.746 $\pm$ 0.069(3)}\\ \small{\textbf{VGG16 + MobileNet-small CAAN}} & 168.0M & 0.744 $\pm$ 0.068(3) & 0.938 $\pm$ 0.058(1) & 0.577 $\pm$ 0.069(3) & 0.867 $\pm$ 0.077(2) & 0.707 $\pm$ 0.074(4)\\ \small{\textbf{VGG16 + ResNet-based CAAN}} & 170.6M & \textbf{0.764 $\pm$ 0.069(5)} & \textbf{0.947 $\pm$ 0.064(1)} & 0.584 $\pm$ 0.076(5) & 0.899 $\pm$ 0.091(3) & \textbf{0.762 $\pm$ 0.035(5)}\\ \end{tabular} \renewcommand{\arraystretch}{1} } \end{table*} \subsection{4-4. Performance on more imbalanced data} We conducted anomaly detection tests using more imbalanced datasets. Four datasets from \textit{Retina}~(DR2) and \textit{Potato}~(PlantVillage) were constructed by changing a proportion of the number of anomalous instances to that of all instances. Then, the performance of LEA-Net was compared to that of baseline models (ResNet18 and VGG16). Settings of LEA-Net were as follows: (i) ResNet18-based ADN with MobileNet-small CAAN, (ii) ResNet18-based ADN with ResNet-based CAAN, (iii) VGG16-based ADN with MobileNet-small CAAN, (iv) VGG16-based ADN with ResNet-based CAAN. The resulting $F_1$ scores for each imbalanced dataset are described in Table~\ref{fig:ImbalancedResult}. The upper two panels show the results for \textit{Retina} and the lower two panels show those for \textit{Potato}. All $F_1$ scores were averaged over the five-fold cross-validation. Horizontal axes indicate a proportion of the number of anomalous instances to that of all instances. We see that $F_1$ scores of the ResNet18-based ADN with CAAN were significantly improved by the layer-wise external attention throughout all imbalanced settings. Also, $F_1$ scores of VGG16-based ADN with CAAN for \textit{Potato} were successfully improved in settings of $24.8\%$ and $12.4\%$. However, for $F_1$ scores of VGG16-based ADN with CAAN for \textit{Retina}, there was no meaningful improvement in all settings. \begin{figure}[htb \centering \captionsetup{justification=raggedright, singlelinecheck=off, labelfont=bf} \includegraphics[width=1.0\hsize]{figure/Imbalance_ver4-2.pdf} \caption{Performances on several imbalanced settings.} \label{fig:ImbalancedResult} \end{figure} \begin{figure*}[t \hspace{-1.5em} \captionsetup{justification=centering, labelfont=bf} \includegraphics[width=1.05\hsize]{figure/Visualization_ver5-2.pdf} \caption{Visualization of feature maps at attention points before and after the layer-wise external attention.} \label{fig:Visualization} \end{figure*} \subsection{4-5. Visualization of Attention Effects} Finally, we attempted to visualize how the layer-wise external attention induces attentions of ADN. Fig.\ref{fig:Visualization} displays feature maps output from intermediate layers in ResNet18-based ADN with ResNet-based CAAN before and after the layer-wise external attention for DR2 (\textit{Retina}) and PlantVillage (\textit{Potato}) datasets. We can see that anomalous regions were substantially highlighted by the layer-wise external attention throughout, from low-level to high-level features. \section{5. Conclusion} We proposed a Layer-wise External Attention Network (LEA-Net) for efficient image anomaly detection. LEA-Net has the layer-wise external attention mechanism to introduce prior knowledge about anomalies, represented as the anomaly map. Through experiments using real-world datasets including PlantVillage, MVTec AD, and Cloud datasets, we demonstrated that the proposed layer-wise external attention mechanism consistently boosts the anomaly detection performance of baseline models. We also confirmed that boosting abilities can remain even for significantly imbalanced datasets. For intuitive understanding of the proposed attention mechanism, we visualized and compared feature maps output from intermediate layers in Anomaly Detection Network~(ADN) before and after layer-wise external attention. The results displayed that attention maps generated from Color Anomaly Attention Network (CAAN) successfully highlighted anomalous regions. In this paper, we experimentally demonstrated that our new attention mechanism considerably boosts the anomaly detection performance of CNN-based image classifiers. We conclude that the layer-wise external attention is a promising technique for practical image anomaly detection. Moreover, we would like to emphasize that the technique is applicable not only for image anomaly detection, but also for various image recognition tasks. While, we found that the appropriate setting for successful boosting depends on the model and the dataset. Further studies focusing on theoretical aspects are expected to control adequately the layer-wise external attention. \section{Acknowledgments} This work was supported by JST, PRESTO Grant Number JPMJPR1875, Japan. \begin{quote} \begin{small} \section{Additional Experiment for Anomaly Detection} We performed additional experiments to evaluate the performance of LEA-Net using Hurricane \cite{satellite}, Concrete \cite{concreate}, PlantVillage \cite{Hughes_2016}, MVTec \cite{Bergmann_2019}, Cloud \cite{cloud} datasets. In the experiments, we additionally evaluate our layer-wise external attention on basic small CNN to see the effectiveness for various types of models. These experimental results were omitted from the main body of this paper due to the space constraints. \subsection{Additional Datasets} From PlantVillage, we used \textit{Grape} and \textit{Strawberry} datasets. From MVTec AD, we used \textit{Hazelnut}, \textit{Tile} and \textit{Carpet}, which contain color anomalous instances. Hurricane dataset contains normal (negative) images and anomalous (positive) images. The anomalous images show damages caused by hurricanes such as floods. Concrete dataset contains normal images without damage and anomalous images with cracks and splits. All images were resized to $256\times256$ pixels before experiments. The details of datasets are shown in Table~\ref{tab:Add_Dataset} and Fig.~\ref{fig:Add_Dataset}. In Fig.~\ref{fig:Add_Dataset}, we display illustrative examples of images and color anomaly maps for the dataset described above. The first rows show original color images. The second rows show reconstructed color images. The third rows show anomaly maps. Anomalous regions in the positive images are failed to be colored, and the regions are highlighted in the color anomaly maps. \subsection{Performance on Anomaly Detection} We show the comparison of anomaly detection performance between LEA-Net and other networks in Table~\ref{tab:Add_Performance_1}-\ref{tab:Add_Performance_4}. The performances are evaluated on the averages of $F_1$ scores with standard deviation. The best and second-best performances are emphasized by bold type. The values given in parentheses indicate attention point of the best $F_1$ score. Table~\ref{tab:Add_Performance_1} and Table~\ref{tab:Add_Performance_2} show that LEA-Nets (networks with MobileNet-small or ResNet-based CAAN) demonstrated the best or second-best performances in most of the cases. From these results, it is shown that the layer-wise external attention mechanism consistently boosted the anomaly detection performances of ResNet18 and VGG16. In addition, Table~\ref{tab:Add_Performance_3} and Table~\ref{tab:Add_Performance_4} clearly show that the layer-wise external attention mechanism works well for basic CNN. The $F_1$ scores of basic CNN based LEA-Net are the hignest or second highest for most of datasets. From this additional experimental results, we confirmed that the layer-wise external attention mechanism is applicable and effective for various types of models. \begin{table}[h] \centering \captionsetup{labelfont=bf} \caption{Additional experimental datasets.} \label{tab:Add_Dataset} \scalebox{0.8}[0.8]{ \renewcommand{\arraystretch}{1.2} \begin{tabular}{c|c c c c} Dataset Name & Positive & Negative & \begin{tabular}{c} P to N \\[-0.5em] Ratio \end{tabular} & Total \\ \hline \textit{Hurricane} & 100 & 300 & 0.333 & 400 \\ \textit{Concrete} & 100 & 300 & 0.333 & 400 \\ \textit{Grape} & 141 & 423 & 0.333 & 564 \\ \textit{Strawberry} & 152 & 456 & 0.333 & 608 \\ \textit{Tile} & 84 & 263 & 0.319 & 347 \\ \textit{Hazelnut} & 70 & 431 & 0.162 & 501 \\ \textit{Carpet} & 89 & 308 & 0.289 & 397 \\ \end{tabular} \renewcommand{\arraystretch}{1} } \end{table} \begin{figure}[htb] \centering \captionsetup{justification=raggedright, singlelinecheck=off, labelfont=bf} \includegraphics[width=0.45\textwidth]{figure/Additional_Dataset.pdf} \caption{Examples of color anomaly maps for additional datasets. For each dataset, the original and colored image and the anomaly map calculated from the two images are shown for Positive and Negative instances. Anomalous regions in the Positive images are failed to be colored, and the regions are highlighted in the color anomaly maps.} \label{fig:Add_Dataset} \end{figure} \begin{table*}[t] \centering \captionsetup{labelfont=bf} \caption{Comparison of $F_1$ scores on \textit{Hurricane}, \textit{Concrete}, \textit{Grape} and \textit{Strawberry} datasets.} \label{tab:Add_Performance_1} \scalebox{0.9}[0.9]{ \renewcommand{\arraystretch}{1.5} \begin{tabular}{l|c||c|c|c|c} Model & Params & Hurricane & Concrete & Grape & Strawberry \\ \hline \small{ResNet18} & 11.2M & \textbf{0.874 $\pm$ 0.075} & \textbf{0.974 $\pm$ 0.026} & 0.944 $\pm$ 0.044 & 0.840 $\pm$ 0.197 \\ \small{ResNet50} & 23.6M & 0.781 $\pm$ 0.125 & 0.921 $\pm$ 0.026 & 0.892 $\pm$ 0.062 & 0.820 $\pm$ 0.163 \\ \small{ResNet18 (AnomalyMap input)} & 11.2M & 0.403 $\pm$ 0.007 & 0.790 $\pm$ 0.218 & 0.856 $\pm$ 0.133 & 0.778 $\pm$ 0.226 \\ \small{ResNet18 (4ch input)} & 11.2M & 0.412 $\pm$ 0.013 & 0.946 $\pm$ 0.035 & 0.918 $\pm$ 0.027 & 0.866 $\pm$ 0.137 \\ \small{ResNet18 (Attentioned input)} & 11.2M & 0.500 $\pm$ 0.076 & 0.952 $\pm$ 0.029 & 0.895 $\pm$ 0.101 & 0.899 $\pm$ 0.095 \\ \small{ResNet18 + Direct Attention} & 11.2M & \textbf{0.870 $\pm$ 0.058(5)} & 0.963 $\pm$ 0.036(5) & 0.951 $\pm$ 0.046(1) & \textbf{0.986 $\pm$ 0.019(2)} \\ \small{\textbf{ResNet18 + MobileNet-small CAAN}} & 13.5M & 0.858 $\pm$ 0.076(3) & \textbf{0.979 $\pm$ 0.029(1)} & \textbf{0.978 $\pm$ 0.039(4)} & \textbf{0.987 $\pm$ 0.022(4)} \\ \small{\textbf{ResNet18 + ResNet-based CAAN}} & 16.1M & 0.866 $\pm$ 0.054(5) & 0.969 $\pm$ 0.022(3) & \textbf{0.961 $\pm$ 0.048(2)} & 0.957 $\pm$ 0.054(3) \\ \hline \small{VGG16} & 165.7M & 0.702 $\pm$ 0.092 & 0.959 $\pm$ 0.029 & 0.982 $\pm$ 0.026 & 0.959 $\pm$ 0.033 \\ \small{VGG19} & 171.0M & 0.655 $\pm$ 0.065 & \textbf{0.980 $\pm$ 0.011} & 0.971 $\pm$ 0.016 & 0.963 $\pm$ 0.03 \\ \small{VGG16 (AnomalyMap input)} & 165.7M & 0.400 $\pm$ 0.000 & 0.886 $\pm$ 0.028 & 0.902 $\pm$ 0.051 & 0.849 $\pm$ 0.109 \\ \small{VGG16 (4ch input)} & 165.7M & 0.441 $\pm$ 0.034 & \textbf{0.942 $\pm$ 0.036} & 0.956 $\pm$ 0.037 & 0.765 $\pm$ 0.158 \\ \small{VGG16 (Attentioned input)} & 165.7M & 0.584 $\pm$ 0.119 & 0.938 $\pm$ 0.047 & 0.978 $\pm$ 0.015 & 0.966 $\pm$ 0.025 \\ \small{VGG16 + Direct Attention} & 165.7M & \textbf{0.717 $\pm$ 0.029(5)} & 0.969 $\pm$ 0.021(5) & 0.982 $\pm$ 0.013(3) & 0.968 $\pm$ 0.039(1) \\ \small{\textbf{VGG16 + MobileNet-small CAAN}} & 168.0M & 0.715 $\pm$ 0.084(5) & 0.964 $\pm$ 0.023(1) & \textbf{0.986 $\pm$ 0.015(1)} & \textbf{0.969 $\pm$ 0.027(3)} \\ \small{\textbf{VGG16 + ResNet-based CAAN}} & 170.6M & \textbf{0.725 $\pm$ 0.045(4)} & 0.964 $\pm$ 0.023(3) & \textbf{0.986 $\pm$ 0.015(1)} & \textbf{0.973 $\pm$ 0.020(2)} \\ \end{tabular} \renewcommand{\arraystretch}{1} } \end{table*} \begin{table*}[t] \centering \captionsetup{labelfont=bf} \caption{Comparison of $F_1$ scores on \textit{Tile}, \textit{Hazelnut} and \textit{Carpet} datasets.} \label{tab:Add_Performance_2} \scalebox{0.9}[0.9]{ \renewcommand{\arraystretch}{1.5} \begin{tabular}{l|c||c|c|c} Model & Params & Tile & Hazelnut & Carpet \\ \hline \small{ResNet18} & 11.2M & 0.768 $\pm$ 0.120 & 0.866 $\pm$ 0.021 & 0.711 $\pm$ 0.061 \\ \small{ResNet50} & 23.6M & 0.601 $\pm$ 0.228 & 0.779 $\pm$ 0.302 & 0.524 $\pm$ 0.151 \\ \small{ResNet18 (AnomalyMap input)} & 11.2M & 0.381 $\pm$ 0.103 & 0.635 $\pm$ 0.06 & 0.392 $\pm$ 0.195 \\ \small{ResNet18 (4ch input)} & 11.2M & 0.669 $\pm$ 0.190 & 0.854 $\pm$ 0.193 & 0.686 $\pm$ 0.06 \\ \small{ResNet18 (Attentioned input)} & 11.2M & 0.750 $\pm$ 0.136 & 0.787 $\pm$ 0.304 & 0.735 $\pm$ 0.057 \\ \small{ResNet18 + Direct Attention} & 11.2M & \textbf{0.780 $\pm$ 0.077(5)} & \textbf{0.902 $\pm$ 0.075(1)} & \textbf{0.756 $\pm$ 0.045(3)} \\ \small{\textbf{ResNet18 + MobileNet-small CAAN}} & 13.5M & \textbf{0.789 $\pm$ 0.096(2)} & \textbf{0.919 $\pm$ 0.079(2)} & \textbf{0.788 $\pm$ 0.057(3)} \\ \small{\textbf{ResNet18 + ResNet-based CAAN}} & 16.1M & 0.776 $\pm$ 0.103(3) & 0.897 $\pm$ 0.040(5) & 0.724 $\pm$ 0.055(1) \\ \hline \small{VGG16} & 165.7M & 0.346 $\pm$ 0.094 & 0.857 $\pm$ 0.082 & 0.373 $\pm$ 0.349 \\ \small{VGG19} & 171.0M & \textbf{0.835 $\pm$ 0.091} & \textbf{0.903 $\pm$ 0.057} & \textbf{0.634 $\pm$ 0.304} \\ \small{VGG16 (AnomalyMap input)} & 165.7M & \textbf{0.599 $\pm$ 0.115} & 0.7 $\pm$ 0.092 & 0.423 $\pm$ 0.177 \\ \small{VGG16 (4ch input)} & 165.7M & 0.589 $\pm$ 0.103 & 0.78 $\pm$ 0.129 & \textbf{0.593 $\pm$ 0.137} \\ \small{VGG16 (Attentioned input)} & 165.7M & 0.512 $\pm$ 0.134 & 0.791 $\pm$ 0.074 & 0.252 $\pm$ 0.141 \\ \small{VGG16 + Direct Attention} & 165.7M & 0.399 $\pm$ 0.103(2) & \textbf{0.842 $\pm$ 0.068(3)} & 0.479 $\pm$ 0.108(3) \\ \small{\textbf{VGG16 + MobileNet-small CAAN}} & 168.0M & 0.432 $\pm$ 0.177(2) & 0.828 $\pm$ 0.066(4) & 0.55 $\pm$ 0.186(4) \\ \small{\textbf{VGG16 + ResNet-based CAAN}} & 170.6M & 0.525 $\pm$ 0.128(1) & 0.82 $\pm$ 0.057(1) & 0.484 $\pm$ 0.247(4) \\ \end{tabular} \renewcommand{\arraystretch}{1} } \end{table*} \begin{table*}[t] \captionsetup{labelfont=bf} \caption{Comparison of $F_1$ scores on \textit{Retina}, \textit{Potato}, \textit{Cloud} and \textit{Leather} datasets.} \label{tab:Add_Performance_3} \scalebox{0.9}[0.9]{ \renewcommand{\arraystretch}{1.5} \begin{tabular}{l|c||c|c|c|c} Model & Params & Retina & Potato & Cloud & Leather \\ \hline \small{basic CNN} & 4.0M & 0.621 $\pm$ 0.027 & 0.868 $\pm$ 0.066 & 0.276 $\pm$ 0.131 & 0.54 $\pm$ 0.094 \\ \small{basic CNN (AnomalyMap input)} & 4.0M & 0.417 $\pm$ 0.036 & 0.772 $\pm$ 0.018 & \textbf{0.475 $\pm$ 0.056} & 0.45 $\pm$ 0.191\\ \small{basic CNN (4ch input)} & 4.0M & 0.483 $\pm$ 0.052 & 0.829 $\pm$ 0.064 & \textbf{0.421 $\pm$ 0.057} & \textbf{0.613 $\pm$ 0.111} \\ \small{basic CNN (Attentioned input)} & 4.0M & 0.63 $\pm$ 0.049 & 0.858 $\pm$ 0.058 & 0.383 $\pm$ 0.109 & 0.459 $\pm$ 0.087 \\ \small{basic CNN + Direct Attention} & 4.0M & 0.65 $\pm$ 0.055(3) & 0.884 $\pm$ 0.051(5) & 0.332 $\pm$ 0.103(3) & \textbf{0.625 $\pm$ 0.11(5)}\\ \small{\textbf{basic CNN + MobileNet-small CAAN}} & 7.0M & \textbf{0.652 $\pm$ 0.015(5)} & \textbf{0.925 $\pm$ 0.033(5)} & 0.324 $\pm$ 0.09(4) & 0.606 $\pm$ 0.093(3)\\ \small{\textbf{basic CNN + ResNet-based CAAN}} & 8.9M & \textbf{0.654 $\pm$ 0.052(3)} & \textbf{0.907 $\pm$ 0.074(4)} & 0.337 $\pm$ 0.111(4) & 0.591 $\pm$ 0.134(4) \\ \end{tabular} \renewcommand{\arraystretch}{1} } \end{table*} \begin{table*}[t] \centering \captionsetup{labelfont=bf} \caption{Comparison of $F_1$ scores on \textit{Hurricane}, \textit{Concrete}, \textit{Grape} and \textit{Hazelnut} datasets.} \label{tab:Add_Performance_4} \scalebox{0.9}[0.9]{ \renewcommand{\arraystretch}{1.5} \begin{tabular}{l|c||c|c|c|c} Model & Params & Hurricane & Concrete & Grape & Hazelnut \\ \hline \small{basic CNN} & 4.0M & 0.835 $\pm$ 0.072 & 0.875 $\pm$ 0.071 & 0.955 $\pm$ 0.017 & 0.463 $\pm$ 0.172 \\ \small{basic CNN (AnomalyMap input)} & 4.0M & 0.401 $\pm$ 0.002 & 0.795 $\pm$ 0.109 & 0.868 $\pm$ 0.1 & 0.503 $\pm$ 0.183\\ \small{basic CNN (4ch input)} & 4.0M & 0.44 $\pm$ 0.024 & 0.888 $\pm$ 0.055 & 0.917 $\pm$ 0.074 & \textbf{0.683 $\pm$ 0.137}\\ \small{basic CNN (Attentioned input)} & 4.0M & 0.601 $\pm$ 0.18 & 0.882 $\pm$ 0.057 & 0.941 $\pm$ 0.03 & 0.377 $\pm$ 0.231\\ \small{basic CNN + Direct Attention} & 4.0M & \textbf{0.848 $\pm$ 0.072(3)} & 0.905 $\pm$ 0.049(3) & \textbf{0.96 $\pm$ 0.024(3)} & 0.465 $\pm$ 0.151(4)\\ \small{\textbf{basic CNN + MobileNet-small CAAN}} & 7.0M & 0.847 $\pm$ 0.089(4) & \textbf{0.918 $\pm$ 0.062(5)} & 0.956 $\pm$ 0.017(2) & 0.462 $\pm$ 0.166(4)\\ \small{\textbf{basic CNN + ResNet-based CAAN}} & 8.9M & \textbf{0.863 $\pm$ 0.101(2)} & \textbf{0.924 $\pm$ 0.051(5)} & \textbf{0.959 $\pm$ 0.029(4)} & \textbf{0.545 $\pm$ 0.261(5)}\\ \end{tabular} \renewcommand{\arraystretch}{1} } \end{table*} \newpage \section{U-Net Architecture} In Table ~\ref{tab:Unet}, we describe the architecture of U-Net that was used in the color anomaly map generation step. The sizes of input images are $256 \times 256$ pixels, and there are eight downsampling points. Except for the first and the last convolutional and deconvolutional layers, batch normalization layers are followed by the convolutional and the deconvolutional layers. \begin{table*}[ht] \centering \captionsetup{labelfont=bf} \caption{The U-Net architecture used in the present study. Conv2D denotes a 2D convolutional layer and BN denotes a batch normalization. All alpha values of LeakyRelu are $0.2$.} \renewcommand{\arraystretch}{1.2} \label{tab:Unet} \begin{tabular}{r r|c c c c c} ID & Layer Type & Output dim & Kernel & Stride & Filters & Activation \\ \hline 1 & Input & 256 $\times$ 256 & - & - & - & - \\ 2 & Conv2D & 128 $\times$ 128 & 4 & 2 & 64 & LeakyRelu \\ 3 & Conv2D $\rightarrow$ BN & 64 $\times$ 64 & 4 & 2 & 128 & LeakyRelu \\ 4 & Conv2D $\rightarrow$ BN & 32 $\times$ 32 & 4 & 2 & 256 & LeakyRelu \\ 5 & Conv2D $\rightarrow$ BN & 16 $\times$ 16 & 4 & 2 & 512 & LeakyRelu \\ 6 & Conv2D $\rightarrow$ BN & 8 $\times$ 8 & 4 & 2 & 512 & LeakyRelu \\ 7 & Conv2D $\rightarrow$ BN & 4 $\times$ 4 & 4 & 2 & 512 & LeakyRelu \\ 8 & Conv2D $\rightarrow$ BN & 2 $\times$ 2 & 4 & 2 & 512 & LeakyRelu \\ 9 & Conv2D $\rightarrow$ BN & 1 $\times$ 1 & 4 & 2 & 512 & LeakyRelu \\ 10 & Conv2DTranspose$\rightarrow$ BN & 2 $\times$ 2 & 2 & 2 & 512 & Relu \\ 11 & Concat(8, 10) & 2 $\times$ 2 & - & - & 1024 & - \\ 12 & Conv2DTranspose$\rightarrow$ BN & 4 $\times$ 4 & 2 & 2 & 512 & Relu \\ 13 & Concat(7, 12) & 4 $\times$ 4 & - & - & 1024 & - \\ 14 & Conv2DTranspose$\rightarrow$ BN & 8 $\times$ 8 & 2 & 2 & 512 & Relu \\ 15 & Concat(6, 14) & 8 $\times$ 8 & - & - & 1024 & - \\ 16 & Conv2DTranspose$\rightarrow$ BN & 16 $\times$ 16 & 2 & 2 & 512 & Relu \\ 17 & Concat(5, 16) & 16 $\times$ 16 & - & - & 1024 & - \\ 18 & Conv2DTranspose$\rightarrow$ BN & 32 $\times$ 32 & 2 & 2 & 256 & Relu \\ 19 & Concat(4, 18) & 32 $\times$ 32 & - & - & 512 & - \\ 20 & Conv2DTranspose$\rightarrow$ BN & 64 $\times$ 64 & 2 & 2 & 128 & Relu \\ 21 & Concat(3, 20) & 64 $\times$ 64 & - & - & 256 & - \\ 22 & Conv2DTranspose$\rightarrow$ BN & 128 $\times$ 128 & 2 & 2 & 64 & Relu \\ 23 & Concat(2, 22) & 128 $\times$ 128 & - & - & 128 & - \\ 24 & Conv2DTranspose & 256 $\times$ 256 & 2 & 2 & 2 & sigmoid \\ \end{tabular} \renewcommand{\arraystretch}{1} \end{table*}
{'timestamp': '2021-09-14T02:21:52', 'yymm': '2109', 'arxiv_id': '2109.05493', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05493'}
arxiv
\section{Introduction} \label{sec:intro} \noindent Many researches show that incorporating role-specific language style makes a dialogue system more human-like and attractive~\shortcite{li2016persona}. As shown in Figure~\ref{fig:application}, in stylistic dialogue generation, the responses are expected to be not only relevant to the context, but also consistent with the desired style. Recently, on the basis of parallel data of an utterance and its stylized version, some studies show the effect of stylistic dialogue generation to account for emotions \shortcite{DBLP:conf/aaai/ZhouHZZL18}, response attitudes \shortcite{niu2018polite}, personas \cite{li2016persona}, and gender identification. \shortcite{IGRL,su2021prototype}. \begin{figure} \centering \includegraphics[width=3in]{styledchat.1.pdf} \vspace{-18pt} \caption{Responses of our chitchat dialogue systems with different character settings. \label{fig:application} \vspace{-6pt} \end{figure} Despite their success, previous studies are generally conducted in a fully supervised setting requiring stylistic dialogue corpus. However, it is expensive and not always feasible to create such a corpus, due to the lack of parallel data which consists of many triplets in \{style, context, response\} format. For a target style, previous work either looks for specific data sources such as movie transcripts~\shortcite{jena2017enterprise}, or recruits human crowd-workers to create corpora~\shortcite{zhang2018personalizing}. On the other hand, although most state-of-the-art business chatbots are built upon information retrieval technology, there isn't any practical way to train a stylistic retrieval-based dialogue agent. The only way to prevent the dialogue agent from contradicting its desired style is to carefully annotate all the corpus and deliberately filter out those contradicted pairs, which is expensive and inefficient. In this paper, we present a light-weight approach that enables a \textit{generic} retrieval-based dialogue system (which does not embed any persona) to mimic the language style of a specific role. Our framework only requires minimum human inputs (e.g., 500 keywords) for each style, and does not need any paralleled data. Instead of building an entirely new dialogue system for each style from scratch, our framework functions as a ``patch'' to stylize a generic retrieval-based dialogue system. The main idea is to rewrite a generic dialogue repository into a stylistic one. Specifically, we consider that a target style is represented by a set of jargon phrases (words that are frequently used by a particular group), and propose a jargon-based rewriting schema to tint the responses in dialogue repository with the desired style. One problem in this rewriting schema is that the jargon in the rewritten stylistic responses may have never occurred in the original repository, and the re-ranking model trained on a generic repository may not understand them. To alleviate this problem, we further propose an alignment process to align each stylized response to an internal response that substitute the jargon phrases with synonyms in plain language. In the re-ranking process the model computes matching degrees based on these internal responses and then the aligned stylized responses are proposed as the final output. To evaluate our framework, we implement five dialogue agents with distinct personas and styles -- trendy teenagers who prefer informal expression and slang, computer junkies who adopt many technical terms in their language, physics fans who frequently use physics jargon, Pok\'emon fans who like using game jargon, and martial arts fans who frequently mention tricks or characters in martial arts novels. The stylistic dialogues are evaluated by both human annotators and automatic metrics. Extensive experiments show that our system properly balances the trade-off between relevance and style intensity, and yields responses with better comprehensive performance. Online A/B test indicates that our implemented chatbot with the trendy teenager character setting improves users engagement. This paper has three main contributions: \begin{enumerate} \item We endow the capability of responding in specific language style to retrieval-based dialogue systems. More importantly, this method can be used to patch any generic dialogue systems for various personas, without any extra fine-tuning or re-training of dialogue models. \item Our method gets rid of the dependency of paralleled data. Instead we only need a small set of jargon phrases and synonyms to rewrite the dialogue repository. \item Offline experimental results and online A/B test show the superiority of our approach, as well as the effect of stylistic response on user engagement. \end{enumerate} In the remaining part, we review related work. Then we describe our approach in details. Experimental results of both offline evaluation and online A/B test are presented finally. \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figure_2.pdf} \small \vspace{-6pt} \caption{Framework of a generic dialogue system and our stylized dialogue system.} \label{fig:framework} \end{figure*} \section{Related Work} \label{sec:related-work} \subsection{Retrieval-based Dialogue Systems} Recently there has been growing interest in building intelligent chatbots to complete tasks or chitchat. This paper focuses on retrieval-based dialogue system that first recall several response candidates from dialogue corpus via lexical-similarity between context, and then learns a semantic matching function between the conversation context and response candidates for response selection~\shortcite{yan2016learning,wu2017sequential,zhou2018multi,zhang2018modeling,tao2019multi} Such systems generally produce more fluent and diverse responses and are widely used in commercial chatbots~\cite{shum2018eliza}. \subsection{Persona-based Dialogue System} \citeyear{li2016persona} introduce persona-based dialogue models which capture speaker's role and represent it as distributed embeddings. Approaches have been proposed to learn a persona model from user profiles~\shortcite{zhang2018personalizing,luo2019learning} and personalized dialogue~\shortcite{herzig2017neural,zhang2019neural,madotto2019personalizing,song2020generate,song2021bob}. However, most persona-based models focus on the consistency of dialogue with the persona, but do not address the language style problem, which is an important aspect of persona-based dialogue.. Some recent studies focus on specific language styles. \citeyear{jena2017enterprise} introduce a Star Trek chatbot that imitates the speaking style of characters in the show. The chatbot is composed of two models that handle Star Trek style input and everyday conversation separately. \citeyear{niu2018polite} propose a set of models for generating polite dialogues. The models are guided by a politeness classifier in generating responses. \citeyear{su2021prototype} first extract a non-stylistic prototype from a generic dialogue system and then generate stylistic response via GPT2. \citeyear{zheng2020stylized} and \citeyear{zhuneural} attempt to using monolingual stylistic data to increase the style intensity of dialogue response. We notice that all these studies focus on a single style, and are difficult to extend to other styles. Compared to these methods, our framework is retrieval-based, and can be used cover for a broader range of personas due to its light-weight nature. \subsection{Text Style Transfer} Style transfer of text is a related task of stylizing dialogue systems. The task is transferring a sentence to a specified language style, while keeping the content of the sentence unchanged. A representative approach is learning disentangled latent representations of content and style. \citeyear{shen2017style} propose a cross-aligned auto-encoder with shared content and separated style representations. \citeyear{hu2017toward} adversarially combine variational auto-encoder and style classifier. Several studies leverage adversarial networks with different discriminators and training objectives~\shortcite{fu2018style,yang2018unsupervised,john2019disentangled,liu2021learning,goyal2021multi}. Another approach separates content and style via explicit sequence editing. \citeyear{fu2019rethinking} show that style transfer can be largely achieved by lexical substitution. \citeyear{li2018delete} propose a ``delete, retrieve, and generate'' framework that replaces style-related words and re-generate the sentence for better fluency. Similar approaches based on pre-trained language model or reinforcement learning are also explored~\shortcite{xu2018unpaired,sudhakar2019transforming,wu2019hierarchical,krishna2020reformulating,li2020unsupervised}. Our approach to stylize dialogue is consistent with the above studies (e.g. with the observation of \citeyear{fu2019rethinking} on lexical substitution). However, we do not employ a heavy mechanism to implement the transfer but exploit a small set of style-related terms to generate stylized sentences. We compare with \cite{shen2017style} and \cite{li2018delete} in experiments. \begin{table} \centering \begin{tabular}{p{0.8in}p{0.98in}p{1in}} Style & Jargon phrase & Synonym \\ \hline \multirow{2}{*}{Trendy Teenager} & \chinese{极好的} (snatched) & really good \\ & \chinese{智商税} (stupid tax) & pay for ignorance \\ \hline \multirow{2}{*}{Computer} & access token & key \\ & transfer learning & learn by analogy \\ \hline \multirow{2}{*}{Physics} & polarization & single direction \\ & sonic boom & very fast\\ \hline \multirow{2}{*}{Pok\'emon} & fire blast & burn \\ & Squirtle & turtle \\ \hline \multirow{2}{*}{Martial Arts} & \chinese{裘千尺} \footnotemark & an antagonist \\ & (Qiu Chianchi) & \\ \end{tabular} \caption{Samples of annotated parallel phrases.} \label{tab:sample-align-phrase} \vspace{-12pt} \end{table} \section{Our Proposed Framework} \subsection{Main Idea} Our proposed framework is shown in Figure~\ref{fig:framework}. To construct a stylized retrieval-based dialogue system, our main idea is to rewrite the source corpus $\mathcal{X}$ to a stylized corpus $X^Y$. The rewriting is based on a jargon - synonym set that contains about 500 jargon phrases and their synonyms in plain language (annotated by human). The first step is \textbf{Response Rewriting} that transforms every response $r$ in $\mathcal{X}$ to a stylized response $r^Y$ with jargon phrases via a style transfer model. After response rewriting, two main challenges still remain: 1) The ranking model trained on a generic repository may not understand the stylized responses $r^Y$, and 2) the stylized responses $r^Y$ may be irrelevant to the original context $c$. To alleviate these problems, we further propose two modules, \textbf{Response Alignment} module and \textbf{Context Rewriting} module, respectively. The former attempts to align $r^Y$ to a synonymous response $r'$ in plain language through the jargon - synonym set, so that the reranking are based on $r'$ instead of the $r^Y$. For the latter, we rewrite the context of $c$ to $c'$ by adding some context words that are related to the jargon so that $c'$ is more relevant to the stylized response. For example, for the jargon ``Markov chain'', we rewrite its origin context \textit{``Isn't life hard for everyone?''} to \textit{``Isn't life hard for everyone? predict; history; trend; uncertain; short-term''}. After Rewriting and Alignment, we can “patch” a generic retrieval-based dialogue system to adapt new language styles. As shown in Figure~\ref{fig:framework}, after replacing the all context-response pairs $(c, r)$ in a generic conversation repository $\mathcal{X}$ to stylized pairs $(c', r')$, the dialogue system searches for stylized contexts $c'$ and selects a synonymous response $r_{i}^{'}$ as an intermediate output. Then, the corresponded stylized response $r_i^Y$ is used as the response of input conversation. \subsection{Jargon phrases \& synonyms} \label{sec:Jargon phrases} We collect a set of jargon phrases from topic-specific websites and ask human experts to annotate them with synonyms in plain language. For instance, for the trendy teenager persona, we collected a list of Internet slang words from Fanjian\footnote{http://www.fanjian.net/}, a website maintaining a large database of Chinese Internet slang. We took a slang word as a jargon phrase $s^Y$. For each slang word, three human annotators were asked to assign a synonymous phrase $s^X$ in plain language. The annotators reviewed and discussed each other's annotation until they reached an agreement. Insulting slang words were removed. Samples of the phrases are presented in Table \ref{tab:sample-align-phrase}. The synonym phrases mostly explain certain aspects of the jargon phrases in plain language. We collected on average 523 parallel jargon phrase - synonym pairs per style. \section{Approach} In this section, we introduce detailed procedures of \textbf{Response Rewriting}, \textbf{Response Alignment}, and \textbf{Context Rewriting}, given a set of jargon phrases and synonyms. The specified language style is implemented in the first step. The second step guarantees the synonymity of $r'$and $r^Y$. The third one fixes the relevance between $c'$ and $r'$. We further describe rewriting response and rewriting context in details. \subsection{Response Rewriting} \label{sec:main-corpus-response} In this section, we introduce detailed procedures of rewriting responses by jargon phrases. Given an original response $r$, the goal of rewriting is to obtain a fluent and stylized response $r^Y$. A trivial way to achieve the goal is letting $r^Y$ be a common sentence like ``I am multi-threaded'' for any $r$. To avoid this, we require that $r^Y$ has as many overlapping words with $r$ as possible so that it is more specific. We generate a number of candidates for $r^Y$, and then filter out ungrammatical ones by a fine-tuned BERT model. \subsubsection{Generating Candidate Response} \label{sec:main-corpus-response-candidate} Given a response $r = \{w_1, w_2, ..., w_n\}$, which is a sequence of words, we select a sub-sequence $s_{i,j} = \{w_i, w_{i+1}, ..., w_j\}$ and substitute it with a jargon phrase $s^Y$. The resulting response $r^Y = \{w_1, ..., w_{i-1}, s^Y, w_{j+1}, ..., w_n\}$ is proposed as a candidate for further filtering. This process is similar to that used in existing style transfer models~\shortcite{li2018delete,sudhakar2019transforming,wu2019mask}. These models substitute style-related words and keep others, so that the content is unchanged. To increase the coverage, we allow arbitrary words to be substituted. This relaxation yields $\mathcal{O}(n^2)$ possible substitutions, so we adopt the following constraints for pruning: \begin{itemize} \item \paragraph{Word constraint:} We only consider words and numbers for substitution. Punctuation marks are not substituted, because they play an important role in grammar. This constraint avoids generating grammatical errors by the change of punctuation. \item \paragraph{Length constraint:} We try to keep $s_{i,j}$ short, so that most words of $r$ are preserved. This choice is made in order to avoid altering too much the initial sentence. Specifically, we limit the length of $s_{i,j}$ to be less than 5 words. \item \paragraph{Context constraint:} We also require the sub-sequence $s_{i,j}$ to share the same preceding or succeeding words with a jargon phrase. For example, suppose we find sentences like ``... is fully multi-threaded ...'' in the stylized corpus $\mathcal{T}$. We may consider applying the substitution only if $s_{i,j}$ succeeds the words ``is fully''. This constraint helps filter out most of obviously ungrammatical candidates. \end{itemize} \subsubsection{Response Filtering} \label{sec:main-corpus-response-filter} We further filter stylized response candidates that are not fluent via a language model. Since a stylized response candidate is not an entirely new sentence, we only need to estimate the fluency of the substituted part. We start with the pre-trained BERT model~\shortcite{devlin2019BERT}, and fine-tune it with a non-conversational stylized corpus $\mathcal{T}$. We mask the jargon phrases in $\mathcal{T}$ and train the model to recover them. Then we use this model to predict the probability of $s^Y$ in a given $r^Y$: $p(s^Y|r^Y)$. The candidate responses with low $p(s^Y|r^Y)$ will be filtered. \subsection{Aligning Responses} After the \textbf{Response Rewriting} process, it is possible that the generated stylized response $r^Y$ is not synonymous to the original response $r$. Moreover, the re-ranking model in the generic dialogue system may not understand $r^Y$ as well. To alleviate these problems, we substitute stylized phrases in $r^Y$ with their synonyms in plain language. That is, for each $s^Y$ in $r^Y$, we substitute $s^Y$ with the synonymous $s^X$. The resulting synonymous response $r'$ is referred to as the modified response. Such direct substitution ensures the synonymity of $r'$ and $r^Y$. Note that $r'$ could be ungrammatical. This is acceptable because $r'$ is only used internally by the dialogue system to match with user input and is not shown to users. \subsection{Context Rewriting} \label{sec:main-corpus-context} Now we have pairs of synonymous response $r'$ and stylized response $r^Y$, and a remaining problem is that the $r'$ and $r^Y$ may be totally irrelevant to the original context $c$ after style transfer. So we attempt to modify $c$ to a more relevant one, $c'$, regarded as the stylized context. To obtain $c'$, we select keywords similar to the stylized phrase $s^Y$ to append to $c$. For example, given $s^y$=``being multi-threaded'', the stylized context $c'$ could be [$c$ + ``simultaneously'' + ``moreover'']. We considered several choices of the keywords, including frequently co-occurred words, nearest words in word embedding space, and simply $s^X$ itself. We found fastText embedding~\shortcite{bojanowski2017enriching} yields more reasonable keywords. We choose the top 5 words with the highest cosine similarity to the stylized phrase $s^Y$. \section{Evaluation} \label{sec:eval} We conducted both offline experiment and online A/B test to evaluate the performance of our framework. Each system is given an utterance in the testing set as input. The output response is evaluated in terms of its quality. \subsection{Dataset\footnote{All datasets will be released.}} \label{Sec:eval-dataset} To train a stylized dialogue system, our framework does not need paralleled data. Instead, we need a generic dialogue corpus $\mathcal{X}$, a stylized non-conversational corpus $\mathcal{T}$, and stylized jargon phrase - synonymous pairs. \paragraph{Source dialogue corpus:} We use the dialogue corpus collected by \shortcite{shang2015neural} from Sina Weibo, a popular twitter-like service in China. The contexts are extracted from posts. Comments on the posts are taken as responses. The corpus covers various topics from different users, so we consider it to be in a generic language style. We normalized the tokens and removed non-content words like ``retweeted from''. Contexts and responses were tokenized by Jieba\footnote{https://github.com/fxsjy/jieba} toolkit. We sampled 100 posts for testing, and took the remaining 4.4 million context-response pairs as the source dialogue corpus. \paragraph{Stylized non-conversational corpus:} Stylized non-conversational corpus are used for Response Filtering only. For each stylized phrase, we searched Sina Weibo and retrieved the first 500 matched posts. Comments were not retrieved. The posts are pre-processed similarly to the source dialogue corpus. We collected five corpora for the Internet slang style and the computer style. \paragraph{Jargon phrase - synonymous pairs:} As mentioned before, We collected on average 523 parallel jargon phrase - synonym pairs per style. \begin{table*} \centering \small \begingroup \setlength{\tabcolsep}{2.9pt} \begin{tabular}{l|R{0.12in}R{0.12in}R{0.12in}R{0.16in}|R{0.12in}R{0.12in}R{0.12in}R{0.16in}|R{0.12in}R{0.12in}R{0.12in}R{0.16in}|R{0.12in}R{0.12in}R{0.12in}R{0.16in}|R{0.12in}R{0.12in}R{0.12in}R{0.16in}||R{0.18in}R{0.19in}R{0.14in}R{0.14in}|R{0.2in}} & \multicolumn{4}{c|}{Trendy Teenager} & \multicolumn{4}{c|}{Computer} & \multicolumn{4}{c|}{Physics} & \multicolumn{4}{c|}{Pok\'emon} & \multicolumn{4}{c||}{Martial Arts} & \multicolumn{5}{c}{Average} \\ & R & S & D1 & D2 & R & S & D1 & D2 & R & S & D1 & D2 & R & S & D1 & D2 & R & S & D1 & D2 & R & S & D1 & D2 & RSA \\ \hline Generic & 1.3 & 0.7 & .51 & .84 & 1.6 & 0.1 & .51 & .84 & 1.6 & 0.0 & .51 & .84 & 1.4 & 0.0 & .51 & .84 & 1.3 & 0.1 & .51 & .84 & 1.45 & 0.17 & .51 & .84 & 0.81 \\ \hline MTask+MMI & \textbf{1.1} & 0.7 & .19 & .40 & 1.0 & 0.1 & .19 & .38 & \textbf{1.1} & 0.0 & .21 & .40 & \textbf{1.0} & 0.0 & .19 & .39 & 1.1 & 0.0 & .19 & .37 & \textbf{1.07} & 0.16 & .19 & .39 & 0.62\\ CAAE-direct & 0.6 & 1.6 & .28 & .48 & 0.1 & 1.7 & .19 & .41 & 0.2 & 1.0 & .25 & .53 & 0.4 & 1.5 & .27 & .51 & 0.3 & 1.1 & .25 & .48 & 0.32 & 1.36 & .25 & .48 & 0.84 \\ CAAE-patch & 0.8 & 1.0 & .32 & .51 & 0.2 & 0.5 & .15 & .30 & 0.3 & 0.1 & .21 & .43 & 0.4 & 0.3 & .27 & .50 & 0.4 & 0.3 & .21 & .50 & 0.42 & 0.45 & .23 & .45 & 0.44 \\ DelRetGen-direct & 0.9 & \textbf{1.7} & .41 & .77 & 0.3 & \textbf{1.9} & .38 & .74 & 0.5 & 1.2 & .47 & .80 & 0.7 & 1.6 & .45 & .77 & 0.7 & \textbf{1.3} & .43 & .76 & 0.62 & \textbf{1.53} & .43 & .77 & 1.08 \\ Ours-direct & \textbf{1.1} & 1.5 & \textbf{.55} & \textbf{.84} & \textbf{1.1} & 0.9 & \textbf{.55} & \textbf{.84} & 1.0 & 0.8 & \textbf{.56} & \textbf{.84} & \textbf{1.0} & 1.2 & \textbf{.57} & \textbf{.83} & \textbf{0.9} & 1.0 & \textbf{.56} & \textbf{.84} & 1.00 & 1.10 & \textbf{.56} & \textbf{.84} & 1.05 \\ Ours-patch & \textbf{1.1} & \textbf{1.7} & .50 & .81 & 0.7 & 1.8 & .47 & .81 & 0.9 & \textbf{1.3} & .49 & .83 & 0.9 & \textbf{1.7} & .50 & \textbf{.83} & 0.8 & 1.2 & .50 & \textbf{.84} & 0.86 & \textbf{1.53} & .49 & .82 & \textbf{1.20} \\ \end{tabular} \endgroup \caption{Evaluation results of stylized dialogue. R: relevance, S: style, D1: distinct-1, D2: distinct-2, *-m: simplified variant without modifying response or context} \label{tab:eval-dialogue} \vspace{-9pt} \end{table*} \subsection{Experiment Settings} \paragraph{Generic dialogue system:} We built a retrieval-based dialogue system as the start point for mimicking different styles. We use Elasticsearch~\shortcite{gormley2015elasticsearch} to build a conversation repository containing the source dialogue corpus $\mathcal{X}$. Given an input utterance, we retrieve the top 100 matched contexts and their paired responses. A pre-trained dialogue model selects a proper response as output. The dialogue model was trained with a different corpus other than the corpus $\mathcal{X}$ used in this paper. \paragraph{Our approach:} We ``patch'' the generic dialogue system with the proposed method. For each $(c, r)$ pair in $\mathcal{X}$, we try to rewrite it to obtain stylized responses. If the rewriting fails, we simply copy the pair, i.e., let $c'=c$ and $r^Y=r'=r$. For ablation study, we consider a simplified variant, where the generic dialogue system is not patched and its output response $r$ is directly rewritten as $r^Y$. We denote our approach and the simplified variant as \textbf{Ours-patch} and \textbf{Ours-direct}. \paragraph{Baselines:} We compare with a generation-based approach by \citeyear{luan2017multi}. It uses multi-task learning to personalize a dialogue model. We train the model with our dialogue corpus $\mathcal{X}$ and non-conversational corpus $\mathcal{T}$. We improve its diversity by interpolating the MMI model by \citeyear{li2016diversity}. We set its encoder and decoder to be 2-layer LSTMs with 500 hidden units. Its vocabulary (60k) covers words in $\mathcal{X}$ and $\mathcal{T}$. We refer to this approach as \textbf{MTask+MMI}. We also consider leveraging text style transfer models. Given an output response $r$ of the generic dialogue system, we use a style transfer model to transform $r$ to a stylized response. Two representative models are used, the cross-aligned auto-encoder by \citeyear{shen2017style} and the ``delete, retrieve, and generate'' model by \citeyear{li2018delete}. We denote the two approaches as \textbf{CAAE-direct} and \textbf{DelRetGen-direct}. In addition, we consider integrating the style transfer models into our framework. We replace the procedures of \textbf{Response Rewriting} with one of the style transfer models. We keep the remaining procedures and ``patch'' the generic dialogue system accordingly. This approach is denoted as \textbf{CAAE-patch}\footnote{We tried to optimize the original implementation of DelRetGen, but still can not rewrite the corpus in a reasonable time.}. \subsection{Metrics} We consider three criteria for response's quality: relevance, style degree, and content diversity. \paragraph{Relevance:} Relevance refers to the extent of a response being proper for an input utterance. We follow the same guideline as \citeyear{shang2015neural} to rate Relevance on a scale of 0 to 2. \paragraph{Style degree:} style degree refers to how likely the specified language style can be identified. We rate style degree on a scale of 0 to 2. \begin{itemize} \item \textbf{Strong style (2):} Obvious usage of words in the specified language style can be found. \item \textbf{Weak style (1):} Two cases are included: (a) Stylized words are used, but it is still similar to everyday conversation, e.g., ``What's the name of this \textbf{software}?'' (b) Common words are used, but they have special meaning for the target persona. For example, ``I have an \textbf{abstract} girlfriend'', where ``abstract'' has a specific meaning in programming. \item \textbf{No style (0):} The response is not fluent or does dot show any identifiable style. \end{itemize} \paragraph{Diversity:} Diversity of response is recognized as an important metric of dialogue systems~\shortcite{li2016diversity}. Dialogue systems with good diversity produce more interesting responses on various topics. We measure the diversity of responses by the number of distinct unigrams and bigrams divided by total number of words in the responses, i.e., Distinct-1 (D1) and Distinct-2 (D2). For each style, we obtained 700 responses from the 100 testing input utterances by the evaluated systems. An input utterance and a shuffled list of responses were presented to 3 annotators each time. The annotators were asked to rate each response according to the above guideline. To measure agreement, we use a generalized form of Scott's pi coefficient with linear weighting~\shortcite{gwet2014handbook}. The coefficients indicate fair agreement among ratings (0.37 and 0.44 for relevance; 0.56 and 0.79 for style degree). \begin{figure} \centering \small \begingroup \setlength{\tabcolsep}{3pt} \begin{tabular}{l|p{2.2in}} \multirow{2}{*}{User Query} & \chinese{好久没吃了,好想吃哇} \\ & Haven't eat it for a long time and really want to eat it. \\ \hline \multirow{2}{*}{Trendy Teenagers} & \chinese{好久没吃了啊,减肥\underline{不存在的},能不诱惑我吗?} \\ & Haven't eat it for a lone time. Losing weight is \textbf{non-existent}. Could you not tempt me? \\ \hline \multirow{2}{*}{Computer Junkies} & \chinese{想吃,\underline{贪婪算法}告诉我怎么吃吗?}\\ & Want to eat. Would \textbf{greedy algorithms} tell me how to eat? \\ \hline \multirow{2}{*}{Physics Fans} & \chinese{好饿啊。看到这汉堡就控制\underline{运动速度}。} \\ & So hungry. I have to control the \textbf{movement velocity} when I see this hamburger.\\ \hline \multirow{2}{*}{Pok\'emon Fans} & \chinese{哈哈,我爱\underline{舔舌}头吃!}\\ & Haha, I love eating by \textbf{lick}. \\ \hline \multirow{2}{*}{Martial Arts Fans} & \chinese{不是好久没吃过,\underline{苏荃}从来都没吃过…} \\ & Not for a long time, \textbf{Su Quan}\footnotemark has never eaten it. \\ \hline \end{tabular} \endgroup \caption{Sample responses by our approach.} \label{fig:sample-dialogue} \end{figure} \subsection{Evaluation Result} Table \ref{tab:eval-dialogue} shows evaluation results of stylized dialogue. The average of relevance and style degree ratings (denoted as RSA) is included for overall performance. The multi-task approach \textbf{MTask+MMI} does not produce stylized response as expected. We attribute it to the low overlap between the dialogue corpus and the target corpus. On average, only 81.4\% words of the target corpus (excluding stop words) appear in the vocabulary of dialogue corpus. The decoder fails to correlate non-overlapping words with the utterance's encoding, even after we extended its vocabulary. For CAAE-patch, its relevance increases after modifying context and response, but its style degree decreases dramatically. The average lengths of response are respectively 7.4 and 5.7 tokens for CAAE-direct and CAAE-patch. The root cause for this behavior is the low content diversity. The model tends to produce short and common responses. The dialogue model has to choose a ``safe'' but more relevant one, when no other relevant and informative response is available. Our simplified approach (Ours-direct) achieves a higher relevance and a lower style degree than our complete approach (ours-patch). Among the responses produced by the base system, the simplified approach fails to transfer any response for 25\% of queries, whereas ours-patch succeed to return at least one stylized responses for all queries. If we count the queries on which both approaches succeed, the relevance is 0.78 and 0.86, and the style degree is 1.43 and 1.52, for the simplified and the complete approaches. The diversity remains similar. This strongly supports our idea of distinguishing transferring style from keeping meaning unchanged does work well. In general, our complete approach (ours-patch) achieves the best overall performance in terms of RSA (t-tests with $p<10^{-4})$. Figure \ref{fig:sample-dialogue} illustrates our approach's responses. \footnotetext{A character in the novel series \textit{The Legend of Lu Xiaofeng}.} \begin{figure*}[h] \centering \includegraphics[width=6.25in]{triggerrate.1} \caption{Relevance and style degree change when we trigger different ratios of stylized responses} \label{fig:corpus-coverage} \end{figure*} \subsection{Changes with Trigger Rate} There is a trade-off between style degree and relevance. When we allow more stylized responses to return during conversations, a chatbot has more chance to exhibit as its style. However, there is a risk of lowering the relevance. Thus we use trigger rate as our variant and draw curves to show how relevance and style degree change at the same time. Based on our human labeled data, we simulate the results when different trigger rates are applied. For example, given a style, e.g., trendy teenagers, we set a threshold of the ensemble regression model output to filter out 90\% stylized responses. Thus we get 10\% trigger rate. Then we average the relevance score and the style degree as the corresponding evaluation results, e.g., 1.3 and 1.8 for the trendy teenager style. Similarly, we can filter out different ratio of stylized responses and get relevance and style degree scores at different trigger rate. Figure \ref{fig:corpus-coverage} shows us the curves for five styles. Take the trendy teenager style as an example. We observe that relevance remains high until about 15\% stylized responses are triggered. Then relevance goes down gradually. Even if all stylized responses are triggered, the relevance score is around 1.1, which means above fair. The style curve has a similar trend and the highest style degree is achieved when 20\% stylized responses are triggered. At that position, the relevance score is close to the maximum. Therefore, if our goal is to add some sense of style while keeping high relevance, we can choose the trigger rate of 20\%. It means that in almost one fifth turns users can get the stylized responses. That is a proper ratio as even a real trendy teenager does not show her/his style at all utterances. As Figure \ref{fig:corpus-coverage} shows, other styles have similar trends. We can find a proper trade-off between relevance and style degree in the curves. Our approach provides the flexibility to adjust a dialogue system according to the requirements of relevance and style degree. Some styles may be more difficult than some other styles to transfer. For example, the computer style has lowest relevance. Although the style degree is as high as 1.8, the relevance score is only 0.7 when the trigger rate is 10\%. This indicate that there is a big gap between the dialogue corpus and the stylized non-conversational corpus for the computer style. We guess that Weibo users like publishing content about their life, more than about techniques. \begin{table} \centering \begingroup \begin{tabular}{l|rrrr|r} & \multicolumn{1}{c}{F} & \multicolumn{1}{c}{S} & \multicolumn{1}{c}{D1} & \multicolumn{1}{c|}{D2} & \multicolumn{1}{c}{FSA} \\ \hline Source & 1.86 & 0.18 & .50 & .84 & 1.02 \\ \hline CAAE & 1.09 & 1.30 & .14 & .32 & 1.20 \\ DelRetGen & 1.01 & \textbf{1.41} & .41 & .77 & 1.21 \\ Ours & \textbf{1.43} & 1.19 & \textbf{.53} & \textbf{.84} & \textbf{1.31} \\ \end{tabular} \endgroup \caption{Evaluation results of transferred responses by single models. LM: Language Model} \label{tab:eval-corpus-single} \vspace{-9pt} \end{table} \subsection{Analysis of Style Transfer} In this study, we propose a first study to transfer a generic corpus to a stylized one. To evaluate how effective our transfer approach is, we further compare our style transfer model with two baseline methods, \textbf{CAAE} and \textbf{DelRetGen}. The evaluation metrics of style transfer are similar to that of stylized dialogue, and we only change the relevance metric to fluency metric. The fluency metric is rated on a scale of 0 to 2 that represent completely non-sense (0), understandable with minor errors (1), and fluent without error (2), respectively. Table \ref{tab:eval-corpus-single} shows the evaluation results. As expected, source responses are rated with perfect fluency and low style degree. They slightly exhibit Internet slang's style, because the dataset is collected from social media. On average, our approach achieves much better fluency and diversity but lower style degree compared to the two baselines. CAAE tends to generate ``safe'' sentences which make use of only a few target style phrases. To see this, we counted distinct target style phrases in transferred responses. The averaged counts are respectively 81, 172, and 181, for CAAE, DelRetGen, and our approach. DelRetGen improves diversity by involving more target style phrases than CAAE. However, its generation step tends to generate frequent words, limiting its overall diversity. In general, our approach outperforms the baselines on overall performance (FSA, D1, and D2; t-tests with $p < 10^{-4}$). \subsection{Online Evaluation} Compared to the generic dialogue system, our framework (as well as other stylized systems) produces more stylized but less relevant responses. We wonder if it has a positive or negative impact on user satisfaction. We conducted A/B test on a commercial social chatbot during one month. We select the trendy teenager style as our testbed. We randomly selected a fraction of users as the treatment group. They were served with the patched system. In case where the patched system fails to find a relevant response, we fallback to the generic system. Users in the control group were always served with the generic system. After the A/B test, we collected 12K conversations for the treatment group. A conversation is a sequence $\{(u_1, r_1), (u_2, r_2)\}$, where $u$ is a user utterance and $r$ is a response. We let $r_1$ be the patched system's response. The same number of conversations were sampled from the control group. We consider two automatic metrics to measure user satisfaction. The first metric is the sentiment of user's follow-up utterance. Positive sentiment reflects better user satisfaction. We use a sentiment classifier~\cite{zeng2019attitude} to classify the follow-up utterance $u_2$. The classifier outputs labels of $\{-1,0,1\}$, for negative, neutral, and positive sentiment. We take the average label for each group as \textit{Sentiment} in Table \ref{tab:online-eval}. The second metric is the fraction of overlapping words between $r_1$ and $u_2$ (See \textit{Automatic follow-up} in Table \ref{tab:online-eval}). It indicates whether the user is following $r_1$ or starting a new topic. We also use human annotation for evaluation. We sampled 250 conversations from each group, and asked 5 human annotators to rate user's satisfaction on a scale of -2 to +2: \begin{itemize} \item \textbf{Satisfied (+2)} The user is satisfied with the conversation and shows positive emotion. \item \textbf{Follow (+1)} The user understands the response $r_1$ and follows the topic. \item \textbf{Neutral (0)} The user keeps chatting but to ignore $r_1$. \item \textbf{Not-follow (-1)} The user is confused about $r_1$ or simply exits the chatbot. \item \textbf{Unsatisfied (-2)} The user is upset about the conversation and shows negative emotion. \end{itemize} Table \ref{tab:online-eval} shows the comparison in the above metrics. The patched system performs consistently better than the baseline system across all metrics. \begin{table} \centering \begin{tabular}{c|cc} & Treatment & Control \\ \hline Sentiment & \textbf{0.0250} & 0.0217 \\ Automatic follow-up & \textbf{0.1120} & 0.10445 \\ Human rating & \textbf{0.488} & 0.436 \\ \end{tabular} \caption{Evaluation result of online A/B test.} \label{tab:online-eval} \vspace{-6pt} \end{table} \section{Conclusion and Future Work} \label{sec:conclude} We propose a light-weight ``patching'' framework that enables a retrieval-based dialogue system to mimic the language style of a specified character setting. Our framework is flexible and less expensive to apply. Our approach is based on transforming a generic dialogue corpus to a stylized corpus. We design a series of strategies to implement the transformation. Five character settings are implemented. The experiments show that, with several hundreds of manually annotated jargon phrases, our approach is able to produce fluent, relevant, stylized, and diverse responses. A/B test indicates that users are more satisfied about the stylized system. As future work, we plan to improve relevance further and experiment with combining two or more styles in one chatbot. Theoretically our proposed framework is additive, because it provides a way to put different but non-contradictory personalities together. For example, a chatbot could be a computer junkie and a martial arts fan at the same time. When both character settings have response candidates, we can choose one of them by pre-defined priors. It would be interesting to implement such combination and test its effectiveness. \bibliographystyle{ACM-Reference-Format} \section{Introduction} \label{sec:intro} \noindent Many researches show that incorporating role-specific language style makes a dialogue system more human-like and attractive~\shortcite{li2016persona}. As shown in Figure~\ref{fig:application}, in stylistic dialogue generation, the responses are expected to be not only relevant to the context, but also consistent with the desired style. Recently, on the basis of parallel data of an utterance and its stylized version, some studies show the effect of stylistic dialogue generation to account for emotions \shortcite{DBLP:conf/aaai/ZhouHZZL18}, response attitudes \shortcite{niu2018polite}, personas \cite{li2016persona}, and gender identification. \shortcite{IGRL,su2021prototype}. \begin{figure} \centering \includegraphics[width=3in]{styledchat.1.pdf} \vspace{-18pt} \caption{Responses of our chitchat dialogue systems with different character settings. \label{fig:application} \vspace{-6pt} \end{figure} Despite their success, previous studies are generally conducted in a fully supervised setting requiring stylistic dialogue corpus. However, it is expensive and not always feasible to create such a corpus, due to the lack of parallel data which consists of many triplets in \{style, context, response\} format. For a target style, previous work either looks for specific data sources such as movie transcripts~\shortcite{jena2017enterprise}, or recruits human crowd-workers to create corpora~\shortcite{zhang2018personalizing}. On the other hand, although most state-of-the-art business chatbots are built upon information retrieval technology, there isn't any practical way to train a stylistic retrieval-based dialogue agent. The only way to prevent the dialogue agent from contradicting its desired style is to carefully annotate all the corpus and deliberately filter out those contradicted pairs, which is expensive and inefficient. In this paper, we present a light-weight approach that enables a \textit{generic} retrieval-based dialogue system (which does not embed any persona) to mimic the language style of a specific role. Our framework only requires minimum human inputs (e.g., 500 keywords) for each style, and does not need any paralleled data. Instead of building an entirely new dialogue system for each style from scratch, our framework functions as a ``patch'' to stylize a generic retrieval-based dialogue system. The main idea is to rewrite a generic dialogue repository into a stylistic one. Specifically, we consider that a target style is represented by a set of jargon phrases (words that are frequently used by a particular group), and propose a jargon-based rewriting schema to tint the responses in dialogue repository with the desired style. One problem in this rewriting schema is that the jargon in the rewritten stylistic responses may have never occurred in the original repository, and the re-ranking model trained on a generic repository may not understand them. To alleviate this problem, we further propose an alignment process to align each stylized response to an internal response that substitute the jargon phrases with synonyms in plain language. In the re-ranking process the model computes matching degrees based on these internal responses and then the aligned stylized responses are proposed as the final output. To evaluate our framework, we implement five dialogue agents with distinct personas and styles -- trendy teenagers who prefer informal expression and slang, computer junkies who adopt many technical terms in their language, physics fans who frequently use physics jargon, Pok\'emon fans who like using game jargon, and martial arts fans who frequently mention tricks or characters in martial arts novels. The stylistic dialogues are evaluated by both human annotators and automatic metrics. Extensive experiments show that our system properly balances the trade-off between relevance and style intensity, and yields responses with better comprehensive performance. Online A/B test indicates that our implemented chatbot with the trendy teenager character setting improves users engagement. This paper has three main contributions: \begin{enumerate} \item We endow the capability of responding in specific language style to retrieval-based dialogue systems. More importantly, this method can be used to patch any generic dialogue systems for various personas, without any extra fine-tuning or re-training of dialogue models. \item Our method gets rid of the dependency of paralleled data. Instead we only need a small set of jargon phrases and synonyms to rewrite the dialogue repository. \item Offline experimental results and online A/B test show the superiority of our approach, as well as the effect of stylistic response on user engagement. \end{enumerate} In the remaining part, we review related work. Then we describe our approach in details. Experimental results of both offline evaluation and online A/B test are presented finally. \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figure_2.pdf} \small \vspace{-6pt} \caption{Framework of a generic dialogue system and our stylized dialogue system.} \label{fig:framework} \end{figure*} \section{Related Work} \label{sec:related-work} \subsection{Retrieval-based Dialogue Systems} Recently there has been growing interest in building intelligent chatbots to complete tasks or chitchat. This paper focuses on retrieval-based dialogue system that first recall several response candidates from dialogue corpus via lexical-similarity between context, and then learns a semantic matching function between the conversation context and response candidates for response selection~\shortcite{yan2016learning,wu2017sequential,zhou2018multi,zhang2018modeling,tao2019multi} Such systems generally produce more fluent and diverse responses and are widely used in commercial chatbots~\cite{shum2018eliza}. \subsection{Persona-based Dialogue System} \citeyear{li2016persona} introduce persona-based dialogue models which capture speaker's role and represent it as distributed embeddings. Approaches have been proposed to learn a persona model from user profiles~\shortcite{zhang2018personalizing,luo2019learning} and personalized dialogue~\shortcite{herzig2017neural,zhang2019neural,madotto2019personalizing,song2020generate,song2021bob}. However, most persona-based models focus on the consistency of dialogue with the persona, but do not address the language style problem, which is an important aspect of persona-based dialogue.. Some recent studies focus on specific language styles. \citeyear{jena2017enterprise} introduce a Star Trek chatbot that imitates the speaking style of characters in the show. The chatbot is composed of two models that handle Star Trek style input and everyday conversation separately. \citeyear{niu2018polite} propose a set of models for generating polite dialogues. The models are guided by a politeness classifier in generating responses. \citeyear{su2021prototype} first extract a non-stylistic prototype from a generic dialogue system and then generate stylistic response via GPT2. \citeyear{zheng2020stylized} and \citeyear{zhuneural} attempt to using monolingual stylistic data to increase the style intensity of dialogue response. We notice that all these studies focus on a single style, and are difficult to extend to other styles. Compared to these methods, our framework is retrieval-based, and can be used cover for a broader range of personas due to its light-weight nature. \subsection{Text Style Transfer} Style transfer of text is a related task of stylizing dialogue systems. The task is transferring a sentence to a specified language style, while keeping the content of the sentence unchanged. A representative approach is learning disentangled latent representations of content and style. \citeyear{shen2017style} propose a cross-aligned auto-encoder with shared content and separated style representations. \citeyear{hu2017toward} adversarially combine variational auto-encoder and style classifier. Several studies leverage adversarial networks with different discriminators and training objectives~\shortcite{fu2018style,yang2018unsupervised,john2019disentangled,liu2021learning,goyal2021multi}. Another approach separates content and style via explicit sequence editing. \citeyear{fu2019rethinking} show that style transfer can be largely achieved by lexical substitution. \citeyear{li2018delete} propose a ``delete, retrieve, and generate'' framework that replaces style-related words and re-generate the sentence for better fluency. Similar approaches based on pre-trained language model or reinforcement learning are also explored~\shortcite{xu2018unpaired,sudhakar2019transforming,wu2019hierarchical,krishna2020reformulating,li2020unsupervised}. Our approach to stylize dialogue is consistent with the above studies (e.g. with the observation of \citeyear{fu2019rethinking} on lexical substitution). However, we do not employ a heavy mechanism to implement the transfer but exploit a small set of style-related terms to generate stylized sentences. We compare with \cite{shen2017style} and \cite{li2018delete} in experiments. \begin{table} \centering \begin{tabular}{p{0.8in}p{0.98in}p{1in}} Style & Jargon phrase & Synonym \\ \hline \multirow{2}{*}{Trendy Teenager} & \chinese{极好的} (snatched) & really good \\ & \chinese{智商税} (stupid tax) & pay for ignorance \\ \hline \multirow{2}{*}{Computer} & access token & key \\ & transfer learning & learn by analogy \\ \hline \multirow{2}{*}{Physics} & polarization & single direction \\ & sonic boom & very fast\\ \hline \multirow{2}{*}{Pok\'emon} & fire blast & burn \\ & Squirtle & turtle \\ \hline \multirow{2}{*}{Martial Arts} & \chinese{裘千尺} \footnotemark & an antagonist \\ & (Qiu Chianchi) & \\ \end{tabular} \caption{Samples of annotated parallel phrases.} \label{tab:sample-align-phrase} \vspace{-12pt} \end{table} \section{Our Proposed Framework} \subsection{Main Idea} Our proposed framework is shown in Figure~\ref{fig:framework}. To construct a stylized retrieval-based dialogue system, our main idea is to rewrite the source corpus $\mathcal{X}$ to a stylized corpus $X^Y$. The rewriting is based on a jargon - synonym set that contains about 500 jargon phrases and their synonyms in plain language (annotated by human). The first step is \textbf{Response Rewriting} that transforms every response $r$ in $\mathcal{X}$ to a stylized response $r^Y$ with jargon phrases via a style transfer model. After response rewriting, two main challenges still remain: 1) The ranking model trained on a generic repository may not understand the stylized responses $r^Y$, and 2) the stylized responses $r^Y$ may be irrelevant to the original context $c$. To alleviate these problems, we further propose two modules, \textbf{Response Alignment} module and \textbf{Context Rewriting} module, respectively. The former attempts to align $r^Y$ to a synonymous response $r'$ in plain language through the jargon - synonym set, so that the reranking are based on $r'$ instead of the $r^Y$. For the latter, we rewrite the context of $c$ to $c'$ by adding some context words that are related to the jargon so that $c'$ is more relevant to the stylized response. For example, for the jargon ``Markov chain'', we rewrite its origin context \textit{``Isn't life hard for everyone?''} to \textit{``Isn't life hard for everyone? predict; history; trend; uncertain; short-term''}. After Rewriting and Alignment, we can “patch” a generic retrieval-based dialogue system to adapt new language styles. As shown in Figure~\ref{fig:framework}, after replacing the all context-response pairs $(c, r)$ in a generic conversation repository $\mathcal{X}$ to stylized pairs $(c', r')$, the dialogue system searches for stylized contexts $c'$ and selects a synonymous response $r_{i}^{'}$ as an intermediate output. Then, the corresponded stylized response $r_i^Y$ is used as the response of input conversation. \subsection{Jargon phrases \& synonyms} \label{sec:Jargon phrases} We collect a set of jargon phrases from topic-specific websites and ask human experts to annotate them with synonyms in plain language. For instance, for the trendy teenager persona, we collected a list of Internet slang words from Fanjian\footnote{http://www.fanjian.net/}, a website maintaining a large database of Chinese Internet slang. We took a slang word as a jargon phrase $s^Y$. For each slang word, three human annotators were asked to assign a synonymous phrase $s^X$ in plain language. The annotators reviewed and discussed each other's annotation until they reached an agreement. Insulting slang words were removed. Samples of the phrases are presented in Table \ref{tab:sample-align-phrase}. The synonym phrases mostly explain certain aspects of the jargon phrases in plain language. We collected on average 523 parallel jargon phrase - synonym pairs per style. \section{Approach} In this section, we introduce detailed procedures of \textbf{Response Rewriting}, \textbf{Response Alignment}, and \textbf{Context Rewriting}, given a set of jargon phrases and synonyms. The specified language style is implemented in the first step. The second step guarantees the synonymity of $r'$and $r^Y$. The third one fixes the relevance between $c'$ and $r'$. We further describe rewriting response and rewriting context in details. \subsection{Response Rewriting} \label{sec:main-corpus-response} In this section, we introduce detailed procedures of rewriting responses by jargon phrases. Given an original response $r$, the goal of rewriting is to obtain a fluent and stylized response $r^Y$. A trivial way to achieve the goal is letting $r^Y$ be a common sentence like ``I am multi-threaded'' for any $r$. To avoid this, we require that $r^Y$ has as many overlapping words with $r$ as possible so that it is more specific. We generate a number of candidates for $r^Y$, and then filter out ungrammatical ones by a fine-tuned BERT model. \subsubsection{Generating Candidate Response} \label{sec:main-corpus-response-candidate} Given a response $r = \{w_1, w_2, ..., w_n\}$, which is a sequence of words, we select a sub-sequence $s_{i,j} = \{w_i, w_{i+1}, ..., w_j\}$ and substitute it with a jargon phrase $s^Y$. The resulting response $r^Y = \{w_1, ..., w_{i-1}, s^Y, w_{j+1}, ..., w_n\}$ is proposed as a candidate for further filtering. This process is similar to that used in existing style transfer models~\shortcite{li2018delete,sudhakar2019transforming,wu2019mask}. These models substitute style-related words and keep others, so that the content is unchanged. To increase the coverage, we allow arbitrary words to be substituted. This relaxation yields $\mathcal{O}(n^2)$ possible substitutions, so we adopt the following constraints for pruning: \begin{itemize} \item \paragraph{Word constraint:} We only consider words and numbers for substitution. Punctuation marks are not substituted, because they play an important role in grammar. This constraint avoids generating grammatical errors by the change of punctuation. \item \paragraph{Length constraint:} We try to keep $s_{i,j}$ short, so that most words of $r$ are preserved. This choice is made in order to avoid altering too much the initial sentence. Specifically, we limit the length of $s_{i,j}$ to be less than 5 words. \item \paragraph{Context constraint:} We also require the sub-sequence $s_{i,j}$ to share the same preceding or succeeding words with a jargon phrase. For example, suppose we find sentences like ``... is fully multi-threaded ...'' in the stylized corpus $\mathcal{T}$. We may consider applying the substitution only if $s_{i,j}$ succeeds the words ``is fully''. This constraint helps filter out most of obviously ungrammatical candidates. \end{itemize} \subsubsection{Response Filtering} \label{sec:main-corpus-response-filter} We further filter stylized response candidates that are not fluent via a language model. Since a stylized response candidate is not an entirely new sentence, we only need to estimate the fluency of the substituted part. We start with the pre-trained BERT model~\shortcite{devlin2019BERT}, and fine-tune it with a non-conversational stylized corpus $\mathcal{T}$. We mask the jargon phrases in $\mathcal{T}$ and train the model to recover them. Then we use this model to predict the probability of $s^Y$ in a given $r^Y$: $p(s^Y|r^Y)$. The candidate responses with low $p(s^Y|r^Y)$ will be filtered. \subsection{Aligning Responses} After the \textbf{Response Rewriting} process, it is possible that the generated stylized response $r^Y$ is not synonymous to the original response $r$. Moreover, the re-ranking model in the generic dialogue system may not understand $r^Y$ as well. To alleviate these problems, we substitute stylized phrases in $r^Y$ with their synonyms in plain language. That is, for each $s^Y$ in $r^Y$, we substitute $s^Y$ with the synonymous $s^X$. The resulting synonymous response $r'$ is referred to as the modified response. Such direct substitution ensures the synonymity of $r'$ and $r^Y$. Note that $r'$ could be ungrammatical. This is acceptable because $r'$ is only used internally by the dialogue system to match with user input and is not shown to users. \subsection{Context Rewriting} \label{sec:main-corpus-context} Now we have pairs of synonymous response $r'$ and stylized response $r^Y$, and a remaining problem is that the $r'$ and $r^Y$ may be totally irrelevant to the original context $c$ after style transfer. So we attempt to modify $c$ to a more relevant one, $c'$, regarded as the stylized context. To obtain $c'$, we select keywords similar to the stylized phrase $s^Y$ to append to $c$. For example, given $s^y$=``being multi-threaded'', the stylized context $c'$ could be [$c$ + ``simultaneously'' + ``moreover'']. We considered several choices of the keywords, including frequently co-occurred words, nearest words in word embedding space, and simply $s^X$ itself. We found fastText embedding~\shortcite{bojanowski2017enriching} yields more reasonable keywords. We choose the top 5 words with the highest cosine similarity to the stylized phrase $s^Y$. \section{Evaluation} \label{sec:eval} We conducted both offline experiment and online A/B test to evaluate the performance of our framework. Each system is given an utterance in the testing set as input. The output response is evaluated in terms of its quality. \subsection{Dataset\footnote{All datasets will be released.}} \label{Sec:eval-dataset} To train a stylized dialogue system, our framework does not need paralleled data. Instead, we need a generic dialogue corpus $\mathcal{X}$, a stylized non-conversational corpus $\mathcal{T}$, and stylized jargon phrase - synonymous pairs. \paragraph{Source dialogue corpus:} We use the dialogue corpus collected by \shortcite{shang2015neural} from Sina Weibo, a popular twitter-like service in China. The contexts are extracted from posts. Comments on the posts are taken as responses. The corpus covers various topics from different users, so we consider it to be in a generic language style. We normalized the tokens and removed non-content words like ``retweeted from''. Contexts and responses were tokenized by Jieba\footnote{https://github.com/fxsjy/jieba} toolkit. We sampled 100 posts for testing, and took the remaining 4.4 million context-response pairs as the source dialogue corpus. \paragraph{Stylized non-conversational corpus:} Stylized non-conversational corpus are used for Response Filtering only. For each stylized phrase, we searched Sina Weibo and retrieved the first 500 matched posts. Comments were not retrieved. The posts are pre-processed similarly to the source dialogue corpus. We collected five corpora for the Internet slang style and the computer style. \paragraph{Jargon phrase - synonymous pairs:} As mentioned before, We collected on average 523 parallel jargon phrase - synonym pairs per style. \begin{table*} \centering \small \begingroup \setlength{\tabcolsep}{2.9pt} \begin{tabular}{l|R{0.12in}R{0.12in}R{0.12in}R{0.16in}|R{0.12in}R{0.12in}R{0.12in}R{0.16in}|R{0.12in}R{0.12in}R{0.12in}R{0.16in}|R{0.12in}R{0.12in}R{0.12in}R{0.16in}|R{0.12in}R{0.12in}R{0.12in}R{0.16in}||R{0.18in}R{0.19in}R{0.14in}R{0.14in}|R{0.2in}} & \multicolumn{4}{c|}{Trendy Teenager} & \multicolumn{4}{c|}{Computer} & \multicolumn{4}{c|}{Physics} & \multicolumn{4}{c|}{Pok\'emon} & \multicolumn{4}{c||}{Martial Arts} & \multicolumn{5}{c}{Average} \\ & R & S & D1 & D2 & R & S & D1 & D2 & R & S & D1 & D2 & R & S & D1 & D2 & R & S & D1 & D2 & R & S & D1 & D2 & RSA \\ \hline Generic & 1.3 & 0.7 & .51 & .84 & 1.6 & 0.1 & .51 & .84 & 1.6 & 0.0 & .51 & .84 & 1.4 & 0.0 & .51 & .84 & 1.3 & 0.1 & .51 & .84 & 1.45 & 0.17 & .51 & .84 & 0.81 \\ \hline MTask+MMI & \textbf{1.1} & 0.7 & .19 & .40 & 1.0 & 0.1 & .19 & .38 & \textbf{1.1} & 0.0 & .21 & .40 & \textbf{1.0} & 0.0 & .19 & .39 & 1.1 & 0.0 & .19 & .37 & \textbf{1.07} & 0.16 & .19 & .39 & 0.62\\ CAAE-direct & 0.6 & 1.6 & .28 & .48 & 0.1 & 1.7 & .19 & .41 & 0.2 & 1.0 & .25 & .53 & 0.4 & 1.5 & .27 & .51 & 0.3 & 1.1 & .25 & .48 & 0.32 & 1.36 & .25 & .48 & 0.84 \\ CAAE-patch & 0.8 & 1.0 & .32 & .51 & 0.2 & 0.5 & .15 & .30 & 0.3 & 0.1 & .21 & .43 & 0.4 & 0.3 & .27 & .50 & 0.4 & 0.3 & .21 & .50 & 0.42 & 0.45 & .23 & .45 & 0.44 \\ DelRetGen-direct & 0.9 & \textbf{1.7} & .41 & .77 & 0.3 & \textbf{1.9} & .38 & .74 & 0.5 & 1.2 & .47 & .80 & 0.7 & 1.6 & .45 & .77 & 0.7 & \textbf{1.3} & .43 & .76 & 0.62 & \textbf{1.53} & .43 & .77 & 1.08 \\ Ours-direct & \textbf{1.1} & 1.5 & \textbf{.55} & \textbf{.84} & \textbf{1.1} & 0.9 & \textbf{.55} & \textbf{.84} & 1.0 & 0.8 & \textbf{.56} & \textbf{.84} & \textbf{1.0} & 1.2 & \textbf{.57} & \textbf{.83} & \textbf{0.9} & 1.0 & \textbf{.56} & \textbf{.84} & 1.00 & 1.10 & \textbf{.56} & \textbf{.84} & 1.05 \\ Ours-patch & \textbf{1.1} & \textbf{1.7} & .50 & .81 & 0.7 & 1.8 & .47 & .81 & 0.9 & \textbf{1.3} & .49 & .83 & 0.9 & \textbf{1.7} & .50 & \textbf{.83} & 0.8 & 1.2 & .50 & \textbf{.84} & 0.86 & \textbf{1.53} & .49 & .82 & \textbf{1.20} \\ \end{tabular} \endgroup \caption{Evaluation results of stylized dialogue. R: relevance, S: style, D1: distinct-1, D2: distinct-2, *-m: simplified variant without modifying response or context} \label{tab:eval-dialogue} \vspace{-9pt} \end{table*} \subsection{Experiment Settings} \paragraph{Generic dialogue system:} We built a retrieval-based dialogue system as the start point for mimicking different styles. We use Elasticsearch~\shortcite{gormley2015elasticsearch} to build a conversation repository containing the source dialogue corpus $\mathcal{X}$. Given an input utterance, we retrieve the top 100 matched contexts and their paired responses. A pre-trained dialogue model selects a proper response as output. The dialogue model was trained with a different corpus other than the corpus $\mathcal{X}$ used in this paper. \paragraph{Our approach:} We ``patch'' the generic dialogue system with the proposed method. For each $(c, r)$ pair in $\mathcal{X}$, we try to rewrite it to obtain stylized responses. If the rewriting fails, we simply copy the pair, i.e., let $c'=c$ and $r^Y=r'=r$. For ablation study, we consider a simplified variant, where the generic dialogue system is not patched and its output response $r$ is directly rewritten as $r^Y$. We denote our approach and the simplified variant as \textbf{Ours-patch} and \textbf{Ours-direct}. \paragraph{Baselines:} We compare with a generation-based approach by \citeyear{luan2017multi}. It uses multi-task learning to personalize a dialogue model. We train the model with our dialogue corpus $\mathcal{X}$ and non-conversational corpus $\mathcal{T}$. We improve its diversity by interpolating the MMI model by \citeyear{li2016diversity}. We set its encoder and decoder to be 2-layer LSTMs with 500 hidden units. Its vocabulary (60k) covers words in $\mathcal{X}$ and $\mathcal{T}$. We refer to this approach as \textbf{MTask+MMI}. We also consider leveraging text style transfer models. Given an output response $r$ of the generic dialogue system, we use a style transfer model to transform $r$ to a stylized response. Two representative models are used, the cross-aligned auto-encoder by \citeyear{shen2017style} and the ``delete, retrieve, and generate'' model by \citeyear{li2018delete}. We denote the two approaches as \textbf{CAAE-direct} and \textbf{DelRetGen-direct}. In addition, we consider integrating the style transfer models into our framework. We replace the procedures of \textbf{Response Rewriting} with one of the style transfer models. We keep the remaining procedures and ``patch'' the generic dialogue system accordingly. This approach is denoted as \textbf{CAAE-patch}\footnote{We tried to optimize the original implementation of DelRetGen, but still can not rewrite the corpus in a reasonable time.}. \subsection{Metrics} We consider three criteria for response's quality: relevance, style degree, and content diversity. \paragraph{Relevance:} Relevance refers to the extent of a response being proper for an input utterance. We follow the same guideline as \citeyear{shang2015neural} to rate Relevance on a scale of 0 to 2. \paragraph{Style degree:} style degree refers to how likely the specified language style can be identified. We rate style degree on a scale of 0 to 2. \begin{itemize} \item \textbf{Strong style (2):} Obvious usage of words in the specified language style can be found. \item \textbf{Weak style (1):} Two cases are included: (a) Stylized words are used, but it is still similar to everyday conversation, e.g., ``What's the name of this \textbf{software}?'' (b) Common words are used, but they have special meaning for the target persona. For example, ``I have an \textbf{abstract} girlfriend'', where ``abstract'' has a specific meaning in programming. \item \textbf{No style (0):} The response is not fluent or does dot show any identifiable style. \end{itemize} \paragraph{Diversity:} Diversity of response is recognized as an important metric of dialogue systems~\shortcite{li2016diversity}. Dialogue systems with good diversity produce more interesting responses on various topics. We measure the diversity of responses by the number of distinct unigrams and bigrams divided by total number of words in the responses, i.e., Distinct-1 (D1) and Distinct-2 (D2). For each style, we obtained 700 responses from the 100 testing input utterances by the evaluated systems. An input utterance and a shuffled list of responses were presented to 3 annotators each time. The annotators were asked to rate each response according to the above guideline. To measure agreement, we use a generalized form of Scott's pi coefficient with linear weighting~\shortcite{gwet2014handbook}. The coefficients indicate fair agreement among ratings (0.37 and 0.44 for relevance; 0.56 and 0.79 for style degree). \begin{figure} \centering \small \begingroup \setlength{\tabcolsep}{3pt} \begin{tabular}{l|p{2.2in}} \multirow{2}{*}{User Query} & \chinese{好久没吃了,好想吃哇} \\ & Haven't eat it for a long time and really want to eat it. \\ \hline \multirow{2}{*}{Trendy Teenagers} & \chinese{好久没吃了啊,减肥\underline{不存在的},能不诱惑我吗?} \\ & Haven't eat it for a lone time. Losing weight is \textbf{non-existent}. Could you not tempt me? \\ \hline \multirow{2}{*}{Computer Junkies} & \chinese{想吃,\underline{贪婪算法}告诉我怎么吃吗?}\\ & Want to eat. Would \textbf{greedy algorithms} tell me how to eat? \\ \hline \multirow{2}{*}{Physics Fans} & \chinese{好饿啊。看到这汉堡就控制\underline{运动速度}。} \\ & So hungry. I have to control the \textbf{movement velocity} when I see this hamburger.\\ \hline \multirow{2}{*}{Pok\'emon Fans} & \chinese{哈哈,我爱\underline{舔舌}头吃!}\\ & Haha, I love eating by \textbf{lick}. \\ \hline \multirow{2}{*}{Martial Arts Fans} & \chinese{不是好久没吃过,\underline{苏荃}从来都没吃过…} \\ & Not for a long time, \textbf{Su Quan}\footnotemark has never eaten it. \\ \hline \end{tabular} \endgroup \caption{Sample responses by our approach.} \label{fig:sample-dialogue} \end{figure} \subsection{Evaluation Result} Table \ref{tab:eval-dialogue} shows evaluation results of stylized dialogue. The average of relevance and style degree ratings (denoted as RSA) is included for overall performance. The multi-task approach \textbf{MTask+MMI} does not produce stylized response as expected. We attribute it to the low overlap between the dialogue corpus and the target corpus. On average, only 81.4\% words of the target corpus (excluding stop words) appear in the vocabulary of dialogue corpus. The decoder fails to correlate non-overlapping words with the utterance's encoding, even after we extended its vocabulary. For CAAE-patch, its relevance increases after modifying context and response, but its style degree decreases dramatically. The average lengths of response are respectively 7.4 and 5.7 tokens for CAAE-direct and CAAE-patch. The root cause for this behavior is the low content diversity. The model tends to produce short and common responses. The dialogue model has to choose a ``safe'' but more relevant one, when no other relevant and informative response is available. Our simplified approach (Ours-direct) achieves a higher relevance and a lower style degree than our complete approach (ours-patch). Among the responses produced by the base system, the simplified approach fails to transfer any response for 25\% of queries, whereas ours-patch succeed to return at least one stylized responses for all queries. If we count the queries on which both approaches succeed, the relevance is 0.78 and 0.86, and the style degree is 1.43 and 1.52, for the simplified and the complete approaches. The diversity remains similar. This strongly supports our idea of distinguishing transferring style from keeping meaning unchanged does work well. In general, our complete approach (ours-patch) achieves the best overall performance in terms of RSA (t-tests with $p<10^{-4})$. Figure \ref{fig:sample-dialogue} illustrates our approach's responses. \footnotetext{A character in the novel series \textit{The Legend of Lu Xiaofeng}.} \begin{figure*}[h] \centering \includegraphics[width=6.25in]{triggerrate.1} \caption{Relevance and style degree change when we trigger different ratios of stylized responses} \label{fig:corpus-coverage} \end{figure*} \subsection{Changes with Trigger Rate} There is a trade-off between style degree and relevance. When we allow more stylized responses to return during conversations, a chatbot has more chance to exhibit as its style. However, there is a risk of lowering the relevance. Thus we use trigger rate as our variant and draw curves to show how relevance and style degree change at the same time. Based on our human labeled data, we simulate the results when different trigger rates are applied. For example, given a style, e.g., trendy teenagers, we set a threshold of the ensemble regression model output to filter out 90\% stylized responses. Thus we get 10\% trigger rate. Then we average the relevance score and the style degree as the corresponding evaluation results, e.g., 1.3 and 1.8 for the trendy teenager style. Similarly, we can filter out different ratio of stylized responses and get relevance and style degree scores at different trigger rate. Figure \ref{fig:corpus-coverage} shows us the curves for five styles. Take the trendy teenager style as an example. We observe that relevance remains high until about 15\% stylized responses are triggered. Then relevance goes down gradually. Even if all stylized responses are triggered, the relevance score is around 1.1, which means above fair. The style curve has a similar trend and the highest style degree is achieved when 20\% stylized responses are triggered. At that position, the relevance score is close to the maximum. Therefore, if our goal is to add some sense of style while keeping high relevance, we can choose the trigger rate of 20\%. It means that in almost one fifth turns users can get the stylized responses. That is a proper ratio as even a real trendy teenager does not show her/his style at all utterances. As Figure \ref{fig:corpus-coverage} shows, other styles have similar trends. We can find a proper trade-off between relevance and style degree in the curves. Our approach provides the flexibility to adjust a dialogue system according to the requirements of relevance and style degree. Some styles may be more difficult than some other styles to transfer. For example, the computer style has lowest relevance. Although the style degree is as high as 1.8, the relevance score is only 0.7 when the trigger rate is 10\%. This indicate that there is a big gap between the dialogue corpus and the stylized non-conversational corpus for the computer style. We guess that Weibo users like publishing content about their life, more than about techniques. \begin{table} \centering \begingroup \begin{tabular}{l|rrrr|r} & \multicolumn{1}{c}{F} & \multicolumn{1}{c}{S} & \multicolumn{1}{c}{D1} & \multicolumn{1}{c|}{D2} & \multicolumn{1}{c}{FSA} \\ \hline Source & 1.86 & 0.18 & .50 & .84 & 1.02 \\ \hline CAAE & 1.09 & 1.30 & .14 & .32 & 1.20 \\ DelRetGen & 1.01 & \textbf{1.41} & .41 & .77 & 1.21 \\ Ours & \textbf{1.43} & 1.19 & \textbf{.53} & \textbf{.84} & \textbf{1.31} \\ \end{tabular} \endgroup \caption{Evaluation results of transferred responses by single models. LM: Language Model} \label{tab:eval-corpus-single} \vspace{-9pt} \end{table} \subsection{Analysis of Style Transfer} In this study, we propose a first study to transfer a generic corpus to a stylized one. To evaluate how effective our transfer approach is, we further compare our style transfer model with two baseline methods, \textbf{CAAE} and \textbf{DelRetGen}. The evaluation metrics of style transfer are similar to that of stylized dialogue, and we only change the relevance metric to fluency metric. The fluency metric is rated on a scale of 0 to 2 that represent completely non-sense (0), understandable with minor errors (1), and fluent without error (2), respectively. Table \ref{tab:eval-corpus-single} shows the evaluation results. As expected, source responses are rated with perfect fluency and low style degree. They slightly exhibit Internet slang's style, because the dataset is collected from social media. On average, our approach achieves much better fluency and diversity but lower style degree compared to the two baselines. CAAE tends to generate ``safe'' sentences which make use of only a few target style phrases. To see this, we counted distinct target style phrases in transferred responses. The averaged counts are respectively 81, 172, and 181, for CAAE, DelRetGen, and our approach. DelRetGen improves diversity by involving more target style phrases than CAAE. However, its generation step tends to generate frequent words, limiting its overall diversity. In general, our approach outperforms the baselines on overall performance (FSA, D1, and D2; t-tests with $p < 10^{-4}$). \subsection{Online Evaluation} Compared to the generic dialogue system, our framework (as well as other stylized systems) produces more stylized but less relevant responses. We wonder if it has a positive or negative impact on user satisfaction. We conducted A/B test on a commercial social chatbot during one month. We select the trendy teenager style as our testbed. We randomly selected a fraction of users as the treatment group. They were served with the patched system. In case where the patched system fails to find a relevant response, we fallback to the generic system. Users in the control group were always served with the generic system. After the A/B test, we collected 12K conversations for the treatment group. A conversation is a sequence $\{(u_1, r_1), (u_2, r_2)\}$, where $u$ is a user utterance and $r$ is a response. We let $r_1$ be the patched system's response. The same number of conversations were sampled from the control group. We consider two automatic metrics to measure user satisfaction. The first metric is the sentiment of user's follow-up utterance. Positive sentiment reflects better user satisfaction. We use a sentiment classifier~\cite{zeng2019attitude} to classify the follow-up utterance $u_2$. The classifier outputs labels of $\{-1,0,1\}$, for negative, neutral, and positive sentiment. We take the average label for each group as \textit{Sentiment} in Table \ref{tab:online-eval}. The second metric is the fraction of overlapping words between $r_1$ and $u_2$ (See \textit{Automatic follow-up} in Table \ref{tab:online-eval}). It indicates whether the user is following $r_1$ or starting a new topic. We also use human annotation for evaluation. We sampled 250 conversations from each group, and asked 5 human annotators to rate user's satisfaction on a scale of -2 to +2: \begin{itemize} \item \textbf{Satisfied (+2)} The user is satisfied with the conversation and shows positive emotion. \item \textbf{Follow (+1)} The user understands the response $r_1$ and follows the topic. \item \textbf{Neutral (0)} The user keeps chatting but to ignore $r_1$. \item \textbf{Not-follow (-1)} The user is confused about $r_1$ or simply exits the chatbot. \item \textbf{Unsatisfied (-2)} The user is upset about the conversation and shows negative emotion. \end{itemize} Table \ref{tab:online-eval} shows the comparison in the above metrics. The patched system performs consistently better than the baseline system across all metrics. \begin{table} \centering \begin{tabular}{c|cc} & Treatment & Control \\ \hline Sentiment & \textbf{0.0250} & 0.0217 \\ Automatic follow-up & \textbf{0.1120} & 0.10445 \\ Human rating & \textbf{0.488} & 0.436 \\ \end{tabular} \caption{Evaluation result of online A/B test.} \label{tab:online-eval} \vspace{-6pt} \end{table} \section{Conclusion and Future Work} \label{sec:conclude} We propose a light-weight ``patching'' framework that enables a retrieval-based dialogue system to mimic the language style of a specified character setting. Our framework is flexible and less expensive to apply. Our approach is based on transforming a generic dialogue corpus to a stylized corpus. We design a series of strategies to implement the transformation. Five character settings are implemented. The experiments show that, with several hundreds of manually annotated jargon phrases, our approach is able to produce fluent, relevant, stylized, and diverse responses. A/B test indicates that users are more satisfied about the stylized system. As future work, we plan to improve relevance further and experiment with combining two or more styles in one chatbot. Theoretically our proposed framework is additive, because it provides a way to put different but non-contradictory personalities together. For example, a chatbot could be a computer junkie and a martial arts fan at the same time. When both character settings have response candidates, we can choose one of them by pre-defined priors. It would be interesting to implement such combination and test its effectiveness. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-09-14T02:21:09', 'yymm': '2109', 'arxiv_id': '2109.05477', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05477'}
arxiv
\section{The Training Details} \vspace{-1 mm} The backbones of classification-based (\textit{Clas}) and regression-based (\textit{Reg}) baseline networks are initialized with ImageNet \cite{deng2009imagenet} pretrained model. In \textit{Clas}, the output resolution of 3D-heatmaps is 28 $\times$ 28 $\times$ 28. The MLP branch that predicts object rotation adopts three fully-connected layers with 512, 256 and 128 neurons for each, and a final layer of 6 neurons that predict the continuity representation \cite{zhou2019continuity} of object rotation: $\mathbf{r}_o \in \mathfrak{so}(3)$. We train the network 100 epochs with Adam optimizer and learning rate of $ 5\times 10^{-5}$. The training batch size across all the following experiments is 64 per GPU and 2 GPUs in total. The framework is implemented in PyTorch. All the object models and textures are provided by the original dataset. For all the training batches, the blended rate of original real-world data and ArtiBoost synthetic data is approximately $1:1$. We empirically find that this real-synthetic blended rate achieves the best performance. \section{Objects' Symmetry Axes}\label{sec:symmetry_axes} In the hand-object interaction dataset, it is far more challenging to predict the pose of an object than in the dataset that only contains objects, since the objects are often severely occluded by the hand. Therefore, we relax the restrictions of the objects' symmetry axes following the practices in \cite{chao2021dexycb,hampali2021handsformer}. Supposing the set $\mathcal{S}$ contains all the valid rotation matrices based on the object's predefined symmetry axes, we calculate $\mathcal{S}$ with the following step: \begin{table}[h] \renewcommand{\arraystretch}{1.0} \begin{center} \resizebox{1.0\linewidth}{!}{ \begin{tabular}{c|c|c} \toprule Objects & Axes: $\mathbf{n}$ & Angle: $\theta$ \\ \midrule 002\_master\_chef\_can & x, y, z & $180^\circ$, $180^\circ$, $\infty$\\ 003\_cracker\_box & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$\\ 004\_sugar\_box & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$\\ 005\_tomato\_soup\_can & x, y, z & $180^\circ$, $180^\circ$, $\infty$\\ 006\_mustard\_bottle & z & $180^\circ$\\ 007\_tuna\_fish\_can & x, y, z & $180^\circ$, $180^\circ$, $\infty$\\ 008\_pudding\_box & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$ \\ 009\_gelatin\_box & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$ \\ 010\_potted\_meat\_can & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$ \\ 024\_bowl & z & $\infty$\\ 036\_wood\_block & x, y, z & $180^\circ$, $180^\circ$, $90^\circ$ \\ 037\_scissors & z & $180^\circ$\\ 040\_large\_marker & x, y, z & $180^\circ$, $\infty$, $180^\circ$\\ 052\_extra\_large\_clamp & x & $180^\circ$\\ 061\_foam\_brick & x, y, z & $180^\circ$, $90^\circ$, $180^\circ$ \\ \bottomrule \end{tabular} } \end{center}\vspace{-5mm} \caption{\textbf{YCB objects' axes of symmetry}. $\infty$ indicates the object is revolutionary by the axis.} \label{tab:def_sym} \end{table} \begin{enumerate}[label={\arabic*)},font={\bfseries},leftmargin=*] \setlength\itemsep{-1 mm} \item Firstly, as shown in Fig~\ref{fig:pca_obj}, we align the object to its principal axis of inertia. \item Secondly, we define the axis $\mathbf{n}$ and angle $\theta$ of symmetry in Tab~\ref{tab:def_sym} under the aligned coordinate system, where the object's geometry does not change when rotate this object by an angle of $\theta$ around $\mathbf{n}$. Here we get the predefined rotation matrix $\mathbf{R}_{def} = \exp(\theta\mathbf{n})$. \item To get a more accurate rotation matrix $\mathbf{R}$, we use the Iterative Closest Point (ICP) algorithm to fit a $\Delta \mathbf{R}$. The ICP minimizes the difference between $\Delta \mathbf{R} * \mathbf{R}_{def} * \mathbf{V}_o$ and $\mathbf{V}_o$, where $\mathbf{V}_o$ is the point clouds on object surface. Finally, we have $\mathbf{R} = \Delta \mathbf{R} * \mathbf{R}_{def}, \mathbf{R} \in \mathcal{S}$. \end{enumerate} \begin{figure}[h] \begin{center} \includegraphics[width=1.0\linewidth]{fig/supp_axes.pdf}\vspace{-3mm} \end{center} \caption{\textbf{YCB objects' principal axis of inertia.} The x, y and z axis are colored in red, green and blue, respectively.}\vspace{-3mm} \label{fig:pca_obj} \end{figure} \begin{table*}[ht] \renewcommand{\arraystretch}{1.0} \begin{center} \resizebox{0.95\linewidth}{!}{ \begin{tabular}{c|c|c|c|c|c} \toprule Objects & Our \textit{Clas} sym & Our \textit{Clas} sym \textbf{+ Arti} & Objects & Our \textit{Clas} sym & Our \textit{Clas} sym \textbf{+ Arti}\\ \midrule 002\_master\_chef\_can & 27.62 & \textbf{25.59} & 003\_cracker\_box & 63.68 & \textbf{46.13}\\ 004\_sugar\_box & 48.42 & \textbf{39.20} & 005\_tomato\_soup\_can & 33.31 & \textbf{31.90}\\ 006\_mustard\_bottle & 35.16 & \textbf{32.01} & 007\_tuna\_fish\_can & 24.54 & \textbf{23.81}\\ 008\_pudding\_box & 39.92 & \textbf{35.04} & 009\_gelatin\_box & 45.99 & \textbf{37.81}\\ 010\_potted\_meat\_can & 41.44 & \textbf{36.47} & 011\_banana & 98.69 & \textbf{79.87}\\ 019\_pitcher\_base & 105.66 & \textbf{84.82} & 021\_bleach\_cleanser & 91.66 & \textbf{72.31}\\ 024\_bowl & \textbf{31.74} & 32.37 & 025\_mug & 65.46 & \textbf{54.28}\\ 035\_power\_drill & 74.95 & \textbf{52.70} & 036\_wood\_block & 51.24 & \textbf{50.69}\\ 037\_scissors & 88.10 & \textbf{66.52} & 040\_large\_marker & 30.76 & \textbf{29.33}\\ 052\_extra\_large\_clamp & 78.87 & \textbf{55.87} & 061\_foam\_brick & 34.23 & \textbf{31.53}\\ \bottomrule \end{tabular} } \end{center} \vspace{-5mm} \caption{Full MSSD results ($mm$) on \textbf{DexYCB} testing set.}\vspace{-1mm} \label{tab:full_dexycb} \end{table*} \begin{figure*}[!t] \begin{center} \includegraphics[width=1.0\linewidth]{fig/supp_qualitative.pdf} \end{center} \vspace{-5mm} \caption{(\textbf{Best view in color}) More qualitative results on \textbf{HO3D} (\engordnumber{1} $\sim$ \engordnumber{3} rows) and \textbf{DexYCB} (\engordnumber{4} $\sim$ \engordnumber{8} rows) datasets.}\vspace{-1mm} \label{fig:supp_qua} \end{figure*} \section{Additional Results}\label{sec:add_results} We demonstrate 20 YCB objects' MSSD on DexYCB in \cref{tab:full_dexycb}. With ArtiBoost, our network can predict a more accurate pose for almost every object. More qualitative results on HO3D and DexYCB testing set are shown in \cref{fig:supp_qua}. \end{appendices} \section{Discussion} \vspace{-1mm}\noindent\textbf{Limitation.} However, we do not explicitly mitigate the domain gap between the synthetic and real data, as we find that the dominant improvement to the HOPE task is brought from the images of more diverse pose variants, rather than images with a more realistic appearance. Besides, as the renderer in ArtiBoost is not differentiable, current ArtiBoost only supports exploration in a predefined lookup table (\eg CCV-space). In future work, we will investigate a powerful generative and contrastive model seeking common features shared by both real and synthetic images. \vspace{1mm}\noindent\textbf{Conclusion.} In this work, we propose a novel online data enrichment method ArtiBoost, which enhances the learning framework of articulated pose estimation by exploration and synthesis. Our proposed ArtiBoost can be integrated into any learning framework, and in this work, we show its efficacy on the challenging task of hand-object pose estimation. Even with a simple baseline, our method can boost it to outperform the previous SOTA on the popular datasets. Besides, the proposed CCV-space also opens the door towards the generic articulated pose estimation, which we leave as future work. \noindent\rule{\columnwidth}{1.5pt} \noindent\textbf{Acknowledgment} This work was supported by the National Key Research and Development Project of China (No.2021ZD0110700), Shanghai Municipal Science and Technology Major Project (2021SHZDZX0102), Shanghai Qi Zhi Institute, and SHEITC (2018-RGZN-02046). \section{Experiment and Result}\label{sec:exp} \begin{table*}[ht] \begin{center} \begin{minipage}[!htp]{0.3\textwidth} \begin{center} \makeatletter\def\@captype{table}\makeatother \resizebox{\linewidth}{!}{ \begin{tabular}{l|c|c} \toprule Method & MPJPE & MPCPE \\ \midrule Hasson \etal \cite{hasson2020leveraging} & 11.33 & 28.42 \\ Our \textit{Clas} w/o $\mathcal{L}_{ord}$ & 8.71 & \textbf{18.64}\\ Our \textit{Clas} & \textbf{8.60} & 19.45\\ \bottomrule \end{tabular} } \end{center}\vspace{-4.0mm} \caption{Comparisons with SOTA on \textbf{FHAB} dataset (errors are reported in $mm$). The comparisons are made in the wrist-aligned coordinates system. } \label{table:fhb_res} \end{minipage} ~~~ \begin{minipage}[!htp]{0.23\textwidth} \begin{center} \resizebox{1.0\linewidth}{!}{ \makeatletter\def\@captype{table}\makeatother \setlength{\tabcolsep}{1mm}{ \begin{tabular}{l|c|c} \toprule Method & MPJPE & MPCPE \\ \midrule Hasson \etal \cite{hasson2020leveraging} & 3.69 & 12.38 \\ Liu \etal \cite{liu2021semi} & 2.93 & - \\ \midrule Our \textit{Reg} & 3.53 & 7.38\\ Our \textit{Reg} \textbf{+ Arti} & \textbf{3.17} & \textbf{5.87}\\ \midrule Our \textit{Clas} & 3.06 & 7.24\\ Our \textit{Clas} \textbf{+ Arti} & \textbf{2.64} & \textbf{5.16}\\ \bottomrule \end{tabular} } } \end{center}\vspace{-5.mm} \caption{Comparisons ($cm$) with SOTA on \textbf{HO3D} dataset.} \label{table:ho3d_res} \end{minipage} ~~~ \begin{minipage}[!htp]{0.41\textwidth} \begin{center} \resizebox{1.0\linewidth}{!} { \makeatletter\def\@captype{table}\makeatother \setlength{\tabcolsep}{1mm}{ \begin{tabular}{l|c|ccc} \toprule \multirow{3}{*}{Method} & \multirow{3}{*}{MPJPE} & \multicolumn{3}{c}{MSSD} \\ \cline{3-5} & & \tabincell{c}{\textit{mustard} \\ \textit{bottle}} & \tabincell{c}{\textit{bleach} \\ \textit{cleanser} } & \tabincell{c}{\textit{potted} \\\textit{meat can} } \\ \midrule Hampali \etal \cite{hampali2021handsformer} & 2.57 & 4.41 & 6.03 & 9.08 \\ Our \textit{Clas} sym & 3.10 & 4.07 & 6.56 & 8.70 \\ Our \textit{Clas} sym \textbf{+ Arti} & \textbf{2.53} & \textbf{3.14} & \textbf{5.72} & \textbf{6.36} \\ \bottomrule \end{tabular} } } \end{center}\vspace{-6.0mm} \caption{Comparison ($cm$) with Transformer-based SOTA on \textbf{HO3D} using symmetry-aware loss $\mathcal{L}_{sym}$. We use the same symmetry axes as described in \cite{hampali2021handsformer}.} \label{table:sym_ho3d_res} \end{minipage} \end{center}\vspace{-8mm} \end{table*} \vspace{-1mm}\subsection{Dataset and Metrics} \vspace{-2mm}\noindent\textbf{Dataset. } We evaluate our methods on three hand-object dataset: \textbf{FHAB} \cite{garcia2018first}, \textbf{HO3D} \cite{hampali2020ho3dv2} and \textbf{DexYCB} \cite{chao2021dexycb}. FHAB contains 20K samples of hand in manipulation with objects. We follow the ``action'' split as in Tekin \etal \cite{tekin2019h+o}, which contains 10,503 training and 10,998 testing samples. The FHAB dataset only contains a few numbers of hand poses and viewpoints. We find its training set is adequate for the neural network. Thus we only use FHAB to verify the feasibility of the learning framework. HO3D is a dataset that contains a large number of images of hand-object interactions. Evaluation of the HO3D testing set is conducted at an online server. We also report our results on the latest \textbf{HO3Dv3} \cite{hampali2021ho}, which is released with different training$/$testing split. DexYCB contains 582K image frames of grasping on 20 YCB objects. We only evaluate the right-hand pose using the official ``S0'' split and filter out the frames that the minimum hand-object distance is large than 5 $cm$ to make sure a plausible hand-object interaction would appear. \vspace{1mm}\noindent\textbf{Metrics.~~} For the hand pose, we report the mean per joint position error (\textbf{MPJPE}) in the wrist-aligned coordinates system. For the object pose, there are two standard metrics in literature: mean per corners position error (\textbf{MPCPE}) and maximum symmetry-aware surface distance (\textbf{MSSD}). The former MPCPE directly measures the unique pose of the object. However, since some objects are symmetrical or revolutionary invariant, and since the objects are often severely occluded by hand, direct measuring objects' absolute and unique pose is sometimes less reasonable. MSSD measures the difference between the current object pose to its closest counterpart in all its rotation invariants. In this paper, we report the object's MPCPE and MSSD within different training schemes. When reporting MPCPE, we train the network with $\lambda_1 = \lambda_2 = 1$ and $\lambda_3 = 0$. When taking objects' symmetricity into account, we train the network with $\lambda_1 = \lambda_2 = 0$ and $\lambda_3 = 1$. We call the later network symmetry model (abbr. sym) and report its MSSD following the BOP challenge protocol \cite{hodavn2020bop}. The definition of YCB objects' symmetry axes can be found in \textbf{Appx}\xspace. \begin{figure}[t] \begin{center} \includegraphics[width=1.0\linewidth]{fig/qualitative_one_col.pdf} \end{center}\vspace{-5mm} \caption{Qualitative results on the \textbf{HO3D} and \textbf{DexYCB} dataset.} \vspace{-4mm} \label{fig:qua} \end{figure} \subsection{HOPE Network Performance}\label{sec:hope_exp} \vspace{-1mm}\noindent\textbf{Qualitative Results.} Our qualitative results on HO3D and DexYCB testing sets are shown in \cref{fig:qua}. We draw the predicted hand joints and object corners as their 2D projections (\engordnumber{1} col). We also adopt a pretrained IK network \cite{lv2021handtailor} that maps the hand joints to hand mesh surfaces for visualization. We draw the full hand-object geometry in camera view (\engordnumber{2} col) and another viewpoint (\engordnumber{3} col). More qualitative results are provided in \textbf{Appx}\xspace. \vspace{1 mm}\noindent\textbf{Comparison with State-of-the-Art.} In \cref{table:fhb_res} we compare our \textit{Clas} with the previous SOTA \cite{hasson2020leveraging} on FHAB to justify the ordinal relation loss $\mathcal{L}_{ord}$. To note, \cite{hasson2020leveraging} regressed hand and object poses in camera space. For fair comparison, we align their results in wrist-relative coordinates system. In the subsequent tables, we use ``\textbf{+ Arti}'' to denote a certain network is trained by the original dataset's training split \textbf{plus} the synthetic data brought from \textbf{Arti}Boost's exploration and synthesis. In \cref{table:ho3d_res}, we show that our ArtiBoost enhances both \textit{Reg} and \textit{Clas} performance on HO3D dataset. We obtain \textbf{28\%} and \textbf{10\%} MPJPE improvement compared with the previous SOTA \cite{hasson2020leveraging} and \cite{liu2021semi}, respectively. For fair compassion, we remove the unseen object in the testing set (\textit{pitcher base}) when calculating MPCPE. Under the symmetry model (denoted as ``sym''), we report the performance of our ArtiBoost in \cref{table:sym_ho3d_res}. Our \textit{Clas} outperforms the recent Transformer-based method \cite{hampali2021handsformer} when using ArtiBoost. We also evaluate our method on latest released dataset DexYCB and HO3D v3 in \cref{table:dexycb_res} and \cref{table:ho3dv3_res}, respectively. All the results demonstrate the effectiveness of our method. \begin{table}[t] \renewcommand{\arraystretch}{1.0} \begin{center} \resizebox{\linewidth}{!}{ \begin{tabular}{l|c|cccc} \toprule \multirow{3}{*}{Method} & \multirow{3}{*}{MPJPE} & \multicolumn{4}{c}{MSSD $\bm{\star}$} \\ \cline{3-6} & & \tabincell{c}{\textit{power} \\ \textit{drill}} & \tabincell{c}{\textit{cracker} \\ \textit{box}} & \tabincell{c}{\textit{scissors}} & \tabincell{c}{\textit{bleach} \\\textit{cleanser}}\\ \midrule Our \textit{Clas} sym & 13.00 & 74.95 & 63.68 & 88.10 & 91.66 \\ Our \textit{Clas} sym \textbf{+ Arti} & \textbf{12.80} & \textbf{52.70} & \textbf{46.13} & \textbf{66.52} & \textbf{72.31} \\ \bottomrule \end{tabular} } \end{center} \vspace{-5.5mm} \caption{Our results ($mm$) on \textbf{DexYCB}. $\bm{\star}$ We only list the MSSD score of 4 objects. The full table can be found in \textbf{Appx}\xspace.}\vspace{-1mm} \label{table:dexycb_res} \end{table} \begin{table}[t] \renewcommand{\arraystretch}{1.0} \begin{center} \resizebox{1.0\linewidth}{!}{ \begin{tabular}{l|cc|ccc} \toprule \multirow{3}{*}{Method} & \multirow{3}{*}{MPJPE} & \multirow{3}{*}{MPCPE} & \multicolumn{3}{c}{MSSD} \\ \cline{4-6} & & & \tabincell{c}{\textit{mustard} \\ \textit{bottle} } & \tabincell{c}{\textit{bleach} \\ \textit{cleanser}} & \tabincell{c}{\textit{potted} \\ \textit{meat can}} \\ \midrule Our \textit{Clas} & 2.94 & 7.53 & 6.88 & 5.56 & 7.63 \\ Our \textit{Clas} \textbf{+ Arti} & 2.50 & 5.88 & 3.79 & \textbf{4.99} & 6.21 \\ \midrule Our \textit{Clas} sym & 2.98 & - & 3.73 & 6.39 & 7.28 \\ Our \textit{Clas} sym \textbf{+ Arti} & \textbf{2.34} & - & \textbf{2.66} & 5.23 & \textbf{5.82} \\ \bottomrule \end{tabular} } \end{center} \vspace{-5.5mm} \caption{Our results ($cm$) on \textbf{HO3D v3}.}\vspace{-4mm} \label{table:ho3dv3_res} \end{table} \begin{table*}[ht] \begin{center} \begin{minipage}[!htp]{0.33\textwidth} \begin{center} \makeatletter\def\@captype{table}\makeatother \resizebox{\linewidth}{!}{ \begin{tabular}{l|c|c} \toprule Training set composition & MPJPE & MPCPE \\ \midrule HO3D & 3.06 & 7.24\\ \cellcolor{Gray} \textbf{a.1)} HO3D $\bigoplus$ YCBAfford & \cellcolor{Gray} 3.01 & \cellcolor{Gray} 6.89 \\ \cellcolor{DGray} \textbf{a.2)} HO3D $\bigoplus$ CCV-space & \cellcolor{DGray} 2.71 & \cellcolor{DGray} 5.49 \\ HO3D \textbf{+ Arti} (full version) & \textbf{2.64} & \textbf{5.16}\\ \bottomrule \end{tabular} } \end{center}\vspace{-6.5mm} \caption{Ablation on grasp poses synthesis. \textbf{a.1) \textit{v.s} a.2)} shows a same network model (\textit{Clas}) trained on HO3D plus synthetic pose from Conventional \textbf{\textit{v.s}} from CCV-space. ($cm$)} \label{table:compare_graspit} \end{minipage} ~~~ \begin{minipage}[!htp]{0.3\textwidth} \begin{center} \resizebox{1.0\linewidth}{!}{ \makeatletter\def\@captype{table}\makeatother \setlength{\tabcolsep}{1mm}{ \begin{tabular}{l|c|c} \toprule Method on \% of source data & MPJPE & MPCPE \\ \midrule Our \textit{Reg} (10\%) & 3.81 & 8.77\\ Our \textit{Reg} (100\%) & 3.53 & 7.38\\ Our \textit{Reg} (10\%) \textbf{+ Arti} & \textbf{3.29} & \textbf{6.87}\\ \midrule Our \textit{Clas} (10\%) & 3.63 & 7.66\\ Our \textit{Clas} (100\%) & 3.06 & 7.24\\ Our \textit{Clas} (10\%) \textbf{+ Arti} & \textbf{3.05} & \textbf{6.02}\\ \bottomrule \end{tabular} } } \end{center}\vspace{-5.5mm} \caption{Performance of models trained on 10\% of \textbf{HO3D} source data. ($cm$)} \label{tab:f01_ho3d_res} \end{minipage} ~~~ \begin{minipage}[!htp]{0.31\linewidth} \begin{center} \resizebox{1.0\linewidth}{!} { \makeatletter\def\@captype{table}\makeatother \setlength{\tabcolsep}{1mm}{ \begin{tabular}{l|l|cc|c} \toprule Dataset & Method & MPJPE & MPCPE & CS-J \\ \midrule HO3Dv1 & \cite{hasson2020leveraging} & 5.75& 9.61 & 6.24 \\ HO3Dv1 & \cite{hasson2020leveraging} + \textbf{Arti} & \textbf{3.67} & \textbf{3.24} & \textbf{3.57} \\ \midrule HO3D & \cite{hasson2020leveraging} & 3.69 & 12.38 & 5.52 \\ HO3D & \cite{hasson2020leveraging} \textbf{+ Arti} & \textbf{3.39} & \textbf{8.31} & \textbf{4.90} \\ \bottomrule \end{tabular} } } \end{center}\vspace{-3.5mm} \caption{Results of porting ArtiBoost to the model in Hasson \etal \cite{hasson2020leveraging}. \textbf{CS-J}: the MPJPE in camera space; all in $cm$.} \label{table:expansibility} \end{minipage} \end{center}\vspace{-7mm} \end{table*} \vspace{-0.5mm}\subsection{Ablation Study}\label{sec:ablation} \vspace{-1 mm} To further discover how ArtiBoost works, we design two ablation studies. \textbf{A).} We compare the ArtiBoost with conventional grasp synthesis methods to show the efficacy of the CCV-space. \textbf{B).} We compare ArtiBoost with an offline training scheme to demonstrate the efficiency of our dynamic online re-weighting. \vspace{0.5mm} \noindent\textbf{A). Conventional Grasp Synthesis.} Simulated hand-object poses in GraspIt \cite{graspit} are not necessarily correct or diverse (see Sec. 3.1 and Fig. 3 of GanHand \cite{corona2020ganhand}). Therefore, Corona \etal \cite{corona2020ganhand} manually annotated the MANO hand grasping YCB objects \cite{ycb} and released a grasping pose dataset: YCBAfford. We find YCBAfford is an ideal contrast of our synthetic grasps in CCV-space. In this study, we compare the performance of the same model trained on two different data compositions. One is \textbf{a.1)} HO3D plus YCBAfford, and the other is \textbf{a.2)} HO3D plus our synthetic poses in CCV-space. To ensure fair and instructive comparison, we use the same amounts of HO poses from YCBAfford and CCV-space, set up an identical rendering pipeline, and turn off the re-weighting. During training, the synthetic HO poses will be randomly sampled and rendered, and then the rendered images will be blended into the original HO3D training set. \cref{table:compare_graspit} shows the results of this study. We find that the model trained with poses in CCV-space outperforms the model trained with conventional synthetic poses, verifying an essential idea in our paper: diverse pose variants facilitate pose estimation. \begin{figure}[t] \begin{center} \includegraphics[width=1.0\linewidth]{fig/re-weighting2}\vspace{-6mm} \end{center} \caption{Ablation on offline training scheme.}\vspace{-4mm} \label{fig:offline_ablation} \end{figure} \vspace{0.5mm} \noindent\textbf{B). Offline Training Scheme.} To simulate the offline training scheme, we fix all the weights in the sampling weight map and randomly choose triplets from the CCV-space. We inspect two experiments throughout the entire training process, one of which uses the online sample re-weighting strategy, and the other follows the offline scheme. Both experiments use the \textit{Clas} and symmetry model and are trained on the DexYCB dataset. We report the interim results on DexYCB testing set at certain intervals. As shown in \cref{fig:offline_ablation}, online sample re-weighting helps the models to converge fast and achieve a higher score. \vspace{-1 mm}\subsection{Applications}\label{sec:application} \vspace{-1 mm} We explore the potential application of ArtiBoost and design two studies. \textbf{A).} As real-world data labeling is inefficient and costly, we try to use ArtiBoost to help neural models on training with less amount of real-world labeled data. \textbf{B).} As ArtiBoost is model-agnostic, we show that it can be ported to other HOPE learning frameworks and boost their performance. \vspace{0.5mm}\noindent\textbf{A). Training on Less Real-world Labeled Data.} ~This study trains the neural models using only a small portion of the HO3D training data. Supposing the original amount of data in the HO3D training set is $N$, we set up three different amounts of training set: (1) 10\% $N$ of the original set, (2) 100\% $N$ of the original set, and (3) 10\% $N$ of the original set plus 100\% $N$ of ArtiBoost synthetic poses. As shown in \cref{tab:f01_ho3d_res}, we find that neural networks trained with setting (3) can outperform the network trained with 100\% real-world data. \vspace{0.5mm}\noindent\textbf{B). Porting ArtiBoost to other HOPE Model.} ~In \cref{table:expansibility}, we provide the results of porting ArtiBoost to another HOPE framework proposed by Hasson \etal \cite{hasson2020leveraging} which directly regressed the hand-object poses and focal-normalized camera-space translations. The source training dataset: \textbf{HO3Dv1} \cite{hampali2020ho3dv1} used in \cite{hasson2020leveraging} is an early version of HO3D. We reproduced the results in \cite{hasson2020leveraging} by training their network on the predefined \textbf{v1} set only. We report both the MPJPE in camera space and wrist-relative system. We show in \cref{table:expansibility} that porting ArtiBoost into a camera-space HOPE model significantly improves all metrics. \section{Introduction} \vspace{-1mm} Articulated bodies, such as the human hand, body, and linkage mechanism, can be observed every day in our life. Their joints, links, and movable parts depict the functionality of the articulation body. Extracting their transient configuration from image or video sequence, which is often referred to as \textit{Pose Estimation} \cite{li2021hybrik, chen2021handmesh, li2020ancsh}, can benefit many downstream tasks in robotics and augment reality. Pose estimation for multi-body articulations is especially challenging as it suffers from severe self- or mutual occlusion. In this work, we paid attention to a certain type of multi-body articulations -- composited hand and object poses during their interaction \cite{hasson2019obman, hasson2020leveraging, hasson21homan, yang2021cpf, grady2021contactopt, rhoi2020, liu2021semi, doosti2020hope, hampali2020ho3dv2, huang2020hotnet, karunratanakul2020graspingfield}. Hands are the primary means by which humans manipulate objects in the real-world, and the hand-object pose estimation (HOPE) task holds great potential for understanding human behavior \cite{goyal2017somethingsomething, materzynska2020somethingelse, kwon2021h2o, garcia2018first, tekin2019h+o}. \begin{figure}[!t] \begin{center} \includegraphics[width=0.95\linewidth]{fig/CCVspace.pdf} \end{center}\vspace{-5mm} \caption{\textbf{An intuitive illustration of the CCV-space.}}\vspace{-4.5mm} \label{fig:capture_ccvspace} \end{figure} As the degrees of freedom (DoF) grows, the proper amount of data to cover the pose distribution has grown exponentially. More than the most common articulation bodies, the human hand has 16 joints and approximately 21 DoF. Preparing such diverse training data for the HOPE task can be very challenging. The real-world recording and annotation methods \cite{brahmbhatt2020contactpose, garcia2018first, hampali2020ho3dv2, chao2021dexycb} tend to hinder the pose diversity. For example, the multi-view-based approaches \cite{brahmbhatt2020contactpose, hampali2020ho3dv2} require the subject to maintain a static grasping pose in a video sequence. As a result, their recording process is inefficient, and their pose diversity is insufficient. In contrast, data synthesis is efficient and annotation-free, and has been widely adopted in single-body N-D pose estimation \cite{yan2021ultrapose, varol21_surreact, zimmermann2017rhd, ge20193d, chen2021MobRecon, liu2022towards}. However, these methods are ineligible for multi-body articulation, in which the poses are restricted by mutual contact and obstruction. Data synthesis for HOPE tasks requires us to simulate virtual hand-object interaction (grasp) that mimics the underlying pose distribution of their real-world counterparts. Conventional method either manually articulated \cite{romero2010_handsInAction, Rogez2015_GUN71, corona2020ganhand} the hand model for grasp, or relegated \cite{hasson2019obman, brahmbhatt2019contactgrasp, kokic2020learningTOG} grasp synthesis to an off-the-shelf grasping simulator: GraspIt \cite{graspit}. However, the manual methods are difficult to scale their data in large amounts, and the simulation method also sacrificed the diversity of hand poses.~GraspIt optimizes for hand-crafted grasp metrics \cite{ferrari1992_optimalGrasps} that do not reflect the pose distribution of a 21-DoF dexterous hand. Besides, even with a vast amount of synthetic grasps, not every hand-object configuration is helpful for training. For example, similar configurations may have already been observed multiple times, and those easily discernable samples may have a frequent appearance. Hence, offline data synthesis, without repeatedly communicating with the model during training, is still considered inefficient for a learning task. To address the above issues, we propose an online data enhancement method \textbf{ArtiBoost}, to effectively \textbf{boost} the \textbf{arti}culated hand-object pose estimation via two alternative steps, namely exploration and synthesis. First, to describe the observation of hand-object interaction, we design a three-dimensional discrete space: \textbf{C}omposited hand-object \textbf{C}onfiguration and \textbf{V}iewpoint space (CCV-space) where object types, hand pose, and viewpoint are its components. Second, to construct valid and diverse hand-object poses in CCV-space, we design a fitting-based grasp synthesis method that exploits the contact constraints \cite{yang2021cpf} between hand and object vertices to simulate MANO hand \cite{romero2017embodied} grasping a given object. After the CCV-space is established, we next describe how ArtiBoost enhances the HOPE tasks. At the exploration step, ArtiBoost explores the CCV-space and samples different hand-object-viewpoint triplets from it. Then at the synthesis step, the hand and object in the triplet will be rendered on the image from the viewpoint in the triplet. These synthetic images are mixed with the real-world source images in batches to train the HOPE model. Later, the training losses are fed back to the exploration step and guide it to re-weight the current hard-discernable triplets for the next round of sampling. With such communication in the training loop, ArtiBoost can adaptively adjust its sampling weights to select more hard-discernable data for the current HOPE model. As the HOPE model becomes powerful, it can also continuously promote the current ArtiBoost to evolve. ArtiBoost is model-agnostic, which means it can be plugged into any modern CNN architecture. In this paper, we plug ArtiBoost into a simple classification-based (\eg \cite{sun2018integral}) and regression-based (\eg \cite{boukhayma20193d}) pose estimation model to show its efficacy. For evaluation, we report those models' performance on two challenging HOPE benchmarks: HO3D (v1-v3) \cite{hampali2020ho3dv1 ,hampali2020ho3dv2, hampali2021ho} and DexYCB \cite{chao2021dexycb}. Without whistles and bells, those simple baseline models can outperform the results of previous state-of-the-arts. In this paper, we propose to boost the performance of HOPE task by enhancing the diversity of underlying poses distribution in the training data. We summarize our contributions as follows. (1) To describe the composited hand-object-viewpoint poses distribution, we design the CCV-space. (2) To overcome the scarcity of such poses in the previous dataset, we design a contact-guided grasp synthesis method and simulate both valid and diverse hand-object poses to fill the CCV-space. (3) To help HOPE model efficiently fit the underlying poses distribution, we parallelize the data synthesis with the learning pipeline, leverage the training feedback, and adopt a sample re-weighting strategy. Finally, We conduct extensive experiments to validate our technical contributions (\cref{sec:hope_exp}, \ref{sec:ablation}) and reveal the potential applications (\cref{sec:application}). \section{Method} \vspace{-1 mm}\noindent\textbf{Overview.} This section describes the exploration and synthesis step in ArtiBoost and elaborates the learning framework for the HOPE task. Inside the explorations step, we present the composited configurations and viewpoints space (CCV-space), the key component of ArtiBoost. \begin{figure}[!t] \begin{center} \includegraphics[width=0.91\linewidth]{fig/pipeline_9.pdf} \end{center}\vspace{-6mm} \caption{\textbf{Illustration of the integrated pipeline.} ArtiBoost can be plugged into an arbitrary HOPE framework by modifying the current data loader.} \vspace{-3 mm} \label{fig:pipeline} \end{figure} \vspace{1 mm}\noindent\textbf{Problem Definition.} Given an input image $\mathbf{I} \in \mathbb{R}^{H \times W \times 3}$ that observes a single hand interacting with a certain object, HOPE aims to learn a certain neural network that predict the 3D hand joint locations: $\mathbf{P}_h=\{\mathbf{p}_j\}^{J}_{j=1}$, object centroid locations: $\mathbf{p}_o$ and object rotation: $\mathbf{r}_o \in \mathfrak{so}(3)$, where $\mathbf{p}_j, \mathbf{p}_o \in \mathbb{R}^3$, $J=21$ and the $H \times W$ is the resolution. To train the neural network, we shall firstly prepare a real-world source dataset: $\mathcal{D}_{real}$. ArtiBoost is employed along with the $\mathcal{D}_{real}$. During the training process, ArtiBoost iteratively samples (without replacement) hand-object-viewpoint triplets from the CCV-space: $\mathcal{C}$ based on a weight map: $\mathbf{M}$. Each entry of $\mathbf{M}$ corresponds to a certain triplet in $\mathcal{C}$, and the value in that entry corresponds to the sampling weight of the triplet. Meanwhile, those selected triplets are rendered as a batch of synthetic images at the synthesis step. The synthetic images are mixed with source images from $\mathcal{D}_{real}$. After that, the mixed batch is fed to the HOPE learning framework to complete a forward and backward propagation. When an epoch of training has finished, ArtiBoost performs the sample re-weighting in $\mathbf{M}$ based on the loss value and waits for the next round of training. The whole pipeline is illustrated in \cref{fig:pipeline}. \subsection{Online Exploration in CCV-Space} \vspace{-1mm}\noindent\textbf{The Composited Configuration \& Viewpoint Space.} \noindent HOPE problem commonly involves a certain interacting hand-object configuration that is observed by a certain viewpoint. The input domain of HOPE can thus be narrowed down to three main dimensions: object type, hand pose, and viewpoint direction. To note, the dimension of object type and hand pose are not independent of each other. Given a certain object model, the hand pose that interacts with it depends on the geometry of the model. As shown in \cref{fig:capture_ccvspace}, we define the discrete representation of the input domain as the CCV-space: $\mathcal{S} = \{ (n_o, n_p, n_v) \in \mathbb{N}_+^3 \ | \ n_o \le N_o, \ n_p \le N_p, n_v \le N_v \}$, where the $N_o$, $N_p$ and $N_v$ is the number of object types, discrete poses and viewpoints, respectively. The $(i,j,k)$ item in $\mathcal{S}$ stands for the scenario that the interaction between the $i$-th object and the $j$-th hand pose is observed at the $k$-th camera viewpoint. Next, we will sequentially present the components in CCV-space, namely: hand configuration space (\textbf{C-space}), composited hand-object configuration space (\textbf{CC-space}) and viewpoint space (\textbf{V-space}). \begin{figure*}[ht] \begin{center} \begin{minipage}[ht]{0.18\textwidth} \centering \resizebox{0.93\linewidth}{!}{ \includegraphics[width=1.0\linewidth]{fig/offset_surface.pdf} } \vspace{-0.1em} \caption{Offset surface.} \label{fig:offset_surface} \end{minipage} \quad \begin{minipage}[htp]{0.33\textwidth} \centering \resizebox{0.95\linewidth}{!} { \includegraphics[width=1.0\linewidth]{fig/gripper_pose_initiation.pdf} } \vspace{-1.0mm} \caption{Pre-grasping hand pose.} \label{fig:pregrasping_hand} \end{minipage} \quad \begin{minipage}[htp]{0.30\textwidth} \centering \resizebox{0.87\linewidth}{!} { \includegraphics[width=1.0\linewidth]{fig/CCspace_pairing.pdf} }\vspace{-2.5mm} \caption{Fingertip and its contact point.} \label{fig:paring_fingertips} \end{minipage}\vspace{-7.0mm} \end{center} \end{figure*} \vspace{1mm}\noindent\textbf{C-Space of Valid Hand Pose.} To represent hand, we employ a parametric skinning hand model, MANO \cite{romero2017embodied} which drives a deformable hand mesh with 16 joints rotations $\bm{\theta} \in \mathbb{R}^{16 \times 3}$ and shape parameters $\bm{\beta} \in \mathbb{R}^{10}$. Given the axis-angle forms of rotation, MANO has 48 DoFs that exceed the DoFs allowed by a valid hand pose \cite{lin2000constraintshand}. Fitting or interpolation on the 48 DoFs rotations may encounter abnormal hand pose that is unhealthy for training the HOPE network. Besides, the original MANO's coordinate system is not coaxial with the direction of the hand's kinematic tree, so that the rotation axis is coupled with at least two of the MANO's orthogonal axes. This property makes the pose interpolation more difficult. In the paper, we employ an axis adaptation based on the \textit{twist-splay-bend} coordinate system that was initially proposed by \cite{yang2021cpf}. It enables us to describe the hand pose at each joint as the rotation angle along with one of the specified coordinate axis (\eg \textit{bend}) at this joint. With the axis adaptation, we design three protocols for describing the C-space of valid hand pose: \begin{enumerate}[label={\roman*).},font={\bfseries}] \setlength\itemsep{-0.5 mm} \vspace{-1.0mm} \item According to hand anatomy, all the non-metacarpal joints along the hand's kinematic tree can only have the bending pose. And the five metacarpal joints can only have a combined bending and splaying poses. Any twisting along the pointing direction or splaying at non-metacarpal joints is prohibited. \item For each of the five fingers, the bending poses on their proximal and distal joint are linked and dependent. The bending poses at the five metacarpal joints are independent of other joints. \item The pose of each finger is independent of each other as long as it does not conflict with the protocol \textbf{i)} \& \textbf{ii)}.\vspace{-1.0mm} \end{enumerate} Based on these protocols, the total DoFs in the hand's C-space is 21 (one splaying and two independent bending DoFs for each of the five fingers, plus 6 DoFs at the wrist). Hence, we can describe the whole hand pose by describing the angles of 15 joints' rotation along its specified axis: $\theta_{i}^{\textit{ bend}}$ or $\theta_i^{\textit{ splay}}$, as well as the wrist pose: $\bm{\xi}_{w} \in \mathfrak{se}(3)$. These protocols not only guarantee the diverse and valid hand poses but also ensure these poses are visually plausible. After constructing a valid C-space, we now move on to the composited space that describes hand-object interaction. \vspace{1mm}\noindent\textbf{Composited C-Space of Hand-Object Interaction.} We firstly define the hand-object ``interaction'' as the scenario that satisfies the following requirements: \begin{enumerate*}[label={\roman*)},font={\bfseries}] \item The thumb and at least one or more fingers should be in contact with the object surface \cite{taheri2020grab}; \item The hand and object model should not intersecting with each other; \end{enumerate*} As the hand's interacting pose is highly dependent on its approaching direction and the object's geometry, only a small portion of poses in hand C-space is valid for interaction purposes. Hence instead of searching for valid interaction poses in the entire hand C-space, we turn to explore a discrete space of predefined hand-object poses. We call it composited C-space (CC-space). The goal of CC-space is to increase the diversity of the interacting poses for a given object. For this purpose, we leverage the contact constraints to optimize grasps. This method is divided into three steps. \vspace{0.5mm}\textbf{$\bullet$~1).~}First, given an object model, we construct an offset surface outside of its original surface and uniformly sample $N_w$ points on the offset surface (\cref{fig:offset_surface}). These points will control the wrist position. For each point: $\mathbf{p}_w$, we query its closet vertex on object surface: $\mathbf{v}_o$. The vector: $(\mathbf{v}_o-\mathbf{p}_w)$ represents the approaching direction from hand to object. Then, we construct a prehensile hand pose that mimics the rest state of a parallel jaw gripper (\cref{fig:pregrasping_hand}). This pre-grasping hand is placed at each $\mathbf{p}_w$ as interaction initiation. The $\mathbf{p}_w$'s approaching direction controls the movement of the wrist. Based on a certain $\mathbf{p}_w$, we define the region between $\mathbf{v}_o$ and the farthest vertex that the finger can reach as the object's contact-feasible region. \vspace{0.5mm}\textbf{$\bullet$~2).~}Second, to generate the interacting pose, we fit the fingertips to contact point $\mathbf{v}_c$ chosen from contact-feasible region (\cref{fig:paring_fingertips}). For each $\mathbf{p}_w$, we generate $N^{w}_{p}$ interacting hand poses. To increase diversity, we employ several randomness during fitting: \begin{enumerate*}[label={\roman*)},font={\bfseries}] \item We randomly select thumb and $N$ $(1 \le N \le 4)$ other fingers on hand. Only the selected fingers will participate in fitting. \item For each selected fingers, we set a random minimal reaching radius $r_c$ inside the contact-feasible region. \end{enumerate*} Now the selected fingertip must reach for a contact point $\mathbf{v}_c$ that satisfies: \begin{enumerate*}[label={\roman*)},font={\bfseries}] \item $\|\mathbf{v}_c - \mathbf{p}_w \|_2 \ge r_c$; \item ${\min_{\mathbf{v}_c}}\|\mathbf{v}_c - \mathbf{p}_f \|_2$, where the $\mathbf{p}_f$ is the selected fingertip point. \end{enumerate*} After each selected fingertip is paired with a certain contact point, we will initiate the fitting process. \vspace{0.5mm}\textbf{$\bullet$~3).~}During fitting, we adopt the anchor-based hand model and contact-based cost function defined in CPF \cite{yang2021cpf}. The fitting process aims to minimize the cost brought from unattached fingertips and contact points: the unattached anchor on a fingertip: $\mathbf{p}_f$ will be attracted to its corresponded contact point $\mathbf{v}_c$ on the object, while the intersected anchors will be pushed out. The fitting of hand poses is only performed on the predefined DoFs in the hand's C-space. Thus valid hand pose can be guaranteed. \vspace{1 mm}\noindent\textbf{Viewpoint Space.} For the camera viewpoint, we uniformly sample ${N_{v}}$ viewpoints direction $\mathbf{n}_{v}$ according to the sphere sampling strategy \cite{marsaglia1972choosing}: \begin{equation} \setlength\abovedisplayskip{5pt} \setlength\belowdisplayskip{5pt} \mathbf{n}_v = (\sqrt{1-u^2} \cos(\phi), \sqrt{1-u^2} \sin(\phi), u)^\mathsf{T} \label{eq:sphere_sampling} \end{equation} where $u \sim \mathcal{U}[-1, 1]$ and $\phi \sim \mathcal{U}[0, 2\pi]$, where $\mathcal{U}$ stands for uniform distribution. \vspace{0.5 mm}\noindent\textbf{CCV-space Implementation.} We iteratively fit 300 different interacting poses for each object. Since optimization may result in local minima, we manually discard the poses that \begin{enumerate*}[label={\roman*)},font={\bfseries}] \item exhibit severe inter-penetration between hand and object; \item form an unnatural grasping or interaction. \end{enumerate*} Then, we select up to 100 interacting hand poses per given object. Though the optimization can potentially generate unlimited interacting poses, we find 100 poses (per object) are sufficient to boost current HOPE tasks. In the viewpoints space, we choose $N_u =12$ and $N_{\phi} = 24$, which comprise $N_v = N_u \times N_{\phi} = 288$ different viewpoints. The total number of different (hand-object-viewpoint) triplets depends on the benchmarking dataset. For example, the triplets catered for DexYCB dataset (containing 20 YCB objects) is $N_o \times N_p \times N_v = 20 \times 100 \times 288 = 576,000$. \vspace{1 mm}\noindent\textbf{Weight-guided Sampling Strategy.} In literature, the uniform sampling strategy was widely adopted by synthetic dataset \cite{zimmermann2017rhd, hasson2019obman, mueller2018ganerated}. However, not every sample in the CCV-space contributes equally to the network. Since we hope that those hardly discernable samples shall have a higher frequency of occurrence, we construct a weight map $\mathbf{M} \in \mathbb{R}^{N_o \times N_p \times N_v}$ to guide the sampling in the exploration step. In $\mathbf{M}$, each element $w_i$ stands for the sampling weight of the corresponding item in CCV-space. The probability $p_i$ of a certain item that would be sampled is $p_i = w_i / \sum{w_j}$. We then draws $N_{syn}$ samples from the multinomial distribution $\{ p_i \ | \ p_i = w_i / \sum{w_j};\ \ w_i, w_j \in \mathbf{M} \}$. Based on this strategy, we shall increase the weights for those hardly discernable samples in $\mathbf{M}$ while decreasing the weights for those who are already easy to discern, when we get the feedback from the loss value. \vspace{1 mm}\noindent\textbf{Sample Re-weighting.} After an epoch of training has finished, ArtiBoost chooses those hard discernable items and re-weights their sampling weights. We inspect a percentile-based re-weighting strategy. During the re-weighting phase, each synthetic sample will be assigned a weight update. These updates are multiplied by the original sampling weight in $\mathbf{M}$. Intuitively, we want those hard discernable samples to have high weight. In the percentile-based re-weighting strategy, we calculate the weight update based on the percentile of the samples' Mean Per Joint Position Error (MPJPE) among the whole epoch of synthetic samples. For the $i$-th sample, given by the MPJPE $e_i$ and its percentile $q_i = \frac{e_{\text{max}} - e_i}{e_{\text{max}} - e_{\text{min}}}$, the weight update are calculated from a simple reciprocal heuristic: $\delta w_i = \frac{1}{q_i + 0.5}$. If the sample $i$ has the maximum MPJPE $e_{\text{max}}$ among the synthetic samples in current epoch, its original sampling weight in $\mathbf{M}$ will be multiplied by a maximum update factor $\delta w_i = 2$. If the $i$ has the minimum MPJPE $e_{\text{min}}$, its update factor would be $\delta w_i = 2/3$. We also clamp the updated $\mathbf{M}$ by a upper bound 2.0 and lower bound 0.1 to avoid over imbalance. \vspace{-1 mm}\subsection{Online Synthesis for HOPE task}\label{sec:rendering} \vspace{-1 mm}During the training process, we synthesize the sampled hand-object-viewpoint triplets to RGB images. This synthesis process is task-oriented, as the adaptive sampling decides its composition to cater to the downstream task. Here, we describe the features in the online synthesis step. \vspace{1 mm}\noindent\textbf{Disturbance on the Triplets.} To increase the variance in the pose distribution and thus to improve the network's generalization ability, we add disturbance on the hand poses and viewpoint directions before rendering images. \textit{$\bullet$~~For the hand poses}, we relieve the restriction in protocol \textbf{ii)} in hand C-space, in which the bending angles of distal and proximal joints on each finger are now independent in terms of disturbance. Then, we add a Gaussian disturbance $\mathcal{N}(0, \sigma_1^2)$ on each of the 15 bending angles. Second, for the disturbance on splaying angles, we add a $\mathcal{N}(0, \sigma_2^2)$ on the five metacarpal joints. We empirically set $\sigma_1 = 3$ and $\sigma_2 = 1.5$ degree. To note, this disturbance still subject to the restrictions in protocol \textbf{i)} and \textbf{iii)}, which ensure a valid and prehensile hand configuration. However, these disturbances may cause the inter-penetration between the hand and object models. Hence, we further process the disturbed hand-object pose through the \textit{RefineNet} module in GrabNet \cite{taheri2020grab}, which has the effect of mitigating inter-penetration. Apart from hand pose, the shape of hand also impacts the interaction with the object. Hence we sample the random MANO shape parameters ($\beta \in \mathbb{R}^{10}$) from the distribution of $\mathcal{N}(0, 0.5)$ to formulate the final hand model. \textit{$\bullet$~For the viewpoint directions}, we add three disturbances: $\mathcal{U}(-\delta u, + \delta u)$, $ \mathcal{U}(-\delta \phi, +\delta \phi)$, and $ \mathcal{U}(0, 2\pi)$ on the elevation distance $u$, azimuth angle $\phi$ and the camera in-plane rotation, respectively. In all experiments, we empirically set $\delta u = 0.05$ and $\delta \phi = 7.5$ degree. \vspace{1 mm}\noindent\textbf{Skin Tone \& Textures.} We adopt a state-of-the-art hand skin tone \& texture model: HTML \cite{qian2020html} for realistic appearance on the rendered images. HTML represents the hand's skin color \& texture of as continuous parameters in a PCA space. Before the refined hand model enters the rendering pipeline, we randomly assign it an HTML texture map. We also found that discarding the shadow removal operation in HTML produces more visually plausible images. \vspace{1 mm}\noindent\textbf{Rendering.} We employ the off-the-shelf rendering software: PyRender \cite{pyrender} inside ArtiBoost. The interactive hand and object are the foreground, and the images in COCO \cite{lin2014microsoft} dataset are the background. The pipeline can support rendering of the photorealistic hand and object textured meshes onto a $224 \times 224$ canvas at 120 FPS per graphic card (Titan X), sufficient for us to parallelize the rendering with training. The synthetic data is the combination of four customized items, namely hand-object-viewpoint triplet, background, skin tone, and texture. We show several synthetic images in \cref{fig:dataset_vis}. \vspace{-1mm}\subsection{Learning Framework}\label{sec:framework} \vspace{-2 mm}We adopt two simple baseline network: one is classification-based (\textit{Clas}) and the other regression-based (\textit{Reg}). We employ ResNet-34 \cite{he2016deep} as the backbone in both of them. In \textit{Clas}, we use two de-convolution layers to generates 22 3D-heatmaps that indicate the location of 22 joints (21 hand joints and one object centroid) as likelihood. The 22 3D-heatmaps are defined in a restricted \textit{uvd} space, where \textit{uv} is the pixel coordinates, and \textit{d} is the a wrist-relative depth value. Then, we employ a soft-argmax operator to convert the 3D-heatmaps into joints' \textit{uvd} coordinates. Finally, we transform the joints' \textit{uvd} coordinates into its 3D locations: $\mathbf{P}_h, \mathbf{p}_o$ in camera space by camera intrinsic: $\mathbf{K}$ and wrist location: $\mathbf{p}_w$. In \textit{Reg}, we use multi-layer perceptron (MLP) to regress the MANO parameters: $\bm{\theta}$, $\bm{\beta}$ and object centroid: $^w\mathbf{p}_o$ w.r.t. the wrist. Then we transfer the $\bm{\theta}$, $\bm{\beta}$ to the wrist-relative hand joints: $^w\mathbf{P}_h$ by the MANO model. Finally the $^w\mathbf{P}_h$ and $^w\mathbf{p}_o$ are translated into the camera space by adding a known wrist location: $\mathbf{p}_w$. Both \textit{Clas} and \textit{Reg} adopt another MLP branch to predict object rotation: $\mathbf{r}_o$. Detailed implementations are provided in \textbf{Appx}\xspace. \begin{figure}[t] \includegraphics[width=1.0\linewidth]{fig/render_illu_3.png}\vspace{-3mm} \caption{The rendered images during online synthesis.}\vspace{-6mm} \label{fig:dataset_vis} \end{figure} \vspace{1mm}\noindent\textbf{Loss Function.} The loss function to train the HOPE network consists of four terms. First, we penalize the error of total 22 joints location (21 hand joints and 1 object centroid) in form of $\ell 2$ distance: \begin{equation} \setlength\abovedisplayskip{5pt} \setlength\belowdisplayskip{5pt} \mathcal{L}_{loc} = \frac{1}{22} \sum_{i=1}^{22} \Big \| \mathbf{p}_i - \mathbf{\hat{p}}_i \Big \|^2_2 \label{eq:loc_loss} \end{equation} where $\mathbf{\hat{p}}_i$ denotes the ground-truth joint location. Second, we penalize the error of object rotation in form of $\ell 2$ distance at the eight tightest bounding box corners: \begin{equation} \setlength\abovedisplayskip{5pt} \setlength\belowdisplayskip{5pt} \mathcal{L}_{cor} = \frac{1}{8} \sum_{i=1}^{8} \Big \| \exp(\mathbf{r}_o) * \mathbf{\mathbf{\bar{c}}}_i - \mathbf{\hat{c}}_i \Big \|^2_2 \label{eq:cor_loss} \end{equation} where the $\mathbf{\bar{c}}_i$ and $\mathbf{\hat{c}}_i$ are the object's corners in canonical view and camera view. $\exp(\mathbf{r}_o)$ is the predicted rotation. Third, we adopt the ordinal relation loss to correct the 2D-3D misalignment. $\mathcal{L}_{ord}$ inspects the joint-level depth relation inside a pair of joints: one from the 21 hand joints and the other from the 8 object corners. We penalize the case if the predicted depth relation between the $i$-th hand joint: $\mathbf{{p}_i}$ and the $j$-th corner $\mathbf{{c}_j}$ is misaligned with its ground-truth relation: $\mathds{1}^{ord}_{i,j}$. The $\mathcal{L}_{ord}$ is formulated as: \begin{equation} \setlength\abovedisplayskip{5pt} \setlength\belowdisplayskip{5pt} \mathcal{L}_{ord} = \sum_{j=1}^{8}\sum_{i=1}^{J=21} \mathds{1}^{ord}_{i,j} * \Big | (\mathbf{p}_i - \mathbf{c}_j) \cdot \mathbf{n}_{\perp} \Big | \label{eq:ord_loss} \end{equation} where the $\mathbf{n}_{\perp}$ is the viewpoint direction. Fourth, we borrow a symmetry-aware object corner loss: $\mathcal{L}_{sym}$ from Hampali \etal \cite{hampali2021handsformer}: \begin{equation} \setlength\abovedisplayskip{5pt} \setlength\belowdisplayskip{5pt} \mathcal{L}_{sym} = \min_{\mathbf{R} \in \mathcal{S}} \frac{1}{8} \sum_{i=1}^{8} \Big \| \exp(\mathbf{r}_o)* \mathbf{\mathbf{\bar{c}}}_i - \exp(\mathbf{\hat{r}}_o) \mathbf{R} * \mathbf{\mathbf{\bar{c}}}_i \Big \|^2_2 \label{eq:sym_loss} \end{equation} where $\exp(\mathbf{\hat{r}}_o)$ denotes object's ground-truth rotation matrix. Given an object, the set $\mathcal{S}$ contains all the valid rotation matrices based on the object's predefined symmetry axes. The overall loss is a weighted sum of the four terms: \begin{equation} \setlength\abovedisplayskip{5pt} \setlength\belowdisplayskip{5pt} \mathcal{L}_{\textit{HOPE}} = \mathcal{L}_{loc} + \lambda_1 \mathcal{L}_{cor} + \lambda_2\mathcal{L}_{ord} + \lambda_3\mathcal{L}_{sym} \label{eq:overall_loss} \end{equation} where the $\lambda_{1\sim3}$ are the hyper-parameters. \section{Related Work} \vspace{-1.0mm}\noindent\textbf{Hand-Object Pose Estimation.} As some HOPE tasks are closely related to hand pose estimation (HPE) tasks \cite{wan2019self, yang2021semihand}, we firstly review several HPE methods. According to its output form, single RGB-based 3D HPE can be categorized into three types: image-to-pose (I2P) \cite{yang2019disentangling}, image-to-geometry (I2G) \cite{chen2021handmesh, tang2021handar}, and hybrid \cite{zhou2020monocular}. While the I2P only focuses on the joints' pose only, the I2G focus on recovering the full hand geometry (pose and shape). Meanwhile, recent works \cite{zhou2020monocular, yang2020bihand, li2021hybrik} showed that I2G could be hybridized to I2P through neural inverse kinematics (IK). Second, we explore several HOPE methods. Regarding the learning-based methods, some aimed to predict the hand-object poses in a unified model \cite{hasson2020leveraging, liu2021semi}, while the others focused on recovering hand-object interaction based on contact modeling \cite{yang2021cpf, grady2021contactopt}. As for the learning-free methods, Hasson \etal \cite{hasson21homan} and Cao \etal \cite{rhoi2020} proposed to aggregate the visual cues from object detection, HPE, and instance segmentation to acquire the optimal hand-object configuration. This paper adopts two simple learning baseline networks of two paradigms: classification (joints as 3D heatmap) and regression (joints from pose and shape predictions). We show that with ArtiBoost, even simple baseline networks can outperform previous sophisticated CNN designs. \vspace{1.0mm}\noindent\textbf{Data Synthesis for Pose Estimation.} Using synthetic data to increase pose variants has been widely adopted in single-body N-D pose estimation tasks, such as human pose \cite{varol21_surreact, yan2021ultrapose, chen2016synthesizing}, hand pose \cite{zimmermann2017rhd, ge20193d, chen2021MobRecon}, 6D object pose \cite{kehl2017ssd6d, tekin2018SeamlessSingleShot, sundermeyer2018implicit}, and 7D articulated object pose \cite{li2020ancsh, liu2022towards}, \etc. These methods utilized the kinematic model of the articulated bodies, drive constrained joints' motion, and rendered the current model from different viewpoints. Unlike single-body pose estimation, Data synthesis for HOPE (multi-body) task not only needs to consider the joints limit, but also to obey the physical constraints brought from mutual contact and obstruction. In terms of composited hand-object pose synthesis, there are also three genres included in the literature. The manual labeling methods \cite{romero2010_handsInAction, Rogez2015_GUN71, corona2020ganhand} articulated a hand model to achieve grasp; The metric-based methods \cite{hasson2019obman, kokic2020learningTOG,brahmbhatt2019contactgrasp} leveraged grasp simulator \cite{graspit} to simulate hand poses subjected to physical grasping metrics; The data-driven methods \cite{taheri2020grab, jiang2021graspTTA, karunratanakul2020graspingfield} trained conditional VAE that generates new grasps. This paper presents an automatically contact-guided optimization method to construct valid and diverse poses of hand-object interaction. \vspace{1.0mm}\noindent\textbf{Exploration for Hard Examples,} also called ``hard example$/$negative mining'', has been proven effective for various computer vision tasks, such as object detection \cite{hard_obj_det1, hard_obj_det2}, person re-id \cite{hard_person_reid1}, head pose estimation\cite{Kuhnke2019DeepHP}, face recognition \cite{hard_face1}, and deep metric learning \cite{hard_deep_metric1, hard_deep_metric3}. Generally speaking, the basic ideology of hard examples mining is that if a prediction of a certain data sample exhibits a large error under a certain metric, then this data sample is not properly learned by the learning algorithm. By adding such data samples to the training batch can help the learning converge faster. Recent work exploited a generative adversarial model \cite{gong2021poseaug} to acquire harder samples based on error feedback training. However, it must pay non-trivial efforts on the adversarial part to ensure samples' validity. In this paper, we adopt a simple yet effective sample re-weighting strategy that adaptively selects those hard-discernable training triplets (hand-object-viewpoint) for training. \section{The Training Details} \vspace{-1 mm} The backbones of classification-based (\textit{Clas}) and regression-based (\textit{Reg}) baseline networks are initialized with ImageNet \cite{deng2009imagenet} pretrained model. In \textit{Clas}, the output resolution of 3D-heatmaps is 28 $\times$ 28 $\times$ 28. The MLP branch that predicts object rotation adopts three fully-connected layers with 512, 256 and 128 neurons for each, and a final layer of 6 neurons that predict the continuity representation \cite{zhou2019continuity} of object rotation: $\mathbf{r}_o \in \mathfrak{so}(3)$. We train the network 100 epochs with Adam optimizer and learning rate of $ 5\times 10^{-5}$. The training batch size across all the following experiments is 64 per GPU and 2 GPUs in total. The framework is implemented in PyTorch. All the object models and textures are provided by the original dataset. For all the training batches, the blended rate of original real-world data and ArtiBoost synthetic data is approximately $1:1$. We empirically find that this real-synthetic blended rate achieves the best performance. \section{Objects' Symmetry Axes}\label{sec:symmetry_axes} In the hand-object interaction dataset, it is far more challenging to predict the pose of an object than in the dataset only contains objects, since the objects are often severely occluded by the hand. Therefore, we relax the restrictions of the objects' symmetry axes following the practices in \cite{chao2021dexycb,hampali2021handsformer}. Supposing the set $\mathcal{S}$ contains all the valid rotation matrices based on the object's predefined symmetry axes, we calculate $\mathcal{S}$ with the following step: \begin{enumerate}[label={\arabic*)},font={\bfseries},leftmargin=*] \setlength\itemsep{-1 mm} \item Firstly, as shown in Fig~\ref{fig:pca_obj}, we align the object to its principal axis of inertia. \item Secondly, we define the axis $\mathbf{n}$ and angle $\theta$ of symmetry in Tab~\ref{tab:def_sym} under the aligned coordinate system, where the object's geometry does not change when rotate this object by an angle of $\theta$ around $\mathbf{n}$. Here we get the predefined rotation matrix $\mathbf{R}_{def} = \exp(\theta\mathbf{n})$. \item To get a more accurate rotation matrix $\mathbf{R}$, we use the Iterative Closest Point (ICP) algorithm to fit a $\Delta \mathbf{R}$. The ICP minimizes the difference between $\Delta \mathbf{R} * \mathbf{R}_{def} * \mathbf{V}_o$ and $\mathbf{V}_o$, where $\mathbf{V}_o$ is the point clouds on object surface. Finally, we have $\mathbf{R} = \Delta \mathbf{R} * \mathbf{R}_{def}, \mathbf{R} \in \mathcal{S}$. \end{enumerate} \begin{figure}[h] \begin{center} \includegraphics[width=1.0\linewidth]{fig/supp_axes.pdf}\vspace{-3mm} \end{center} \caption{\textbf{YCB objects' principal axis of inertia.} The x, y and z axis are colored in red, green and blue, respectively.}\vspace{-3mm} \label{fig:pca_obj} \end{figure} \begin{table}[h] \renewcommand{\arraystretch}{1.0} \begin{center} \resizebox{0.95\linewidth}{!}{ \begin{tabular}{c|c|c} \toprule Objects & Axes: $\mathbf{n}$ & Angle: $\theta$ \\ \midrule 002\_master\_chef\_can & x, y, z & $180^\circ$, $180^\circ$, $\infty$\\ 003\_cracker\_box & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$\\ 004\_sugar\_box & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$\\ 005\_tomato\_soup\_can & x, y, z & $180^\circ$, $180^\circ$, $\infty$\\ 006\_mustard\_bottle & z & $180^\circ$\\ 007\_tuna\_fish\_can & x, y, z & $180^\circ$, $180^\circ$, $\infty$\\ 008\_pudding\_box & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$ \\ 009\_gelatin\_box & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$ \\ 010\_potted\_meat\_can & x, y, z & $180^\circ$, $180^\circ$, $180^\circ$ \\ 024\_bowl & z & $\infty$\\ 036\_wood\_block & x, y, z & $180^\circ$, $180^\circ$, $90^\circ$ \\ 037\_scissors & z & $180^\circ$\\ 040\_large\_marker & x, y, z & $180^\circ$, $\infty$, $180^\circ$\\ 052\_extra\_large\_clamp & x & $180^\circ$\\ 061\_foam\_brick & x, y, z & $180^\circ$, $90^\circ$, $180^\circ$ \\ \bottomrule \end{tabular} } \end{center}\vspace{-5mm} \caption{\textbf{YCB objects' axes of symmetry}. $\infty$ indicates the object is revolutionary by the axis.}\vspace{-3mm} \label{tab:def_sym} \end{table} \begin{table*}[ht] \renewcommand{\arraystretch}{1.0} \begin{center} \resizebox{0.95\linewidth}{!}{ \begin{tabular}{c|c|c|c|c|c} \toprule Objects & Our \textit{Clas} sym & Our \textit{Clas} sym \textbf{+ Arti} & Objects & Our \textit{Clas} sym & Our \textit{Clas} sym \textbf{+ Arti}\\ \midrule 002\_master\_chef\_can & 27.62 & \textbf{25.59} & 003\_cracker\_box & 63.68 & \textbf{46.13}\\ 004\_sugar\_box & 48.42 & \textbf{39.20} & 005\_tomato\_soup\_can & 33.31 & \textbf{31.90}\\ 006\_mustard\_bottle & 35.16 & \textbf{32.01} & 007\_tuna\_fish\_can & 24.54 & \textbf{23.81}\\ 008\_pudding\_box & 39.92 & \textbf{35.04} & 009\_gelatin\_box & 45.99 & \textbf{37.81}\\ 010\_potted\_meat\_can & 41.44 & \textbf{36.47} & 011\_banana & 98.69 & \textbf{79.87}\\ 019\_pitcher\_base & 105.66 & \textbf{84.82} & 021\_bleach\_cleanser & 91.66 & \textbf{72.31}\\ 024\_bowl & \textbf{31.74} & 32.37 & 025\_mug & 65.46 & \textbf{54.28}\\ 035\_power\_drill & 74.95 & \textbf{52.70} & 036\_wood\_block & 51.24 & \textbf{50.69}\\ 037\_scissors & 88.10 & \textbf{66.52} & 040\_large\_marker & 30.76 & \textbf{29.33}\\ 052\_extra\_large\_clamp & 78.87 & \textbf{55.87} & 061\_foam\_brick & 34.23 & \textbf{31.53}\\ \bottomrule \end{tabular} } \end{center} \vspace{-5mm} \caption{Full MSSD results ($mm$) on \textbf{DexYCB} testing set.}\vspace{-1mm} \label{tab:full_dexycb} \end{table*} \begin{figure*}[!t] \begin{center} \includegraphics[width=1.0\linewidth]{fig/supp_qualitative.pdf} \end{center} \vspace{-5mm} \caption{(\textbf{Best view in color}) More qualitative results on \textbf{HO3D} (\engordnumber{1} $\sim$ \engordnumber{3} rows) and \textbf{DexYCB} (\engordnumber{4} $\sim$ \engordnumber{8} rows) datasets.}\vspace{-1mm} \label{fig:supp_qua} \end{figure*} \section{Additional Results}\label{sec:add_results} We demonstrate 20 YCB objects' MSSD on DexYCB in \cref{tab:full_dexycb}. With ArtiBoost, our network can predict a more accurate pose for almost every object. More qualitative results on HO3D and DexYCB testing set are shown in \cref{fig:supp_qua}. \end{appendices}
{'timestamp': '2022-03-28T02:13:50', 'yymm': '2109', 'arxiv_id': '2109.05488', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05488'}
arxiv
\section*{Broader Impact} The algorithmic processes behind modern search engines, with extensive use of machine learning algorithms, have great power to determine users' access to information~\cite{764d88eb1b1043249afc97900350d6a6}. Our research provides evidence that unintentionally using image search models trained either on in-domain image retrieval data sets or massive corpora across the internet may lead to unequal inclusiveness between males and females in image search results, even when the search terms are gender-neutral. This inequity can and do have significant impacts on shaping and exaggerating gender stereotype in people's minds~\cite{gender-image-search}. This work offers new methods for mitigating gender bias in multimodal models, and we regard the algorithms proposed in this paper have the potentials to be deployed in real-world systems. We conjecture that our methods may contribute to driving the development of responsible image search engines with other fairness issues. For instance, we would encourage future works to understand and mitigate the risks arising from other social biases, like racial bias, in image search results. We would also encourage researchers to explore whether the methodology presented in this work could be generalized to quantify and mitigate other bias measures. Our work has limitations. The gender bias measures and the debiasing methods proposed in this study require acquiring the gender labels of images. Our method for identifying the gender attributes of people portrayed in the images is limited: we make use of the contextual cues in the human-annotated captions from the image datasets. The accuracy of such a proxy-based method heavily relies on the coverage of gendered nouns and the inclusiveness of gendered language in the original human annotations. The corruption of gender labels, due to missing gendered words or inappropriate text pre-processing steps, may introduce biases we have not foreseen into the evaluated metrics. Additionally, the gendered word lists are collected from English corpora and may differ in other languages or cultures. It is possible that blind application of our methods by improperly acquiring the gender labels may create image search models that produce even greater inequality, which is very much discouraged. This limitation arises from the unavailability of such sensitive attributes in the source datasets. The lack of relevant data for studying gender bias in image search, and the concerns about how to acquire the gender attributes while preserving the privacy of people concerned, is itself an important question in this area. We believe this research would benefit when richer datasets become available. \section*{Acknowledgements} The authors would like to thank anonymous reviewers for their constructive comments. This work is supported by the UC Santa Cruz Startup Funding, and the National Science Foundation (NSF) under grants IIS-2040800 and CCF-2023495. \section{Introduction}\label{sec:introduction} Internet information is shaping people's minds. The algorithmic processes behind modern search engines, with extensive use of machine learning, have great power to determine users' access to information~\cite{764d88eb1b1043249afc97900350d6a6}. These information systems are biased when results are systematically slanted in unfair discrimination against protected groups~\cite{BiasInComputerSystems}. Gender bias is a severe fairness issue in image search. \cref{fig:case_study} shows an example: given a gender-neutral natural language query ``a person is cooking", only 2 out of 10 images retrieved by an image search model~\cite{CLIP} depict females, while equalized exposure for male and female is expected. Such gender-biased search results are harmful to society as they change people's cognition and worsen gender stereotypes~\cite{gender-image-search}. Mitigating gender bias in image search is imperative for social good. \begin{figure*} \begin{center} \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth, height=\linewidth]{fig/top5_cooking/4469735380.jpg} \end{subfigure} \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth,height=\linewidth]{fig/top5_cooking/17186135.jpg} \end{subfigure} \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth,height=\linewidth]{fig/top5_cooking/400598822.jpg} \end{subfigure} \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth,height=\linewidth]{fig/top5_cooking/5510073103.jpg} \end{subfigure} \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth,height=\linewidth]{fig/top5_cooking/2709044515.jpg} \end{subfigure} \vskip0.15\baselineskip \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth, height=\linewidth]{fig/top5_cooking/86350713.jpg} \end{subfigure} \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth,height=\linewidth]{fig/top5_cooking/3091786541.jpg} \end{subfigure} \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth,height=\linewidth]{fig/top5_cooking/238177432.jpg} \end{subfigure} \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth,height=\linewidth]{fig/top5_cooking/180209719.jpg} \end{subfigure} \begin{subfigure}[b]{0.19\linewidth} \centering \includegraphics[width=\linewidth,height=\linewidth]{fig/top5_cooking/5491874786.jpg} \end{subfigure} \end{center} \caption{Gender bias in image search. We show the top-10 retrieved images for searching ``a person is cooking'' on the Flickr30K~\cite{Flickr30K} test set using a state-of-the-art model~\cite{CLIP}. Despite the gender-neutral query, only 2 out of 10 images are depicting female cooking.} \label{fig:case_study} \end{figure*} In this paper, we formally develop a framework for quantifying gender bias in image search results, where text queries in English\footnote{This study is conducted on English corpora. We will assume the text queries are all English queries hereafter.} are made gender-neutral, and gender-balanced search images are expected for models to retrieve. To evaluate model fairness, we use the normalized difference between masculine and feminine images in the retrieved results to represent gender bias. We diagnose the gender bias of two primary families of multimodal models for image search: (1) the specialized models that are often trained on in-domain datasets to perform text-image retrieval, and (2) the general-purpose representation models that are pre-trained on massive image and text data available online and can be applied to image search. Our analysis on MS-COCO~\cite{Lin2014MicrosoftCC} and Flickr30K~\cite{Flickr30K} datasets reveals that both types of models lead to serious gender bias issues (e.g., nearly 70\% of the retrieved images are masculine images). To mitigate gender bias in image search, we propose two novel debiasing solutions for both model families. The specialized in-domain training methods such as SCAN~\cite{SCAN} often adopt contrastive learning to enforce image-text matching by maximizing the margin between positive and negative image-text pairs. However, the gender distribution in the training data is typically imbalanced, which results in unfair model training. Thus we introduce a fair sampling (\emph{FairSample}) method to alleviate the gender imbalance during training without modifying the training data. Our second solution aims at debiasing the large, pre-trained multimodal representation models, which effectively learn pre-trained image and text representations to accomplish down-stream applications~\cite{NEURIPS2019_ddf35421,iGPT,SimCLR,gan2020large,chen2020uniter,CLIP}. We examine whether the representative CLIP model~\cite{CLIP} embeds human biases into multimodal representations when they are applied to the task of image search. Furthermore, we propose a novel post-processing feature clipping approach, \emph{clip}, that effectively prunes out features highly correlated with gender based on their mutual information to reduce the gender bias induced by multimodal representations. The \emph{clip} method does not require any training and is compatible with various pre-trained models. We evaluate both debiasing approaches on MS-COCO and Flickr30K and find that, on both benchmarks, the proposed approaches significantly reduce the gender bias exhibited by SCAN and CLIP models when evaluated on the gender-neutral corpora, yielding fairer and more gender-balanced search results. In addition, we evaluate the similarity bias of the CLIP model in realistic image search results for occupations on the internet, and observe that the post-processing methods mitigate the discrepancy between gender groups by a large margin. Our contributions are four-fold: (1) we diagnose a unique gender bias in image search, especially for gender-neutral text queries; (2) we introduce a fair sampling method to mitigate gender bias during model training; (3) we also propose a novel post-processing clip method to debias pre-trained multimodal representation models; (4) we conduct extensive experiments to analyze the prevalent bias in existing models and demonstrate the effectiveness of our debiasing methods. \section{Mitigating Gender Bias in Image Search}\label{sec:methodology} There are two fashions of multimodal models for the image search task. One is to build a specialized model that could embed image and text into representation vectors with measurable similarity scores. The other is to use general-purpose image-text representations pre-trained on sufficiently big data and compute a particular distance metric. We focus on two representative models, SCAN~\cite{SCAN} and CLIP~\cite{CLIP}, for both fashions. For the first fashion, we propose an in-processing learning approach to ameliorate the unfairness caused by imbalanced gender distribution in training examples. This approach builds on contrastive learning but extends with a \textit{fair sampling} step. The in-processing solution requires full training on in-domain data examples. For the second fashion, we propose a post-processing feature \textit{clipping} technique to mitigate bias from an information-theoretical perspective. This approach is compatible with pre-trained models and is light to implement without repeating training steps. \subsection{In-processing Debiasing: Fair Sampling}\label{sec:fairsample} Image search models in the first fashion are often trained under the contrastive learning framework~\cite{contrastive-learning-review}. For our in-processing debiasing approach, we now explain the two primary components, contrastive learning and fair sampling, within our context. \paragraph{Contrastive Learning} We start by formally introducing the standard contrastive learning framework commonly used in previous works~\cite{SCAN,Chen2020AdaptiveOQ} for image-text retrieval. Given a batch of $N$ image-text pairs $\batch = \{(v_n,c_n)\}_{n=1}^N$, the model aims to maximize the similarity scores of matched image-text pairs (positive pairs) while minimizing that of mismatched pairs (negative pairs). The representative SCAN model~\cite{SCAN}, denoted as $S(v, c)$ outputting a similarity score between image and text, is optimized with a standard hinge-based triplet loss: \begin{align} \mathcal{L}_{i-t} & = \sum_{(v, c) \in \batch} [\gamma - S(v, c) + S(v, \tilde{c})]_+ \\ \mathcal{L}_{t-i} & = \sum_{(v, c) \in \batch} [\gamma - S(v, c) + S(\tilde{v}, c)]_+ \end{align} where $\gamma$ is the margin, $\tilde{v}$ and $\tilde{c}$ are negative examples, and $[\cdot]_+$ denotes the ramp function. $\mathcal{L}_{i-t}$ corresponds to image-to-text retrieval, while $\mathcal{L}_{t-i}$ corresponds to text-to-image retrieval (or image search). Common negative sampling strategy includes selecting all the negatives~\cite{HuangWW17}, selecting hard negatives of highest similarity scores in the mini-batch~\cite{faghri2018vse++}, and selecting hard negatives from the whole training data~\cite{Chen2020AdaptiveOQ}. Minimizing the margin-based triplet loss will make positive image-text pairs closer to each other than other negative samples in the joint embedding space. \paragraph{Fair Sampling} One major issue in the contrastive learning framework is that the gender distribution in a batch of image-text pairs is typically imbalanced. Hence, the negative samples will slant towards the majority group, leading to systematic discrimination. To address this problem, we propose a fair sampling strategy. We split the batch of image-text pairs into masculine and feminine pairs based on the image's gender attribute: \begin{align*} \imageset_\male & = \{v \mid g(v) = \male, (v, c) \in \batch\} \\ \imageset_\female & = \{v \mid g(v) = \female, (v, c) \in \batch\} \\ \imageset_\neutral & = \{v \mid g(v) = \neutral, (v, c) \in \batch\} \end{align*} For every positive image and text pair $(v, c) \in \batch$, we identify the gender information contained in the query $c$. If the natural language query is gender-neutral, we sample a negative image from the set of male and female images with probability $\frac{1}{2}$, respectively. Otherwise, we keep the primitive negative sampling selection strategy for keeping the model's generalization on gender-specific queries. Let $\batch^\ast$ be the batch of gender-neutral image-text pairs, the image search loss with fair sampling is: \begin{multline} \mathcal{L}_{t-i}^{fair} = \sum_{(v, c) \in \batch^\ast}(\frac{1}{2}\Expectation_{\bar{v} \in \imageset_\male} [\gamma - S(v, c) + S(\bar{v}, c)]_+ \\ \quad + \frac{1}{2}\Expectation_{\bar{v} \in \imageset_\female} [\gamma - S(v, c) + S(\bar{v}, c)]_+) \\ + \sum_{(v, c) \in \batch / \batch^\ast} [\gamma - S(v, c) + S(\tilde{v}, c)]_+ \end{multline} Empirically, we find that if we thoroughly apply the Fair Sampling strategy, the recall performance drops too much. To obtain a better tradeoff, we use a weight $\alpha$ to combine the objectives \[ \alpha \mathcal{L}_{t-i}^{fair} + (1-\alpha)\mathcal{L}_{t-i} \] as the final text-to-image loss function. We do not alter the sentence retrieval loss $\mathcal{L}_{i-t}$ during training for preserving generalization. \subsection{Post-processing Debiasing: Feature Clipping based on Mutual Information}\label{sec:prune} Pre-training methods have shown promising zero-shot performance on extensive NLP and computer vision benchmarks. The recently introduced CLIP model~\cite{CLIP} was pre-trained on an enormous amount of image-text pairs found across the internet to connect text and images. CLIP can encode image and text into $d$-dimensional embedding vectors, based on which we can use cosine similarity to quantify the similarity of image and text pairs. In this work, we find that the pre-trained CLIP model reaches the state-of-the-art performance but exhibits large gender bias due to training on uncurated image-text pairs collected from the internet. Although \citet{CLIP} released the pre-trained CLIP model, the training process is almost unreproducible due to limitations on computational costs and massive training data. In order to avoid re-training of the CLIP model, we introduce a novel post-processing mechanism to mitigate the representation bias in the CLIP model. We propose to ``clip'' the dimensions of feature embeddings that are highly correlated with gender information. This idea is motivated by the fact that an unbiased retrieve implies the independence between the covariates (active features) and sensitive attributes (gender)~\cite{barocas-hardt-narayanan}. Clipping the highly correlating covariates will return us a relatively independent and neutral set of training data that does not encode hidden gender bias. \begin{algorithm}[tb] \small \caption{\textit{clip} algorithm} \label{algo:prune} \begin{algorithmic} \REQUIRE Index set $\Omega = \{1, ..., d\}$, number of clipped features $0 \leq m < d$ \STATE $\mathcal{Z} \leftarrow \O$; \FOR {$i=1$ to $d$} \STATE Estimate mutual information $I(V_i; g(V))$; \ENDFOR \FOR {$j=1$ to $m$} \STATE $z \leftarrow \argmax \{I(V_i; g(V)): i \in \Omega / \mathcal{Z}\}$; \STATE $\mathcal{Z} \leftarrow \mathcal{Z} \cup \{z\}$; \ENDFOR \RETURN Index set of clipped features $\mathcal{Z}$ \end{algorithmic} \end{algorithm} The proposed \emph{clip} algorithm is demonstrated in \cref{algo:prune}, and we explain the key steps below. Let $\Omega = \{1,...,d\}$ be the full index set. We use $V = V_\Omega = [V_1, V_2, ..., V_d]$ to represent the variable of $d$-dimensional encoding image vectors and $g(V) \in \{\male, \female, \neutral\}$ to represent the corresponding gender attribute. The goal is to output the index set $\mathcal{Z}$ of clipped covariates that reduce the dependence between representations $V_{\Omega/\mathcal{Z}}$ and gender attributes $g(V)$. We measure the correlation between each dimension $V_i$ and gender attribute $g(V)$ by estimating their mutual information $I(V_i;g(V))$~\cite{estimate-mutual-information}: \begin{equation} I(V_I;g(V)) = D_{\text{KL}}(\Probability_{(V_i,g(V))}\|\Probability_{V_i} \otimes \Probability_{g(V)}) \end{equation} where $D_{\text{KL}}$ is the KL divergence~\cite{kullback1951}, $\Probability_{(V_i,g(V))}$ indicates the joint distribution, $\Probability_{V_i}$ and $\Probability_{g(V)}$ indicate their marginals. Next, we greedily clip $m$ covariates with highest mutual information, and construct $(d-m)$-dimensional embedding vectors $V_{\Omega / \mathcal{Z}}$. $m$ is a hyper-parameter that we will experimentally find to best trade-off accuracy and the reduced gender bias, and we show how the selection of $m$ affects the performance in \cref{sec:trade-off}. To project text representations, denoted by variable $C$, into the same embedding space, we also apply the index set $\mathcal{Z}$ to obtain clipped text embedding vectors $C_{\Omega / \mathcal{Z}}$. The clipped image and text representations, denoted by $\vec{v}^\ast$ and $\vec{c}^\ast$, will have a relatively low correlation with gender attributes due to the ``loss'' of mutual information. Then we compute the cosine similarity between image and text by substituting $\vec{v}^\ast$ and $\vec{c}^\ast$ into \cref{eq:similarity}: \begin{equation} S(v, c) = \frac{\vec{v}^\ast \cdot \vec{c}^\ast}{\|\vec{v}^\ast\| \|\vec{c}^\ast\|} \end{equation} Finally, we rank the images based on the cosine similarity between the clipped representations. \section{Experimental Setup}\label{sec:experiment} \subsection{Datasets} We evaluate our approaches on the standard MS-COCO~\cite{Chen2015MicrosoftCC} and Flickr30K~\cite{Flickr30K} datasets. Following \citet{Karpathy2017DeepVA} and \citet{faghri2018vse++}, we split MS-COCO captions dataset into 113,287 training images, 5,000 validation images and 5,000 test images.\footnote{The data is available at \url{cocodataset.org}.} Each image corresponds to 5 human-annotated captions. We report the results on the test set by averaging over five folds of 1K test images or evaluating the full 5K test images. Flickr30K consists of 31,000 images collected from Flickr.\footnote{The data is available at \url{http://bryanplummer.com/Flickr30kEntities/}.} Following the same split of \citet{Karpathy2017DeepVA,SCAN}, we select 1,000 images for validation, 1,000 images for testing, and the rest of the images for training. \paragraph{Identifying Gender Attributes of Images} Sensitive attributes such as gender are often not explicitly annotated in large-scale datasets such as MS-COCO and Flickr30K, but we observe that implicit gender attributes of images can be extracted from their associated human-annotated captions. Therefore, we pre-define a set of masculine words and a set of feminine words.\footnote{We show the word lists in \cref{app:word-list}.} Following~\citet{Zhao2017MenAL} and~\citet{Burns2018WomenAS} we use the ground-truth annotated captions to identify the gender attributes of images. An image will be labeled as ``male'' if at least one of its captions contains masculine words and no captions include feminine words. Similarly, an image will be labeled as ``female" if at least one of its captions contains feminine words and no captions include masculine words. Otherwise, the image will be labeled as ``gender-neutral". \begin{figure*}[ht] \begin{subfigure}[b]{0.32\linewidth} \centering \includegraphics[width=\linewidth]{fig/coco_test_gender_difference.pdf} \caption{MS-COCO 1K Test Set.} \end{subfigure} \hfill \begin{subfigure}[b]{0.32\linewidth} \centering \includegraphics[width=\linewidth]{fig/coco_testall_gender_difference.pdf} \caption{MS-COCO 5K Test Set.} \end{subfigure} \hfill \begin{subfigure}[b]{0.32\linewidth} \centering \includegraphics[width=\linewidth]{fig/f30k_gender_difference.pdf} \caption{Flick30K Test Set.} \end{subfigure} \caption{Gender bias analysis with different top-$K$ results. } \label{fig:gender-bias} \end{figure*} \subsection{Models} We compare the fairness performance of the following approaches: \squishlist \item \textbf{SCAN}~\cite{SCAN}: we use the official implementation for training and evaluation\footnote{The code is available at \url{https://github.com/kuanghuei/SCAN}.}. \item \textbf{FairSample}: we apply the fair sampling method proposed in \cref{sec:fairsample} to the SCAN framework and adopt the same hyper-parameters suggested by \citet{SCAN} for training. \item \textbf{CLIP}~\cite{CLIP}: we use the pre-trained CLIP model released by OpenAI.\footnote{The pre-trained model is available at \url{https://github.com/openai/CLIP}.} The model uses a Vision Transformer~\cite{dosovitskiy2021an} as the image encoder and a masked self-attention Transformer~\cite{attention} as the text encoder. The original model produces 500-dimensional image and text vectors. \item \textbf{CLIP-clip}: we apply the feature pruning algorithm in \cref{sec:prune} to the image and text features generated by the CLIP model. We set $m=100$ and clip the image and text representations into 400-dimensional vectors. \squishend Note that SCAN and FairSample are trained and tested on the in-domain MS-COCO and Flickr30K datasets, while the pre-trained CLIP model is directly tested on MS-COCO and Flickr30K test sets without fine-tuning on their training sets (same for CLIP-clip as it simply drops CLIP features). \subsection{Evaluation} \paragraph{Gender-Neutral Text Queries} In this study, we focus on equalizing the search results of gender-neutral text queries. In addition to the existing gender-neutral captions in the test sets, we pre-process those gender-specific captions to construct a purely gender-neutral test corpus to guarantee a fair and large-scale evaluation. For every caption, we identify all these gender-specific words and remove or replace them with corresponding gender-neutral words. We show some pre-processing examples in \cref{tab:construct-neutral-query}. \paragraph{Metrics} As introduced in \cref{sec:measure-gender-bias}, we employ the fairness metric in \cref{eq:fairness}, Bias@K, to measure the gender bias among the top-K images. In addition, following standard practice, we measure the retrieval performance by Recall@K, defined as the fraction of queries for which the correct image is retrieved among the top-K images. \section{Debiasing Results} \subsection{Main Results on MS-COCO \& Flickr30K} We report the results comparing our debiasing methods and the baseline methods in \cref{tab:main_result}. \paragraph{Model Bias} Although the pre-trained CLIP model is evaluated without fine-tuning, we observe that it achieves a comparable recall performance with the SCAN model on MS-COCO and dominates the Flickr30K dataset. However, both models suffer from severe gender bias. Especially, the $\bias@10$ of the SCAN model on Flickr30K is $0.3960$, meaning nearly $70\%$ of the retrieved gender-specific images portray men and only $30\%$ portray women. Similarly, the CLIP model achieves $0.2648$ gender bias on MS-COCO 1K test set, indicating about $6.4$ out of 10 retrieved images portray men while about $3.6$ out of 10 portray women. Given that all of the testing text queries are gender-neutral, this result shows that severe implicit gender bias exists in image search models. \begin{table*}[t] \small \setlength{\tabcolsep}{2.5pt} \centering \begin{tabular}{l l c c c c c c } \toprule & & \multicolumn{3}{c}{Gender Bias$\downarrow$} & \multicolumn{3}{c}{Recall$\uparrow$} \\ \cmidrule(lr){3-5}\cmidrule(lr){6-8} Dataset & Method & Bias@1 & Bias@5 & Bias@10 & Recall@1 & Recall@5 & Recall@10 \\ \midrule \multirow{4}{*}{COCO1K} & SCAN & .1250 & .2044 & .2506 & 47.7 & $82.0$ & $\mathbf{91.0}$ \\ & FairSample & .1140 & .1951 & $.2347$ & $\mathbf{49.7}$ & $\mathbf{82.5}$ & 90.9 \\ & CLIP & .0900 & .2024 & .2648 & $48.2$ & 77.9 & 88.0\\ & CLIP-clip & $\mathbf{.0670}$ & $\mathbf{.1541}$ & $\mathbf{.2057}$ & 46.1 & 75.2 & 86.0 \\ \midrule \multirow{4}{*}{COCO5K} & SCAN & .1379 & .2133 & .2484 & 25.4 & 54.1 & $67.8$ \\ & FairSample & .1133 & .1916 & .2288 & $26.8$ & $\mathbf{55.3}$ & $\mathbf{68.5}$ \\ & CLIP & .0770 & $.1750$ & $.2131$ & $\mathbf{28.7}$ & 53.9 & 64.7\\ & CLIP-clip & $\mathbf{.0672}$ & $\mathbf{.1474}$ & $\mathbf{.1611}$ & 27.3 & 50.8 & 62.0 \\ \midrule \multirow{4}{*}{Flickr30K} & SCAN & .1098 & .3341 & .3960 & 41.4 & 69.9 & 79.1 \\ & FairSample & $\mathbf{.0744}$ & $\mathbf{.2699}$ & .3537 & 35.8 & 67.5 & 77.7 \\ & CLIP & .1150 & .3150 & .3586 & $\mathbf{67.2}$ & $\mathbf{89.1}$ & $\mathbf{93.6}$ \\ & CLIP-clip & .0960 & .2746 & $\mathbf{.2951}$ & 63.9 & 85.4 & 91.3\\ \bottomrule \end{tabular \caption{Results on MS-COCO (1K and 5K) and Flickr30K test sets. We compare the baseline models (SCAN~\cite{SCAN} and CLIP~\cite{CLIP}) and our debiasing methods (FairSample and CLIP-clip) on both the gender bias metric Bias@K and the retrieval metric Recall@K. } \label{tab:main_result} \end{table*} \paragraph{Debiasing Effectiveness} As shown in \cref{tab:main_result}, both the in-processing sampling strategy \emph{FairSample} and the post-processing feature pruning algorithm \emph{clip} consistently mitigate the gender bias on test data. For instance, among the top-10 search images, SCAN with FairSample reduces gender bias from $0.3960$ to $0.3537$ (decreased by $10.7\%$) on Flickr30K. Using the clipped CLIP features for image search (CLIP-clip), the gender bias drops from $0.2648$ to $0.2057$ ($22.3\%$) on MS-COCO 1K, from $0.2131$ to $0.1611$ ($24.4\%$) on MS-COCO 5K, and from $0.3586$ to $0.2951$ (17.7\%) on Flickr30K. For the tradeoff, CLIP-clip sacrifices the recall performance slightly (from $93.6\%$ Recall@10 to $91.3\%$ on Flickr30K). On the other hand, SCAN with FairSample even achieves a comparable recall performance with SCAN. \subsection{Gender Bias at Different Top-K Results} We plot how gender bias varies across different values of $K$ (1-10) for all the compared methods in \cref{fig:gender-bias}. We observe that when $K < 5$, the gender bias has a higher variance due to the inadequate retrieved images. When $K \geq 5$, the curves tend to be flat. This result indicates that $\bias@10$ is more recommended than $\bias@1$ for measuring gender bias as it is more stable. It is also noticeable that CLIP-clip achieves the best fairness performance in terms of $\bias@10$ consistently on all three test sets compared to the other models. \subsection{Tradeoff between Recall and Bias}\label{sec:trade-off} There is an inherent tradeoff between fairness and accuracy in fair machine learning~\cite{NEURIPS2019_b4189d9d}. To achieve the best recall-bias tradeoff in our methods, we further examine the effect of the controlling hyper-parameters: the weight $\alpha$ in FairSampling and the number of clipped dimensions $m$ in CLIP-clip. \cref{fig:fairsample_tradeoff} demonstrates the recall-bias curve with the fair sampling weight $\alpha \in [0,1]$. Models of higher recall often suffer higher gender bias, but the fairness improvement outweighs the recall performance drop in FairSample models. For example, the model fully trained with fair sampling ($\alpha=1$) has the lowest bias and drops the recall performance the most---it relatively reduces $22.5\%$ Bias@10 but only decreases $10.9\%$ Recall@10 on Flickr30K. We choose $\alpha=0.4$ for the final model, which has a better tradeoff in retaining the recall performance. \begin{figure}[tb] \centering \begin{subfigure}[b]{0.48\linewidth} \includegraphics[width=\linewidth]{fig/fairsample_tradeoff_coco.pdf} \caption{MS-COCO 1K test set} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\linewidth} \includegraphics[width=\linewidth]{fig/fairsample_tradeoff_f30k.pdf} \caption{Flickr30K test set} \end{subfigure} \vspace{-1ex} \caption{The Pareto frontier of recall-bias tradeoff curve for FairSample on MS-COCO 1K and Flickr30K.} \label{fig:fairsample_tradeoff} \end{figure} \begin{figure}[t] \centering \begin{subfigure}[b]{0.445\linewidth} \centering \includegraphics[width=\linewidth]{fig/ablation_recall.pdf} \caption{recall} \end{subfigure} \hfill \begin{subfigure}[b]{0.475\linewidth} \centering \includegraphics[width=\linewidth]{fig/ablation_bias.pdf} \caption{gender bias} \end{subfigure} \caption{Effect of the number of clipped dimensions $m$ on performance of recall and bias on MS-COCO 1K.} \label{fig:clip-ablation} \end{figure} As shown in \cref{fig:clip-ablation}, we set the range of the clipping dimension $m$ between $100$ and $400$ on MS-COCO 1K. We find that clipping too many covariates (1) harms the expressiveness of image and text representations (Recall@1 drops from $46.1\%$ to $11.3\%$, Recall@5 drops from $75.2\%$ to $25.4\%$, and Recall@10 drops from $86.0\%$ to $34.2\%$), and (2) causes high standard deviation in gender bias. In light of the harm on expressiveness, we select $m=100$ for conventional use. \begin{figure*}[htb] \centering \begin{subfigure}[b]{0.49\linewidth} \centering \includegraphics[width=\textwidth]{fig/clip.pdf} \caption{CLIP} \end{subfigure} \begin{subfigure}[b]{0.49\linewidth} \centering \includegraphics[width=\textwidth]{fig/clip-clip.pdf} \caption{CLIP-clip} \end{subfigure} \caption{Gender bias evaluation of internet image search results on \texttt{occupations}~\cite{gender-image-search}. We visualize the similarity biases on 18 occupations. \crule[RoyalBlue]{8pt}{8pt} indicates the occupation is biased towards males and \crule[orange]{8pt}{8pt} indicates it is biased towards females. The clip algorithm mitigates gender bias for a variety of occupations. }\label{fig:occupation} \end{figure*} \subsection{Evaluation on Internet Image Search} The aforementioned evaluation results on MS-COCO and Flickr30K datasets are limited that they rely on gender labels extracted from human captions. In this sense, it is important to measure the gender biases on a benchmark where the gender labels are identified by crowd annotators. To this end, we further evaluate on the \texttt{occupation} dataset~\cite{gender-image-search}, which collects top 100 Google Image Search results for each gender-neutral occupation search term.\footnote{The data is available at \url{https://github.com/mjskay/gender-in-image-search}.} Each image is associated with the crowd-sourced gender attribute of the participant portrayed in the image. Inspired by \citet{Burns2018WomenAS} and \citet{Tang2020MitigatingGB}, we measure the gender bias by computing the difference of expected cosine similarity between male and female occupational images. Given an occupation $o$, the similarity bias is formulated as \begin{equation} \bias = \Expectation_{v \in \mathcal{V}^o_\male} S(v, o) - \Expectation_{v \in \mathcal{V}^o_\female} S(v, o) \end{equation} where $\mathcal{V}^o_\male$ and $\mathcal{V}^o_\female$ are the sets of images for occupation $o$, labeled as ``male'' and ``female''. \cref{fig:occupation} demonstrates the absolute similarity bias of CLIP and CLIP-clip on the \texttt{occupation} dataset for 18 occupations. We observe that the CLIP model exhibits severe similarity discrepancy for some occupations, including telemarketer, chemist, and housekeeper, while the \emph{clip} algorithm alleviates this problem effectively. Note that for doctor and police officer, the CLIP-clip model exaggerates the similarity discrepancy, but the similarity bias is still less than 0.01. In general, CLIP-clip is effective for mitigating similarity bias and obtains a 42.3\% lower mean absolute bias of the 100 occupations than the CLIP model ($0.0064$ \textit{vs.} $0.0111$). \section{Gender Bias in Image Search} In an image search system, text queries may be either gender-neutral or gender-specific. Intuitively, when we search for a gender-neutral query like ``a person is cooking'', we expect a fair model returning approximately equal proportions of images depicting men and women. For gender-specific queries, an unbiased image search system is supposed to exclude images with misspecified gender information. This intention aligns with seeking more accurate search results and would be much different from the scope of measuring gender bias in gender-neutral cases. Therefore, we focus on identifying and quantifying gender bias when only searching for gender-neutral text queries. \subsection{Problem Statement}\label{sec:problem-statement} Given a text query provided by the users, the goal of an image search system is to retrieve the matching images from the curated images. In the domain of multi-modality, given the dataset $\{(v_n,c_n)\}_{n=1}^N$ with $N$ image-text pairs, the task of image search aims at matching every image $v$ based on the providing text $c$. We use $\imageset =\{v_n\}_{n=1}^N$ to denote the image set and $\textset = \{c_n\}_{n=1}^N$ to denote the text set. Given a text query $c \in \textset$ and an image $v \in \imageset$, image retrieval models often predict the similarity score $S(v, c)$ between the image and text. One general solution is to embed the image and text into a high-dimensional representation space and compute a proper distance metric, such as Euclidean distance or cosine similarity, between vectors~\cite{Wang2014LearningFI}. We take cosine similarity for an example: \begin{equation}\label{eq:similarity} \begin{split} & S(v, c) = \frac{\vec{v} \cdot \vec{c}}{\|\vec{v}\| \|\vec{c}\|} \\ \textnormal{s.t.}\ &\ \vec{v} = \mathsf{image\_encoder}(v) \\ &\ \vec{c} = \mathsf{text\_encoder}(c) \end{split} \end{equation} The image search system outputs a set of top-$K$ retrieved images $\mathcal{R}_{K}(c)$ with the highest similarity scores. In this work, we assume that when evaluating on test data, $\forall c \in \mathcal{C}$, the text query $c$ is written in gender-neutral language. \subsection{Measuring Gender Bias}\label{sec:measure-gender-bias} The situations of image search results are complex: there might be no people, one person, or more than one person in the images. Let $g(v) \in \{\male, \female, \neutral\}$ represent the gender attribute of an image $v$. Note that in this study gender refers to biological sex~\citealp{larson-2017-gender}. We use the following rules to determine $g(v)$: $g(v) = \male$ when there are only men in the image, $g(v) = \female$ when there are only women in the image, otherwise $g(v) = \neutral$. Portraits in image search results with different gender attributes often receive unequal exposure. Inspired by ~\citet{gender-image-search} and~\citet{Zhao2017MenAL}, we measure gender bias in image search by comparing the proportions of masculine and feminine images in search results. Given the set of retrieved images $\mathcal{R}_{K}(c)$, we count the images depicting males and females \begin{align*} N_\male & = \sum_{v \in \mathcal{R}_K(c)} \Indicator[g(v) = \male], \\ N_\female & = \sum_{v \in \mathcal{R}_K(c)} \Indicator[g(v) = \female], \end{align*} and define the gender bias metric as: \begin{equation} \Delta_K(c) = \begin{cases} 0, & \text{ if $N_\male + N_\female = 0$ } \\ \frac{N_\male - N_\female}{N_\male + N_\female}, & \text{ otherwise} \end{cases} \end{equation} We don't take absolute values for measuring the direction of skewness, i.e., if $\Delta_K(c) > 0$ it skews towards males. Note that a similar definition of gender bias $\frac{N_\male}{N_\male + N_\female}$ in \citet{Zhao2017MenAL} is equivalent to $(1 + \Delta(c))/2$. But our definition of gender bias considers the special case when none of the retrieved images are gender-specific, i.e., $N_\male + N_\female = 0$. For the whole test set, we measure the mean difference over all the text queries: \begin{equation}\label{eq:fairness} \bias@ K = \frac{1}{|\textset|} \sum_{c \in \textset} \Delta_K(c) \end{equation} \section{Related Work}\label{sec:related-work} \paragraph{Fairness in Machine Learning} A number of unfair treatments by machine learning models were reported recently \cite{angwin2016machine,pmlr-v81-buolamwini18a,10.5555/3157382.3157584,10.1145/3025453.3025727}, and the literature has observed a growing demand and interests in proposing defenses, including regularizing disparate impact~\cite{Zafar2015LearningFC} and disparate treatment~\cite{Hardt2016EqualityOO}, promoting fairness through causal inference~\cite{NIPS2017_6995}, and adding fairness guarantees in recommendations and information retrieval~\cite{Beutel2019FairnessIR,Biega2018EquityOA,10.1145/3397271.3401100}. The existing fair machine learning solutions can be broadly categorized as pre-processing~\cite{KamiranFaisal2012DataPT,Feldman2015,NIPS2017_6988}, in-processing, and post-processing approaches. Pre-processing algorithms typically re-weight and repair the training data which captures label bias or historical discrimination~\cite{KamiranFaisal2012DataPT,Feldman2015,NIPS2017_6988}. % In-processing algorithms focus on modifying the training objective with additional fairness constraints or regularization terms~\cite{Zafar2017FairnessCM,fairlearn,Cotter2019OptimizationWN}. Post-processing algorithms enforce fairness constraints by applying a post hoc correction of a (pre-)trained classifier~\cite{Hardt2016EqualityOO,NIPS2017_6988}. In this work, the \textit{fair sampling} strategy designed for the contrastive learning framework could be considered as an in-processing treatment, while the \textit{clip} algorithm is in the post-processing regime that features an information-theoretical clipping procedure. Our contribution highlights new challenges of reducing gender bias in a multimodal task and specializes new in-processing and post-processing ideas in the domain of image search. \paragraph{Social Bias in Multi-modality} Implicit social bias related to gender and race has been discussed in multimodal tasks including image captioning~\cite{Burns2018WomenAS,Tang2020MitigatingGB}, visual question answering~\cite{Manjunatha_2019_CVPR}, face recognition~\cite{pmlr-v81-buolamwini18a}, and unsupervised image representation learning~\cite{unsupervised-image-representation}. For example, \citet{Zhao2017MenAL} shows that models trained on unbalanced data can amplify bias, and injecting corpus-level Lagrangian constraints can calibrate the bias amplification. \citet{Caliskan2017SemanticsDA} demonstrates the association between the word embeddings of occupation and gendered concepts correlates with the imbalanced distribution of gender in text corpora. There are also a series of debiasing techniques in this area. \citet{10.5555/3157382.3157584} propose to surgically alter the embedding space by identifying the gender subspace from gendered word pairs. \citet{manzini-etal-2019-black} extend the bias component removal approach to the setting where the sensitive attribute is non-binary. Data augmentation approaches remove the implicit bias in the training corpora and train the models on the balanced datasets~\cite{zhao-etal-2018-gender}. Our work complements this line of research by examining gender bias induced by multimodal models in image search results. Our focus on gender bias in the gender-neutral language would offer new insights for a less explored topic to the community. \paragraph{Gender Bias in Online Search Systems} Our work is also closely connected to studies in the HCI community showing the gender inequality in online image search results. \citet{gender-image-search} articulate the gender bias in occupational image search results affect people's perceptions of the prevalence of men and women in each occupation. \citet{gender-image-search} compare gender proportions in occupational image search results and discuss how the bias affects people's perceptions of the prevalence of men and women in each occupation. \citet{DBLP:journals/jasis/SinghCIF20} examine the prevalence of gender stereotypes on various digital media platforms. \citet{10.1145/3025453.3025727} identify gender bias with character traits. Nonetheless, these works do not attempt to mitigate gender bias in search algorithms. Our work extends these studies into understanding how gender biases enter search algorithms and provides novel solutions to mitigating gender bias in two typical model families for image search. \section{Conclusion} In this paper, we examine gender bias in image search models when search queries are gender-neutral. As an initial attempt to study this critical problem, we formally identify and quantify gender bias in image search. To mitigate the gender bias perpetuating two representative fashions of image search models, we propose two novel debiasing algorithms in in-processing and post-processing manners. When training a new image search model, the in-processing \textit{FairSample} method can be used to learn a fairer model from scratch. Meanwhile, the \textit{clip} algorithm can be used for lightweight deployment of pre-trained representation models with accessible gender information. \section{Gender Word Lists}\label{app:word-list} We show the word lists for identifying the gender attributes of a caption in \cref{tab:gender-word-list}. \begin{table}[!ht] \centering \begin{tabular}{p{0.2\linewidth} | p{0.7\linewidth}} \toprule feminine words & woman, women, female, girl, lady, mother, mom, sister, daughter, wife, girlfriend \\ \midrule masculine words & man, men, male, boy, gentleman, father, brother, son, husband, boyfriend \\ \midrule gender-neutral words & person, people, human, adult, baby, child, kid, children, guy, teenage, crowd\\ \bottomrule \end{tabular} \caption{Gender word lists. We identify the gender attributes of captions based on the occurrence of gender-specific words appeared in the sentences.} \label{tab:gender-word-list} \end{table} \section{Implementation Details} \subsection{Computing Infrastructure} We use a GPU server with 4 NVIDIA RTX 2080 Ti GPUs for training and evaluation. \subsection{Computational Time Costs} We find that SCAN~\cite{SCAN} and SCAN with fair sampling need about 20 hours for training 30 epochs on MS-COCO and 8-10 minutes for testing on 1K test set. In comparison, pre-trained CLIP~\cite{CLIP} and CLIP-clip can be evaluated within 1 minutes on MS-COCO 1K test set. \section{Qualitative Examples}\label{app:qualitative} We take a qualitative study on the image search results. We show the results of searching ``a person riding a bike'' in \cref{fig:qualitative-analysis2}. The first row presents the top-5 retrieved images for SCAN, the second row presents the top-5 retrieved images for SCAN+FairSample, the third row presents the top-5 retrieved images for CLIP, and the last row presents the top-5 retrieved images for CLIP-clip. While we notice that all the models retrieve relevant images, we find FairSample put images depicting females in a higher rank. \begin{figure*}[!b] \setlength{\tabcolsep}{1ex} \renewcommand{\arraystretch}{1.5} \centering \begin{tabular}{r c c c c c} \rotatebox[origin=l]{90}{SCAN} & \includegraphics[width=0.16\linewidth, height=0.16\linewidth]{examples/scan/7890007278.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/scan/4923272678.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/scan/5365075444.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/scan/3243094580.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/scan/3543294190.jpg} \\ \rotatebox[origin=l]{90}{FairSample} & \includegraphics[width=0.16\linewidth, height=0.16\linewidth]{examples/fair/5365075444.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/fair/3739742770.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/fair/4914732942.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/fair/4914029409.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/fair/7890007278.jpg} \\ \rotatebox[origin=l]{90}{CLIP} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/clip/3543294190.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/clip/5365075444.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/clip/4930533574.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/clip/4153147942.jpg} & \includegraphics[width=0.16\linewidth, height=0.16\linewidth]{examples/clip/4821487527.jpg} \\ \rotatebox[origin=l]{90}{CLIP-clip} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/clip-clip/3543294190.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/clip-clip/4930533574.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/clip-clip/4153147942.jpg} & \includegraphics[width=0.16\linewidth,height=0.16\linewidth]{examples/clip-clip/3739742770.jpg} & \includegraphics[width=0.16\linewidth, height=0.16\linewidth]{examples/clip-clip/94024624.jpg} \\ \end{tabular} \caption{Qualitative analysis of gender bias in image search results. The text query is ``a person riding a bike''. The first row presents the top-5 retrieved images for SCAN, the second row presents the top-5 retrieved images for SCAN+FairSample, the third row presents the top-5 retrieved images for CLIP, and the last row presents the top-5 retrieved images for CLIP-clip. } \label{fig:qualitative-analysis2} \end{figure*}
{'timestamp': '2021-09-14T02:19:10', 'yymm': '2109', 'arxiv_id': '2109.05433', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05433'}
arxiv
\section{Agnostic boosting via multicalibration\xspace} \label{sec:ag} In this section we apply our results to the setting of agnostic learning, where the labels are Boolean, and the relevant loss is the classification error aka $0$-$1$ loss. \begin{definition} Let $\mathcal{H} : \mathcal{X} \rightarrow \ensuremath{\{0,1\}}$ be a family of classifiers. Given a distribution $\mathcal{D}$ on $\mathcal{X} \times \ensuremath{\{0,1\}}$, for $h \in \mathcal{H}$ let its classification error be $\mathrm{err}(h) = \Pr_{\ensuremath{(\x, \y) \sim \D}}[h(\mathbf{x}) \neq \mathbf{y}]$ and $\mathrm{OPT}(\mathcal{H}) = \min_{h \in \mathcal{H}} \mathrm{err}(h)$. An algorithm is an agnostic learner for a class $\mathcal{H}$ if it produces a hypothesis $f$ such that $\mathrm{err}(f) \leq \mathrm{OPT}(\mathcal{H}) + \epsilon$. \end{definition} The $\ell_1$ loss defined by $\ell_1(y,t) = |y -t|$ becomes the classification error for Boolean functions, since for any $h:\mathcal{X} \rightarrow \ensuremath{\{0,1\}}$, \[ \mathrm{err}(h) = \Pr_{\ensuremath{(\x, \y) \sim \D}}[y \neq h(\mathbf{x})] = \E_{\ensuremath{(\x, \y) \sim \D}}[|\mathbf{y} - h(\mathbf{x})|] =\E_{\ensuremath{(\x, \y) \sim \D}}[\ell_1(y, h(\mathbf{x}))]. \] \begin{definition} A class $\mathcal{H}$ is $(\epsilon, W)$-approximated by the class $\mathcal{C}$ if for every $h \in \mathcal{H}$ and $\epsilon > 0$, there exists $g_w \in \mathrm{Lin}_\mathcal{C}(W)$ such that \[\E_{\ensuremath{(\x, \y) \sim \D}} \left[|g_w(x) - h(\mathbf{x})|\right] \leq \epsilon .\] \end{definition} For $p \in [0,1]$ the function \[ \\E_{\mathbf{y} \sim \B{p}} \ell_1(\mathbf{y}, t) = p|1 - t| + (1- p)|t| \] is minimized in $t$ by the function $k_{\ell_1}(p) = \ind{p \geq 1/2}$. Hence the $\ell_1$-optimized hypothesis $h^\mathcal{S}_{\ell_1}$ outputs $1$ for $x \in S_i$ where $p_i \geq 1/2$ and $0$ elsewhere. We are now ready to state our main result about agnostic learning via multi-calibration. We show that multicalibration\xspace\ gives a predictor that is competitive with the best predictor in a possibly much more powerful class $\mathcal{H}$. Since multicalibration\xspace\ can be achieved using a weak learner for $\mathcal{C}$, this implies a form of agnostic boosting. \begin{theorem} \label{thm:ag} Let $\mathcal{H}$ be a class that is $(\epsilon/2, W)$-approximated by $\mathcal{C}$. If the partition $\mathcal{S}$ is $\epsilon/2W$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$, then $\mathrm{err}(h^\mathcal{S}_{\ell_1}) \leq \mathrm{OPT}(\mathcal{H}) + \epsilon$. Hence an algorithm that outputs such a partition gives an agnostic learner for $\mathcal{H}$. \end{theorem} \begin{proof} Let $h =\arg\min_{h \in \mathcal{H}}\mathrm{err}(h)$ so that $\mathrm{err}(h) = \mathrm{OPT}(\mathcal{H})$. There exists $g_w \in \mathrm{Lin}_\mathcal{C}(W)$ such that \[\E_{\ensuremath{(\x, \y) \sim \D}} [|g_w(x) - h(\mathbf{x})|] \leq \epsilon/2 .\] Hence by the triangle inequality, \begin{align*} \E_{\ensuremath{(\x, \y) \sim \D}}[\ell_1(\mathbf{y}, g_w(\mathbf{x})] &\leq \E_{\ensuremath{(\x, \y) \sim \D}}[|\mathbf{y} - h(\mathbf{x})|] + \E_{\ensuremath{(\x, \y) \sim \D}}[|g_w(\mathbf{x}) - h(\mathbf{x})|] \leq \mathrm{err}(h) + \epsilon/2. \end{align*} The $\ell_1$ loss function is $1$-Lipschitz, and $(\mathbb{R}, 1, 0)$-nice. By Corollary \ref{cor:lipschitz} we conclude that since $\mathcal{S}$ is $\epsilon/2W$ approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$, \[ \E_{(\mathbf{x} ,\mathbf{y}) \sim \mathcal{D}} [\ell(\mathbf{y}, h^\mathcal{S}_{\ell_1}(\mathbf{x}))] \leq \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ \ell(\mathbf{y}, g_w(\mathbf{x}))\right] + \epsilon/2 \leq \mathrm{err}(h) + \epsilon. \] But since $h^\mathcal{S}_{\ell_1}$ is a Boolean function, we have \[ \E_{(\mathbf{x} ,\mathbf{y}) \sim \mathcal{D}} [\ell(\mathbf{y}, h^\mathcal{S}_{\ell_1}(\mathbf{x}))] = \mathrm{err}(h^\mathcal{S}_{\ell_1}). \] Hence $\mathrm{err}(h^\mathcal{S}_{\ell_1}) \leq \mathrm{err}(h) + \epsilon$, which proves our claim. \end{proof} Some comments on the connection of Theorem \ref{thm:ag} to other work: \begin{itemize} \item The agnostic learnability of a class $\mathcal{H}$ that is $\ell_1$ approximated by $\mathcal{C}$ was first proved by \cite{KKMS08} using linear programming; see \cite{feldman2009distribution, kk09} for a boosting based approach. Our result reproves this through multicalibration\xspace and the algorithm of \cite{MansourM2002}. \item Agnostic boosting was introduced in the work of \cite{SBD2}. The agnostic boosting abilities of the \cite{MansourM2002} algorithm are analyzed in \cite{KalaiMV08}, however they bound the error by $\mathrm{OPT}(\mathcal{C})$. Our work shows that this algorithm is even more powerful; one can compare it to $\mathrm{OPT}(\mathcal{H})$. \item Theorem \ref{thm:ag} gives an upper bound, but it is not a tight characterization of the error of the hypothesis $h^\mathcal{S}_{\ell_1}$. Indeed, in subsection \ref{sec:better}, we give an example showing that the error of the hypothesis can be much smaller than $\mathrm{OPT}(\mathrm{Lin}_\mathcal{C})$. \item For the purposes of agnostic boosting, it is often desirable to keep the same marginal distribution over $\mathcal{X}$. Following Kalai-Kanade \cite{kk09} and Feldman \cite{feldman2009distribution}, one can reduce multicalibration\xspace\ to weak agnostic learning over a distribution with the same marginal on $\mathcal{X}$, by adding noise to the labels. \end{itemize} \subsection{Multicalibration\xspace can be better than $\mathrm{OPT}$} \label{sec:better} In the literature of agnostic boosting (specifically \cite{kk09}), a \textit{$\gamma$-weak agnostic learner} \cite{kk09} for ${\cal H}$ is defined as an algorithm that outputs $c \in {\cal C}$ such that, \begin{align} \label{eq:kk09} \cor_\mathcal{D}(c) \geq \gamma \sup_{h \in {\cal H}} \cor_\mathcal{D}(h), \end{align} for $\gamma > 0$ in terms of \textit{correlation} $\cor_\mathcal{D}(h) \in [-1,1]$ defined as, \[\cor_\mathcal{D}(h):=\Pr_{\mathcal{D}}[h(x) = y] - \Pr_{\mathcal{D}}[h(x) \neq y].\] It is shown that a $\gamma$ weak agnostic learner can be used to achieve error within $\epsilon$ of $\mathrm{OPT}(\mathcal{H})$ using time and samples $\poly(1/\gamma, 1/\epsilon)$. \cite{kk09} do not explicitly limit what class $\mathcal{H}$ can be relative to $\mathcal{C}$, beyond saying that it should satisfy condition Equation \eqref{eq:kk09}. However it is not difficult to see that this definition limits agnostic boosting to ${\cal H} \subseteq \mathrm{Lin}_\mathcal{C}$, i.e., linear combinations as defined in Equation \eqref{eq:mLC}. Therefore, agnostic boosting (as in \cite{KalaiMV08, kk09}) essentially learns linear combinations of ${\cal C}$, while we have shown that multi-calibrated predictors also satisfy this goal. Indeed, our proof shows that the marginal distribution on $\mathcal{X}$ can be considered fixed, we just require Equation \eqref{eq:kk09} to hold for all $h \in \mathcal{H}$ and marginal distributions on the label $\mathbf{y}$. \begin{lemma} \label{lem:adam} For Equation \eqref{eq:kk09} to hold for every $h \in \mathcal{H}$, we must have ${\cal H} \subseteq \mathrm{Lin}_\mathcal{C}$. \end{lemma} \begin{proof} For the purpose of contradiction consider any $h \notin \mathrm{Lin}_\mathcal{C}$. Let $g: \mathcal{X} \rightarrow \mathbb{R}$ be the projection of $h$ onto $\mathrm{Lin}_\mathcal{C}$, i.e., that minimizes $\E_\mathcal{D}[(g(x)-h(x))^2]$. Since $\mathcal{X}$ and ${\cal C}$ are finite, $g$ is bounded. Thus consider \[f^*(x) := \frac{1}{2} + \frac{h(x)-g(x)}{\max_{\mathcal{X}} |h(x)-g(x)|} \in [0,1].\] In particular, for the distribution $\mathcal{D}'$ which has the same marginal over $\mathcal{X}$ but so that $f^*(x)=\E_{\mathcal{D}'}\mathbf{y}|x]$, it is not difficult to see that $\cor_{\mathcal{D}'}(c)=0$ for all $c \in {\cal C}$ and yet $\cor_{\mathcal{D}'}(h)>0$ violating the definition of a weak learner. \end{proof} We now show that being approximately multicalibrated\xspace is a \textit{stronger} notion than $\mathrm{OPT}(\mathrm{Lin}_\mathcal{C})$ in that being multi-calibrated with respect to ${\cal C}$ implies a loss that may be even lower than the best classifier in $\mathrm{Lin}_\mathcal{C}$. This says that the upper bound on the classification error in terms of $\mathrm{OPT}(\mathrm{Lin}_\mathcal{C})$ given by Theorem \ref{thm:ag} may not always be tight. \begin{theorem} For any $\epsilon > 0$, there exists a distribution $\mathcal{D}$ on $\ensuremath{\{0,1\}}^2 \times \ensuremath{\{0,1\}}$ and a set of functions $\mathcal{C}:\mathcal{X} \rightarrow \ensuremath{\{0,1\}}$ such that for any approximately multicalibrated\xspace partition $\mathcal{S}$, we have $\mathrm{OPT}(\mathrm{Lin}_\mathcal{C}) - \mathrm{err}(h^\mathcal{S}_{\ell_1}, \mathcal{D}) \geq 1/4 - \epsilon/2$. \end{theorem} \begin{proof} Let $\mathcal{X} =\{0,1\}^2, \mathcal{Y} = \ensuremath{\{0,1\}}$, the marginal distribution over $x \in \mathcal{X}$ uniform, and the conditional distribution over $\mathcal{Y}$ given by $$\E[\mathbf{y}|x] = \begin{cases}0 & \text{if }x=(0,0)\\ \epsilon & \text{if }x=(1,0)\\ \epsilon & \text{if }x=(1,1)\\ 1 & \text{if }x=(0,1). \end{cases}$$ Let $\mathcal{C}=\{x_1, x_2\}$ be the family of two classifiers based on the two coordinates. It is not hard to see that, for this ${\cal C}$ and for ${\cal H}:=\mathrm{Lin}_\mathcal{C}$, which is the most agnostic boosting can cover, $\mathrm{OPT}(\mathcal{H})=1/4$ is the error of the best classifier $c(x)=x_2$. On the other hand, it is not difficult to see that any multi-calibrated partition must have separate sets for $\{(0,1)\}$ and $\{(0,0)\}$. This implies a smaller 0-1 loss of $\epsilon/2$. \end{proof} Clearly, by reducing the constant $\epsilon$, the multi-calibrated loss can approach 0, but we chose not to set it to exactly 0 because standard boosting could be applied in the noiseless case. \subsection{Reducing multi-calibration to weak agnostic learning} Informally, a weak agnostic learner is an algorithm that is able to detect non-trivial correlation between the labels and functions in a class. We use the definition of a weak agnostic learner for a class $\mathcal{C}$ of functions following Kalai and Kanade. \begin{definition} For $\alpha' \leq \alpha$, an $(\alpha, \alpha')$ weak learner for a class $\mathcal{C}$ takes samples from a distribution $\mathcal{D}$ on $\mathcal{X} \times \ensuremath{ \{\pm 1\} }$. If there exists $c \in \mathcal{C}$ such that $\E_{\mathcal{D}}[c(\mathbf{x}) \mathbf{z}] \geq \alpha$ then with probability $1- \delta$ the weak learner returns a hypothesis $c' \in \mathcal{C}$ such that $\E_{\mathcal{D}}[c'(\mathbf{x}) \mathbf{z}] \geq \alpha'$. The sample complexity and running time depend on $\alpha, \alpha'$ and $\delta$ and the dimensionality of the data. \end{definition} Note that $\alpha' \leq \alpha$, and indeed Kalai and Kanade consider $\alpha' = \gamma \alpha$ for some $\gamma < 1$. One can allow the learner to be improper, meaning that it returns $c' \in \mathcal{C}'$ for some different, possibly broader class of function $\mathcal{C}' \neq \mathcal{C}$. Our results will apply even with these changes, but for simplicity we work with proper learners. One can reduce the problem of detecting if a partition is multi-calibrated to a weak agnostic learning problem. While Equation \eqref{eq:m-cal} does require finding significant correlation with $\mathcal{C}$, $\mathbf{y} \in \ensuremath{\{0,1\}}$, $\mathbf{y} - p_i$ can take values outside $\ensuremath{\{0,1\}}$, whereas our definition of weak learner for $\mathcal{C}$ expects $\ensuremath{ \{\pm 1\} }$ labels. There are a couple of ways of dealing with this issue in the literature. \paragraph {Distribution Reweighting.} Define the distribution $\mathcal{D}_i^0$ on $S_i \times \ensuremath{ \{\pm 1\} }$ as follows: with probability $1/2$ we sample $\mathbf{x} \sim \mathcal{D}_i|\mathbf{y} =1$ and output $(\mathbf{x}, \mathbf{z} = 1)$, and with probability $1/2$ we sample $\mathbf{x} \sim \mathcal{D}_i|\mathbf{y} = 0$ and output $(\mathbf{x}, \mathbf{z} = -1)$. It is easy to check that this is equivalent to \begin{align} \label{eq:d0} \mathcal{D}_i^0(x, 1) = \frac{\mathcal{D}_i(x,1)}{2p_i}, \ \mathcal{D}_i^0(x, -1) = \frac{\mathcal{D}_i(x, 0)}{2(1 - p_i)} \end{align} and that $\E_{\mathbf{z} \sim \mathcal{D}^0_i}[\mathbf{z}] = 0$. \begin{lemma} \label{lem:reweight} $\mathcal{S}$ is $\alpha$-multi-calibrated for $\mathcal{C}, \mathcal{D}$ iff the following condition holds for all $i \in [m]$ and $c \in \mathcal{C}$: \[ \abs{\E_{(\mathbf{x}, \mathbf{z}) \sim \mathcal{D}^0_i}[c(\mathbf{x}) \mathbf{z}]} \leq \alpha/2.\] \end{lemma} \begin{proof} Let $(\mathbf{x}', \mathbf{z}) \sim \mathcal{D}_i^0$, and $(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}$. Then we claim that \begin{align*} \E_{\mathcal{D}^0_i} [c(\mathbf{x}')\mathbf{z}] &= \frac{\E_{\mathcal{D}_i}[c(\mathbf{x})(\mathbf{y} - p_i)]}{2p_i(1 - p_i)}. \end{align*} We can rewrite Equation \eqref{eq:d0} as \begin{align} \label{eq:d0-single} D_i^0(x, 2y -1) = D_i(x, y) \frac{ (1 - 2p_i)y + p_i}{2p_i(1 - p_i)}. \end{align} Hence \begin{align*} \E_{(\mathbf{x}', \mathbf{z}) \sim \mathcal{D}^0_i}[c(\mathbf{x}') \mathbf{z}] = \E_{(x, \mathbf{y}) \sim D_i} \left[\frac{ (1 - 2p_i)\mathbf{y} + p_i}{2p_i(1 - p_i)}c(\mathbf{x})(2\mathbf{y} -1)\right] = \E_{(x, \mathbf{y}) \sim D_i}\left[c(\mathbf{x})\frac{ \mathbf{y} - p_i}{2p_i(1 - p_i)}\right]. \end{align*} \end{proof} Given random samples from $\mathcal{D}_i$ one can generate a random sample from $\mathcal{D}^0_i$ using rejection sampling, using $O(1/p_i(1 - p_i))$ samples. \eat{ Hence Rather than shifting the inputs, we reweight them to make the labels unbiased: every sample labelled $1$ is scaled by $(1 - p_i)$ and every sample labelled $0$ is scaled by $p_i$. (entirely standard, but we present it below for completeness). In this reweighted scheme, we require a weak learner to produce $c \in \mathcal{C}$ that has correlation at least $\alpha$. \begin{lemma} \label{def:mcab} $D_i^0$ defined in Equation \eqref{eq:d0} is a distribution, where the labels are unbiased: $\E_{\mathcal{D}^0_i}[\mathbf{y}] = 1/2$. The partition $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$ iff for every $i \in [m]$ and $c \in \mathcal{C}$, it holds that \begin{align} \label{eq:m-cal3} \abs{ \E_{(\mathbf{x},\mathbf{y})\sim \mathcal{D}_i^0} [c(\mathbf{x}) \mathbf{y}] } \leq \alpha. \end{align} \end{lemma} \begin{proof} One can verify that $\mathcal{D}_i^0$ is a distribution since \[ \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} \left[\frac{\mathcal{D}^0_i(\mathbf{x}, \mathbf{y})}{\mathcal{D}_i(\mathbf{x}, \mathbf{y})} \right] = \fr{1 -\eta_i^2}\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [1 - \mathbf{y} \eta_i] = 1, \] and that the labels are unbiased under $\mathcal{D}^0_i$ since \[ \E_{(\mathbf{x}, \mathbf{y})\sim \mathcal{D}^0_i}[\mathbf{y}] = \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} \left[\mathbf{y}\frac{1 - \mathbf{y} \eta_i}{1 - \eta_i^2}\right] = \fr{1 -\eta_i^2} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [\mathbf{y} - \mathbf{y}^2\eta_i] = 0\] where we use $\E_{\mathcal{D}_i}[\mathbf{y}] = \eta_i$ and $\mathbf{y}^2 =1$ since $\mathbf{y} \in \ensuremath{ \{\pm 1\} }$. We have \begin{align*} \E_{(\mathbf{x},\mathbf{y})\sim \mathcal{D}_i^0} [c(\mathbf{x}) \mathbf{y}] &= \E_{(\mathbf{x},\mathbf{y})\sim \mathcal{D}_i} \left[\frac{\mathcal{D}_i^0(\mathbf{x}, \mathbf{y})}{\mathcal{D}_i(\mathbf{x}, \mathbf{y})} c(\mathbf{x}) \mathbf{y}\right] = \E_{(\mathbf{x},\mathbf{y})\sim \mathcal{D}_i} \left[ \frac{1 - \mathbf{y} \eta_i}{ 1 - \eta_i^2} c(\mathbf{x}) \mathbf{y}\right]\\ & = \fr{1 - \eta_i^2} \E_{(\mathbf{x},\mathbf{y})\sim \mathcal{D}_i}[c(\mathbf{x})(\mathbf{y} - \mathbf{y}^2\eta_i)] = \fr{1 - \eta_i^2} \E_{(\mathbf{x},\mathbf{y})\sim \mathcal{D}_i}[c(\mathbf{x})(\mathbf{y} - \eta_i)]. \end{align*} It follows that Equations \eqref{eq:m-cal2} and \eqref{eq:m-cal3} are equivalent. \end{proof} Alternately, following Kalai-Kanade and Feldman, one can probably keep the marginal distribution on $\mathcal{X}$ unchanged, and just add label noise. } \subsection{Sample efficiency} In practice, we are given random samples from the distribution $\mathcal{D}$, which means that we cannot estimate quantities like $\Var_{D_i}[\mathbf{y}]$ exactly. To account for this, we use the following relaxed notion of $(\alpha, \beta)$-multicalibration\xspace. \begin{definition} Let $\mathcal{C} = \{c: \mathcal{X} \rightarrow \mathbb{R}\}$ be a collection of real-valued functions on $\mathcal{X}$, and $\mathcal{D}$ be a distribution $\mathcal{X} \times \ensuremath{\{0,1\}}$. We say that the partition $\mathcal{S}$ of $\mathcal{X}$ is $(\alpha, \beta)$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$ if there exists a distribution $\mathcal{D}'$ on $\mathcal{X} \times \ensuremath{\{0,1\}}$ such that $\mathrm{d_{TV}}(\mathcal{D}, \mathcal{D}') \leq \beta$ and $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}'$. \end{definition} \section{Computing approximately multicalibrated\xspace\ partitions} \label{sec:algo} In this section, we show how one can use a weak agnostic learner to compute a multi-calibrated partition for the multi-class setting, where we are given a distribution $\mathcal{D}$ on $\mathcal{X} \times [l]$ and our goal is to compute a partition of $\mathcal{X}$ satisfying definition \ref{def:m-cal-k}. We start with the definition of a weak agnostic leaner in the setting where the class of hypotheses $\mathcal{C}$ can be real-valued. Similar definitions appear in the literature in \cite{Kalai04, KalaiMV08, kk09}. We restrict the class of output hypotheses $\mathcal{C}'$ found by the weak learner to be Boolean for simplicity, but this requirement is easy to relax. \begin{definition} \label{def:weak} Let $\mathcal{C} = \{c: \mathcal{X} \rightarrow \mathbb{R}\}$ be a family of real-valued hypotheses. Let $w: (0,1] \rightarrow (0,1]$ be such that $w(\alpha) \leq \alpha$. Let $\mathcal{C}' = \{c': \mathcal{X} \rightarrow \ensuremath{\{0,1\}}\}$ be a family of Boolean hypotheses. An $(w, \mathcal{C}')$ weak learner for $\mathcal{C}$ is given sample access to a distribution $\mathcal{D}$ on $\mathcal{X} \times \ensuremath{\{0,1\}}$. If there exists $c \in \mathcal{C}$ such that $\CoVar_{\mathcal{D}}[c(\mathbf{x}), \mathbf{y}] \geq \alpha$, then with probability $1- \delta$ the weak learner returns a hypothesis $c' \in \mathcal{C}'$ such that $\CoVar_{\mathcal{D}}[c'(\mathbf{x}),\mathbf{y}] \geq w(\alpha)$. \end{definition} A few comments on our definition: \begin{itemize} \item We have defined the weak agnostic learner to work for every distribution $\mathcal{D}$ on $\mathcal{X} \times \ensuremath{\{0,1\}}$. One can work with a weaker notion called distribution-specific agnostic learning \cite{kk09, feldman2009distribution}, where we only have guarantees for a fixed marginal distribution on $\mathcal{X}$. \item Ideally, we would like $w(\alpha)$ to be lower bounded by a polynomial in $\alpha$, and the sample complexity and running time to depend polynomially on $1/w(\alpha), \log(1/\delta)$ and the dimensionality of $\mathcal{X}$. Since $w(\alpha) \leq \alpha$, this allows a polynomial dependence in $1/\alpha$. For simplicity, we will ignore the failure probability $\delta$ since it can be made arbitrarily small by repetition. We will state our results in terms of the number of calls made to the weak learner, through which the running time and sample complexity of our algorithm will depend on those for the weak learner. \item We can relax the assumption that $\mathcal{C}'$ is Boolean to allow for bounded real-valued functions: if $c': \mathcal{X} \rightarrow \mathbb{R}$ satisfies $\CoVar[c'(\mathbf{x}), \mathbf{y}] \geq w(\alpha)$, then it is well-known \cite{Kalai04} that there exists $\theta$ such that the $\CoVar[\ind{c'(x) \geq \theta}, \mathbf{y}] \geq w(\alpha)/\max_{x \in \mathcal{X}}|c'(x)|$. Such a $\theta$ can be found by a simple line search. \end{itemize} \begin{theorem} \label{thm:alg-multi} Given a $(w, \mathcal{C}')$ weak learner for $\mathcal{C}$, for any $\alpha > 0$ and any distribution $\mathcal{D}$ on $\mathcal{X} \times [l]$, there is an efficient algorithm to compute an $\alpha$-approximately multicalibrated\xspace partition for $\mathcal{C}, \mathcal{D}$ of size \[ m \leq 2l\left(\frac{12}{\alpha w(\alpha/2)^2}\right)^{l-1}. \] The partition can be computed by a layered branching program with nodes labelled by hypotheses from $\mathcal{C}'$, of width $m$ and length $T$ where \[ T \leq 2l\left(\frac{12}{\alpha w(\alpha/2)^2}\right)^l.\] The algorithm makes $O((l/w(\alpha/2))^{O(l)})$ queries to the weak agnostic learner. \end{theorem} Our algorithm uses ideas and analyses that appear previously in the literature \cite{MansourM2002, Kalai04, gopalan2021multicalibrated}, yet since it differs each of these works along one or more axes, we present the algorithm and sketch its analysis in Appendix \ref{app:algo} for completeness. We highlight the similarities and differences from previous work below. \begin{itemize} \item The notion of boosting using branching programs was introduced by \cite{MansourM2002}, building on the work of \cite{KearnsM99} on boosting via decision trees. The work of \cite{Kalai04} shows that the \cite{MansourM2002} algorithm can be used to achieve {\em correlation boosting} in real-valued setting where the labels come form $[0,1]$. Under the assumption that for any distribution $\mathcal{D}$ on $\mathcal{X} \times [0,1]$, the weak learner can produce a real-valued hypothesis that has non-trivial correlation with the labels; Kalai \cite{Kalai04} shows that the \cite{MansourM2002} algorithm produces a hypothesis whose correlation with the labels is close to $1$. In contrast, we work with binary labels, and only assume that the weak learner can produce a correlated hypothesis for a specific marginal distribution $\mathcal{D}_X$. The outcome of our algorithm is a multicalibrated partition. Our definition of multicalibration is influenced by the correlation-based notion of weak learning form this work. \item The notion of multicalibrated partitions was introduced in \cite{gopalan2021multicalibrated} in the context of computing importance weights. Their work may be thought of defining approximate multicalibration in the unsupervised setting, which involves some subtle technical issues. Similarly, our algorithm and analysis follows the same high level outline, but there are technical differences. \end{itemize} \eat{ By the results of \cite{MansourM2002, gopalan2021multicalibrated} and \cite{hkrr2018}, there exists an $\alpha$-approximately multicalibrated\xspace partition which can be computed efficiently, given access to an efficient weak learner. \paragraph{Algorithm for the multi-class setting.} Similar to the binary setting, for the multi-class setting with $k$ classes there exists an $\alpha$-approximately multicalibrated\xspace partition of size $O(1/w(\alpha)^{O(k)})$ which can be computed with $k \poly(1/w(\alpha)^k)$ queries to a weak-agnostic learner for $\mathcal{C}$, by a simple modification to the algorithm of \cite{gopalan2021multicalibrated} for computing approximately multicalibrated\xspace partitions. Intuitively, rather than conditioning on just the predicted probability of a single label, we now condition on the entire histogram of predicted probabilities for each label in $[k]$, which gives rise to the exponential dependence on $k$. A similar result can be derived using the moment-multicalibration algorithm of \cite{Jung20}. } \section{Algorithm for the multi-class setting} \label{app:algo} In this Section, we sketch the proof of Theorem \ref{thm:alg-multi}. A distribution in $\mathcal{P}(l)$ in a vector $v \in [0,1]^l$ such that $\sum_i v_i =1$. We can partition this space into subcubes, where each subcube is the product of $l$ intervals of length $\delta$. We refer to this collection of subcubes as $\mathcal{I}_\delta$. Naively $|\mathcal{I}_\delta| = O(1/\delta^l)$, we can also bound it by $l O(1/\delta^{l-1})$ by observing that since the co-ordinates need to sum to $1$, fixing the first $l-1$ co-ordinates leaves at most $l$ possible intervals of the length $\delta$ for the last coordinate. Our algorithm maintains a partition $\mathcal{S}$ of the space $\mathcal{X}$. We have a target bound on the number of states $m = |\mathcal{I}_\delta|$ for $\delta$ to be specified later. We will ensure that the number of states never exceeds $2m$. We iteratively modify the partition until we reach a multicalibrated partition, using one of two operations $\mathrm{Split}$ and $\mathrm{Merge}$. $\mathrm{Split}$ increases the number of states in the partition by $1$. $\mathrm{Merge}$ is applied whenever the number of states exceeds $2m$ and brings the number down to at most $m$. The algorithm terminates when neither operation is applicable. This results a sequence $\{\mathcal{S}_t\}_{t=0}^T$ starting from the trivial partition $\mathcal{S}_0 = \{ \mathcal{X} \}$ until the algorithm terminates with $\mathcal{S}_T$, which we will show is multicalibrated. For very partition $\mathcal{S}_t$, we define a corresponding distribution function $f_t : \mathcal{S}_t \rightarrow \mathcal{P}(l)$, where $f_t(S_i) \in \mathcal{P}(l)$ is the distribution over labels $[l]$ conditioned on $S_i$. \paragraph{$\mathrm{Split}$:} The $\mathrm{Split}$ operation takes a two arguments \begin{enumerate} \item A state $S_i \in \mathcal{S}_t$ such that $\mathcal{D}(S_i) \geq \alpha/4m$. \item A hypothesis $c' \in \mathcal{C}'$ such that there exists a label $j \in [l]$ so that \[\CoVar_{\mathcal{D}_i}[c'(\mathbf{x}), \ind{\mathbf{y} = j}] \geq w(\alpha/2).\] \end{enumerate} It splits $S_i$ into two states $T_0 = S_i \cap c'^{-1}(0)$ and $T_1 = S_i \cap c'^{-1}(1)$ to create the next partition $\mathcal{S}_{t+1}$. To see if the $\mathrm{Split}$ operation can be applied, we iterate over all states $S_i$ which are sufficiently large ($\mathcal{D}(S_i) \geq \alpha/4m$). For every $j \in [l]$, we create a distribution $\mathcal{D}_{i, j}$ on $\mathcal{X} \times \ensuremath{\{0,1\}}$ by sampling a pair $\mathbf{x}, \mathbf{y}$ according to $\mathcal{D}_i$ and outputting the pair $(\mathbf{x}, \ind{\mathbf{y} =j})$. We run the weak learner on each such distribution $\mathcal{D}_{i, j}$. If for some $j$, it find a hypothesis $c' \in \mathcal{C}'$, we run $\mathrm{Split}$ on the apir $(S_i, c')$. \paragraph{$\mathrm{Merge}$:} The $\mathrm{Merge}$ operation is applied whenever the number of states exceeds $2m$, and brings it down to at most $m$. For every subcube $I \in \mathcal{I}_\delta$, we merge all states $S_i$ so that $f_t(S_i) \in I$ into a single state. \paragraph{Correctness. } Suppose the algorithm terminates at time $T$, and let $m_T$ denote the number of states. For every $i \in m_T$ such that $\mathcal{D}(S_i) \geq \alpha/4m$, for every $c \in \mathcal{C}$ and $j \in [l]$ \begin{align} \label{eq:term} \CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \ind{\mathbf{y} = j}] \leq \alpha/2 \end{align} If this condition were violated, then running the weak learner on $\mathcal{D}_i$ is guaranteed to find $c'$, such that we can run $\mathrm{Split}$ on the pair $S_i, c'$, violating the termination condition. We can use these conditions to show that for any $c \in \mathcal{C}$ and $j \in [l]$, \[ \E_{\i \sim \mathcal{D}}\left[\left|\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \ind{\mathbf{y} =j}\right|\right] \leq \alpha \] hence the partition is indeed multicalibrated. The total contribution from {\em small} states $S_i$ such that $\mathcal{D}(S_i) \leq \alpha/4m$ is at most $\alpha/2$ since there are at most $2m$ states. By Equation \eqref{eq:term}, the contribution to it from large states is bounded by $\alpha/2$. \paragraph{Running time.} We bound the number of iterations using $\E_{\mathbf{x} \sim \mathcal{D}}[\|f_t(\mathbf{x})\|^2]$ as our potential function, as in \cite{Kalai04}. If $\mathcal{S}_{t+1}$ is created from $\mathcal{S}_t$ by splitting the state $S_i$ using $c' \in \mathcal{C}'$, then one can show that \[ \E_{\mathbf{x} \sim \mathcal{D}}[\|f_{t+1}(\mathbf{x})\|^2] - \E_{\mathbf{x} \sim \mathcal{D}}[\|f_t(\mathbf{x})\|^2] \geq \mathcal{D}(S_i) \sum_{j \in [l]} \left(\CoVar_{\mathcal{D}_i}[c'(x), \ind{\mathbf{y} = j}]\right)^2 \geq \frac{\alpha}{4m}w(\alpha/2)^2.\] On the other hand, one can show that a $\mathrm{Merge}$ operation only causes a small reduction in the potential. If $\mathcal{S}_{t+1}$ is created from $\mathcal{S}_t$ by a $\mathrm{Merge}$ operation, then \[ \E_{\mathbf{x} \sim \mathcal{D}}[\|f_{t+1}(\mathbf{x})\|^2] - \E_{\mathbf{x} \sim \mathcal{D}}[\|f_t(\mathbf{x})\|^2] \geq -2\delta. \] Since the $\mathrm{Merge}$ operation reduces the number of states from $2m$ to $m$, there are at least $m$ $\mathrm{Split}$ operations before the next $\mathrm{Merge}$ happens. If we partition time into epochs, each ending with a $\mathrm{Merge}$, then in each epoch, the potential increases by at least \[ m\frac{\alpha}{4m}w(\alpha/2)^2 - 2\delta = \frac{\alpha}{4}w(\alpha/2)^2 - 2\delta \geq \delta \] if we choose \[ \delta = \frac{\alpha}{12}w(\alpha/2)^2. \] Since the potential can be at most $1$, this implies a bound of $1/\delta$ on the number of epochs. We have \[ m_T \leq 2m \leq 2l/\delta^{l-1} \leq 2l\left(\frac{12}{\alpha w(\alpha/2)^2}\right)^{l-1} \] Since the number of epochs is at most $1/\delta$ and a single epoch involves at most $2m$ $\mathrm{Split}$ operations, we have \[ T \leq 2m/\delta \leq 2l/\delta^l \leq 2l\left(\frac{12}{\alpha w(\alpha/2)^2}\right)^l.\] \paragraph{Sample Complexity.} At each time step, the weak agnostic learner might be invoked at most $l \cdot m$ times. Since we only consider those states $S_i$ where $\mathcal{D}(S_i) \geq \alpha/4m$, the number of samples from $\mathcal{D}$ needed for each call is roughly $4m/\alpha$ times the sample complexity of the weak agnostic learner. Overall, the multiplicative overhead in sample complexity over the weak agnostic learner is \[ l m \cdot 4m/\alpha \cdot T = O\left(l^2 \left(\frac{12}{\alpha w(\alpha/2)^2}\right)^{3l}\right). \] \section{More Proofs} \subsection{Proofs from Section \ref{sec:mcab}} \label{app:mcab} \begin{proof}[Proof of Corollary \ref{cor:covar}] Since $\mathbf{y} \in \ensuremath{\{0,1\}}$, $\E_\mathcal{D}[\mathbf{y}] = \Pr_\mathcal{D}[\mathbf{y} =1]$, while $\E_\mathcal{D}[\mathbf{z}\mathbf{y}] = \Pr[\mathbf{y} =1]\E_\mathcal{D}[\mathbf{z}|\mathbf{y} = 1]$. Substituting in the definition of covariance gives the first equality in Equation \eqref{eq:covar-1}. To derive the second equality, we let $\mathbf{y}' = 1 - \mathbf{y}$ so that \[ \CoVar_{\mathcal{D}}[\mathbf{z}, \mathbf{y}'] = \CoVar_{\mathcal{D}}[\mathbf{z}, 1 - \mathbf{y}] = -\CoVar_{\mathcal{D}}[\mathbf{z}, \mathbf{y}]\] and then apply the same reasoning to $\mathbf{y}'$. \end{proof} \begin{proof}[Proof of Lemma \ref{lem:small}] Let $L \subseteq [m]$ denote the set of states for which Equation \eqref{eq:small} does not hold. For such states we use the bound \[ \CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}] \leq \max_{x \in \mathcal{X}, y \in \ensuremath{\{0,1\}}}|c(x)||y| \leq \infnorm{C} .\] Hence \[ \sum_{i \in L}D(S_i)\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}] \leq m\frac{\alpha}{2m\infnorm{C}}\infnorm{C} \leq \frac{\alpha}{2}.\] By Equation \eqref{eq:small-cov} we have the bound \[ \sum_{i \not\in L}D(S_i)\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}] \leq \frac{\alpha}{2}. \] Summing the two bounds, we conclude that $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace. \end{proof} \begin{proof}[Proof of Corollary \ref{cor:bin}] By Equation \eqref{eq:covar-1}, \begin{align*} \E_{\i \sim \mathcal{D}}\left[\Pr_{\mathcal{D}_i}[\mathbf{y} = b]\left|E_{\mathcal{D}_i|\mathbf{y} = b}[c(\mathbf{x})] - \E_{\mathcal{D}_i}[c(\mathbf{x})]\right|\right] = \E_{\i \sim \mathcal{D}}\left[\left|\CoVar_{\mathcal{D}_\i} [(c\mathbf{x}), \mathbf{y}]\right|\right] \leq \alpha. \end{align*} \end{proof} \begin{proof}[Proof of Lemma \ref{lem:linear}] Let $g_w \in \mathrm{Lin}_\mathcal{C}(W)$. Then for each $i \in [m]$, using the linearity of covariance \begin{align*} \CoVar_{\mathcal{D}_i}[g_w(\mathbf{x}), \mathbf{y} ] = w_0\CoVar[1, \mathbf{y} ] + \sum_{j \geq 1} w_j \CoVar_{D_i}[c_j(\mathbf{x}), \mathbf{y})] = \sum_{j \geq 1} w_j \CoVar_{D_i}[c_j(\mathbf{x}), \mathbf{y})] \end{align*} Averaging over states, using the triangle inequality and using approximate multicalibration\xspace, \begin{align*} \sum_{i \in [m]} \mathcal{D}(S_i) \abs{\CoVar_{\mathcal{D}_i}[g_w(\mathbf{x}), \mathbf{y}]} &= \sum_{i \in [m]}\mathcal{D}(S_i)\abs{\sum_{j \geq 1} w_j \CoVar_{D_i}[c_j(\mathbf{x}), \mathbf{y})] } \\ &\leq \sum_{i \in [m]}\mathcal{D}(S_i)\sum_{j \geq 1} |w_j|\abs{\CoVar_{D_i}[c_j(\mathbf{x}), \mathbf{y})] } \\ & = \sum_{j \geq 1} |w_j| \sum_{i \in [m]}\mathcal{D}(S_i) \abs{\CoVar_{D_i}[c_j(\mathbf{x}), \mathbf{y})]}\\ & \leq \alpha \sum_{ j\geq 1}|w_j| \leq \alpha W. \end{align*} \end{proof} \subsection{Proof of Theorem \ref{thm:sub-pop}} \label{app:sub-pop} In order to prove Theorem \ref{thm:sub-pop}, we will first restate the definition of multicalibration\xspace\ as follows. For a set $S \subseteq \mathcal{X}$, let $S(x) =1$ if $x \in S$ and $0$ otherwise. \begin{lemma} \label{lem:m-cal-newer} The partition $\mathcal{S}$ of $\mathcal{X}$ is $\alpha$-approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$ iff for every $c \in \mathcal{C}$, \begin{align} \label{eq:m-cal-newer} \sum_{i \in [m]}\abs{\E_\mathcal{D}[S_i(x) c(\mathbf{x}) (\mathbf{y} - p_i)]} \leq \alpha. \end{align} \end{lemma} \begin{proof} We can rewrite the LHS of Equation \eqref{eq:m-cal-new} as \begin{align} \label{eq:rewrite} \sum_{i \in [m]}\mathcal{D}(S_i)\abs{\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}]} = \sum_{i \in [m]}\mathcal{D}(S_i)\frac{\abs{\E_{\mathcal{D}}[S_i(x)c(\mathbf{x})(y - p_i)]}}{\mathcal{D}(S_i)} = \sum_{i \in [m]}\abs{\E_{\mathcal{D}}[S_i(x)c(\mathbf{x})(y - p_i)]} \end{align} \end{proof} \begin{proof}[Proof of Lemma \ref{thm:sub-pop}] By Lemma \ref{lem:m-cal-newer}, our goal is to show that for any $c' \in \mathcal{C}'$, \begin{align} \sum_{i \in [m]}\abs{\E_{\mathcal{D}'}[S'_i(x) c'(\mathbf{x}) (\mathbf{y} - p'_i)]} \leq \frac{(1 + \infnorm{\mathcal{C}'})\alpha}{\mathcal{D}(\mathcal{X}')}. \end{align} Observe that the expectations are of quantities supported on $\mathcal{X}'$, and for every $x \in X'$, $\mathcal{D}'_i(x) = \mathcal{D}_i(x)/\mathcal{D}(\mathcal{X}')$, so this is equivalent to showing that \begin{align*} \sum_{i \in [m]}\abs{\E_{\mathcal{D}}[S'_i(x) c'(\mathbf{x}) (\mathbf{y} - p'_i)]} \leq (1 + \infnorm{\mathcal{C}'})\alpha. \end{align*} We will bound the LHS using the triangle inequality as \begin{align} \label{eq:triangle} \sum_{i \in [m]}\abs{\E_{\mathcal{D}}[S'_i(x) c'(\mathbf{x}) (\mathbf{y} - p'_i)]} \leq \sum_{i \in [m]}\abs{\E_{\mathcal{D}}[S'_i(x) c'(\mathbf{x}) (\mathbf{y} - p_i)]} + \sum_{i \in [m]}\abs{\E_{\mathcal{D}}[S'_i(x) c'(\mathbf{x}) (p'_i- p_i)]}. \end{align} We claim that for every $x \in \mathcal{X}$, $S(x)c'(x) = S_i'(x)c'(x)$. This follows since $S_i(x) - S_i'(x) = 0$ for $x \in \mathcal{X}'$ and $c'(x) = 0$ for $x \not\in \mathcal{X}'$ since $c' \in \mathcal{C}'$ is supported on $\mathcal{X}'$. Hence we can bound the first term by \begin{align} \label{eq:bound-1} \sum_{i \in [m]}\abs{\E_{\mathcal{D}}[S'_i(x) c'(\mathbf{x}) (\mathbf{y} - p_i)]} = \sum_{i \in [m]}\abs{\E_{\mathcal{D}}[S_i(x) c'(\mathbf{x}) (\mathbf{y} - p_i)]} \leq \alpha. \end{align} For the second term, we apply the multicalibration\xspace\ condition to the indicator function of the set $\mathcal{X}'$: \begin{align*} \alpha \geq \sum_{i \in m}\E_{\mathcal{D}}[\mathcal{X}'(\mathbf{x})S_i(\mathbf{x})(\mathbf{y} - p_i)] = \sum_{i \in m}\abs{\E_{\mathcal{D}}[S'_i(\mathbf{x})(\mathbf{y} - p_i)]} = \mathcal{D}(S_i')|p_i - p_i'| \end{align*} where we use $S_i \cap \mathcal{X}' = S_i'$ so $\mathcal{X}'(x)S_i(x) = S_i'(x)$ and \[ p_i' = \E_\mathcal{D}[\mathbf{y}|\mathbf{x} \in S_i'] = \frac{\E_\mathcal{D}[S_i'(\mathbf{x})\mathbf{y}]}{\mathcal{D}(S_i')}. \] We then bound the second term on the RHS of Equation \eqref{eq:triangle} by \begin{align} \label{eq:bound-2} \sum_{i \in [m]}\abs{\E_{\mathcal{D}}[S'_i(x) c(\mathbf{x}) (p'_i- p_i)]} &\leq \sum_{i=1}^m|p_i - p_i'| \abs{\E_{\mathcal{D}}[S'_i(x) c(\mathbf{x})]}\notag\\ & \leq \sum_{i=1}^m|p_i - p_i'| \mathcal{D}(S_i') \infnorm{\mathcal{C}'}\leq \alpha \infnorm{\mathcal{C}'}. \end{align} The claim now follows by plugging in Equations \eqref{eq:bound-1} and \eqref{eq:bound-2} into Equation \eqref{eq:triangle}. \end{proof} \input{app_l2} \eat{ \subsection{Adding label noise for agnostic boosting} \label{app:noise} Following Kalai-Kanade \cite{kk09} and Feldman \cite{feldman2009distribution}, we show how one can reduce multicalibration\xspace\ to weak agnostic learning over a distribution with the same marginal on $\mathcal{X}$, by adding noise to the labels. We define a new distribution $\mathcal{D}''_i$ on $\mathcal{X} \times \ensuremath{\{0,1\}} \times \ensuremath{ \{\pm 1\} }$. We first sample $(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i$. We then sample $\mathbf{z} \in \ensuremath{ \{\pm 1\} }$ as a function of $\mathbf{y}$ so that $\E[\mathbf{z}|\mathbf{y}] = \mathbf{y} - p_i$ and $\mathbf{z}|\mathbf{y}$ is independent of $\mathbf{x}$. In other words, $\E[\mathbf{z}|\mathbf{y} =0] = -p_i$ and $\E[\mathbf{z}|\mathbf{y} = 1] = 1 -p_i$. Crucially the marginal distribution over $\mathcal{X}$ stays the same. \begin{lemma} Let $(\mathbf{x}, \mathbf{z}) \sim \mathcal{D}''_i$ and $(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i$. Then \begin{align} \E_{\mathcal{D}''_i}[\mathbf{z}] &= 0,\\ \E_{\mathcal{D}''_i}[c(\mathbf{x}) \mathbf{z}] &= \E_{\mathcal{D}_i}[c(\mathbf{x})(\mathbf{y} - p_i)] \end{align} \end{lemma} \begin{proof} We have \begin{align*} \E_{\mathcal{D}^0_i}[\mathbf{z}] &= \Pr_{\mathcal{D}_i}[\mathbf{y} =0]\E_{\mathcal{D}^0_i}[\mathbf{z}|\mathbf{y} = 0] + \Pr_{\mathcal{D}_i}[\mathbf{y} = 1]\E_{\mathcal{D}^0_i}[\mathbf{z}|\mathbf{y} = 1] = (1 - p_i)(-p_i) + p_i(1 - p_i) =0. \end{align*} Since $\E[\mathbf{z}|\mathbf{y}] = \mathbf{y} - p_i$, we have \begin{align*} \E_{\mathcal{D}^0_i}[c(\mathbf{x})\mathbf{z}] = \E_{\mathcal{D}^0_i}[c(\mathbf{x})\E_{D^0_i}[\mathbf{z}|\mathbf{y}, \mathbf{x}]] = \E_{\mathcal{D}_i}[c(x)(\mathbf{y} - p_i)]. \end{align*} \end{proof} It follows that $\mathcal{S}$ is multi-calibrated for $\mathcal{C}, \mathcal{D}$ iff $\E_{\mathcal{D}''_i}[c(\mathbf{x}) \mathbf{z}] \leq \alpha p_i(1 - p_i)$. To compare this to distribution reweighting, note that adding label noise keeps the marginal distribution on $\mathcal{X}$ the same. This is an advantage if we have a {\em distribution-specific} weak learner for $\mathcal{C}$. But with label noise, the weak learner has to detect a much lower correlation $\alpha p_i(1 - p_i)$, as opposed to $\alpha/2$ when we use distribution reweighting. } \section{Relation to prior definitions of multicalibration\xspace} \label{app:def-mcab} The work of \cite{hkrr2018, Jung20} and follow-up papers considers the setting of predictors $f:\mathcal{X} \rightarrow [0,1]$ and where $\mathcal{C}$ is a collection of subsets or equivalently of Boolean functions. Our work departs from this along some axes: \begin{enumerate} \item We consider partitions and not predictors. While this is a seemingly minor change, it lets us work with the covariance under the conditional distribution, which proves to be the right notion for numerous technical reasons. This is inspired by the works of \cite{gopalan2021multicalibrated} who introduced partitions for multicalibration\xspace in the unsupervised setting, for the problem of computing importance weights, and \cite{Kalai04} who uses covariance as a splitting criterion for boosting. \item We allow $\mathcal{C}$ to consist of arbitrary real-valued functions, not just Boolean functions. Real-valued functions have been considered for multiaccuracy\xspace \cite{kgz} but to our knowledge, not for multicalibration\xspace. In the Boolean setting, our definition is essentially equivalent to that of \cite{hkrr2018, Jung20}, under a suitable setting of parameters. \end{enumerate} \paragraph{Partitions versus Predictors} A predictor is a function $f: \mathcal{X} \rightarrow [0,1]$. The goal of our algorithm is to produce a predictor that approximates the ground truth values $f^*: \mathcal{X} \rightarrow [0,1]$. We say that $f$ is $\alpha$-calibrated for a set $S$ if \[ \abs{\E_{\mathbf{x} \sim \mathcal{D}|S}[f(\mathbf{x})] - \E_{\mathbf{y} \sim \mathcal{D}}[\mathbf{y}]} \leq \alpha. \] One can switch between the notions of predictors and partitions with only a small loss in parameters. We first show how to derive a predictor from a partition and vice versa. \begin{definition} \label{def:partition} For $\lambda > 0$, let $m = \lceil1/\lambda \rceil$ and let $J(\lambda) = \{J_i\}_{i=1}^m$ denote the partition of $[0,1]$ into disjoint intervals of width $\lambda$. Given a predictor $f: \mathcal{X} \rightarrow [0,1]$, the $\lambda$-canonical partition of $\mathcal{X}$ if given by $\mathcal{S}^f =\{S_i\}_{i=1}^m$ where $S_i = f^{-1}(J_i)$. \end{definition} Our notion of canonical partition is inspired by the notion of $\lambda$-discretization in \cite{hkrr2018}, however they discretize the range of $f$, rather than partition the domain $\mathcal{X}$. Suppose we start from a partition $\mathcal{S}$ and let $f = f^\mathcal{S}$ be its canonical predictor. The canonical $\lambda$-partion $\mathcal{S}^f$ for $f$ will merge together those states in $\mathcal{S}$ for which $\E[\mathbf{y}]$ lies in $J_i$, hence these expectations are all within $\lambda$ of each other. Hence the canonical predictor for $\mathcal{S}$ and $\mathcal{S}^f$ only differs from the canonical predictor for $\mathcal{S}$ by $\lambda$. In the other direction, if we start from $f$ and let $\mathcal{S} = \mathcal{S}^f$ be the $\lambda$-canonical partition, and $f^\mathcal{S}$ to be the corresponding canonical predictor, then $f^\mathcal{S}(x) = \E_{S_i}[\mathbf{y}]$ is simply the average of $f$ over all $x$ where $f(x) \in J_i$. If the predictor $f$ is $\alpha$-calibrated for the set $S_i$, then this average $\E_{S_i}[\mathbf{y}]$ is $\alpha$-close to $\E_{\mathbf{x} \in S_i}[f(\mathbf{x})] \in J_i$, hence $|f(x) - f^\mathcal{S}(x)| \leq (\alpha + \lambda)$ for any $x \in S_i$. \paragraph{Comparing the definitions for Boolean functions} Let us consider the family $\mathcal{C}$ to consist of Boolean functions $c: \mathcal{X} \rightarrow \ensuremath{\{0,1\}}$. We can associate each $c \in \mathcal{C}$ with the subset $c^{-1}(1) \subseteq \mathcal{X}$. The two relevant definitions for us are the notion of multicalibration\xspace\ from \cite{hkrr2018} and mean-multicalibration\xspace from \cite{Jung20}. Both definitions apply to families of sets and predictors, so we restate them specialized to the setting of a canonical predictor for a partition. \cite{Jung20} were interested in the case when $y \in [0,1]$, since their goal was to define multicalibration\xspace\ for higher moments. In our setting, we consider the Boolean case. \begin{definition} \cite{Jung20} \label{def:aaron} Let $\mathcal{C}$ be a collection of Boolean functions and let $\mathcal{S}$ be a partition. The canonical predictor associated with $\mathcal{S}$ is $\alpha$-mean multicalibrated if for every $c \in \mathcal{C}$ \begin{align} \label{eq:aaron} \Pr_{\mathcal{D}_i}[c(\mathbf{x}) =1]\abs{\E_{\mathcal{D}_i|c(\mathbf{x}) =1}[\mathbf{y}] - \E_{\mathcal{D}_i}[\mathbf{y}]} \leq \alpha. \end{align} \end{definition} This is a slight variation of the original definition of multicalibration\xspace\ from \cite{hkrr2018}, who required the RHS be bounded by $\alpha$, but then only consider those $i, c$ where $\E_{\mathcal{D}_i}[c(\mathbf{x}) \geq \gamma]$. The two definitions are equivalent up to a reparametrization, the above formulation handles the case of small sets by allowing the guarantee to degrade. See Remark 2.1 of \cite{Jung20}. In Equation \eqref{eq:multicalibration_corollary} we condition on $\mathbf{y}$ and consider the expectation of $c(\mathbf{x})$, whereas \eqref{eq:aaron} conditions on $c(\mathbf{x})$ and takes the expectation of $\mathbf{y}$. Conditioning on $\mathbf{y}$ extends naturally even to real-valued functions $c$ and Boolean labels $\mathbf{y}$, where the notion of conditioning on $c$ may not make sense. We also extend it to real-valued $\mathbf{y}$ by considering the event $\ind{\mathbf{y} \in J}$ for some interval $J$. But in fact the two definitions are equivalent when $c$ and $\mathbf{y}$ are both Boolean. \begin{lemma} \label{lem:eq-boolean} For Boolean functions $c$, Equation \eqref{eq:aaron} is equivalent to Equation \eqref{eq:m-cal}. \end{lemma} \begin{proof} Since $c$ is Boolean we have \begin{align*} \Pr_{\mathcal{D}_i}[c(\mathbf{x}) =1] &= \E_{\mathcal{D}_i}[c(\mathbf{x})]\\ \E_{\mathcal{D}_i|c(\mathbf{x}) =1}[\mathbf{y}] &= \frac{\E_{\mathcal{D}_i}[c(\mathbf{x})y]}{\E_{\mathcal{D}_i}[c(\mathbf{x})]}. \end{align*} We may assume $\E_{\mathcal{D}_i}[c(\mathbf{x})] \neq 0$, else the condition holds trivially. Multiplying both sides by $\E_{\mathcal{D}_i}[c(\mathbf{x})]$, we can rewrite Equation \eqref{eq:aaron} as \begin{align*} \abs{\E_{\mathcal{D}_i}[c(\mathbf{x})y] - \E_{\mathcal{D}_i}[c(\mathbf{x})]\E_{\mathcal{D}_i}[y] } \leq \alpha. \end{align*} The quantity on the left is $|\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), y]|$, hence this is identical to Equation \eqref{eq:m-cal}. \end{proof} \subsection{Proof of Lemma \ref{lem:l2}: Stronger bounds for the $\ell_2$ loss}\label{sec:l2_proof} \begin{proof} Since the squared loss is $1$-Lipschitz, by the argument in Equation \eqref{eq:real_reduction}, we can work with an $\epsilon$-discretization of the interval $[0,1]$ with at most $\epsilon$ loss. Therefore, for $l=\lceil 1/\epsilon \rceil$, let $y=j\epsilon$, for $j \in \{0,\dots,l\}$. For any $(x,y)$ we have \begin{align*} (g_w(x) - y)^2 = (g_w(x) - p_i)^2 + (p_i -y)^2 + 2(g_w(x) - p_i)(p_i - y). \end{align*} As in the proof of Theorem \ref{thm:key}, let use denote $\alpha_i = \CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}]$. Fixing $i \in [m]$ and taking expectations over $(\mathbf{x},\mathbf{y}) \sim \mathcal{D}_i$ \begin{align} \label{eq:sq-error} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[ (g_w(\mathbf{x}) - \mathbf{y})^2] &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(g_w(\mathbf{x}) - p_i)^2] + \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(p_i - \mathbf{y})^2]\notag\\ & + 2p_i\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [p_i - \mathbf{y}] + 2\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [g_w(\mathbf{x})(p_i - \mathbf{y} )] . \end{align} We can simplify all except the last term as \begin{align*} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[ (g_w(\mathbf{x}) - \mathbf{y})^2] &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[\ell_2(\mathbf{y}, g_w(\mathbf{x})]\\ \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(g_w(\mathbf{x}) - p_i)^2] &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(g_w(\mathbf{x}) - f^\mathcal{S}(\mathbf{x}))^2]\\ \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(p_i - \mathbf{y})^2] &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(f^\mathcal{S}(\mathbf{x}) - \mathbf{y})^2] = \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[\ell_2(\mathbf{y}, f^\mathcal{S}(\mathbf{x}))] \\ \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [p_i - \mathbf{y}] &= 0. \end{align*} For the last term in Equation \eqref{eq:sq-error} we can write, \begin{align*} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [g_w(\mathbf{x})(\mathbf{y} - p_i)] &= \sum_{t \geq 1}w_t \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [c_t(\mathbf{x})(\mathbf{y} - p_i)]\\ &= \sum_{t \geq 1}w_t\left[ \E_{ \mathbf{y} \sim \mathcal{D}_i} \E_{ \mathbf{x} \sim \mathcal{D}_i|\mathbf{y} }[c_t(\mathbf{x})\mathbf{y}] - \E_{ (\mathbf{x},\mathbf{y}) \sim \mathcal{D}_i }[c_t(\mathbf{x})p_i] \right]\\ &= \sum_{t \geq 1}w_t \left( \sum_j \left[ \Pr[\mathbf{y}=j\epsilon] \E_{ \mathbf{x} \sim \mathcal{D}_i|\mathbf{y}=j\epsilon }[c_t(\mathbf{x})j \epsilon]\right] - \E_{ \mathbf{x} \sim \mathcal{D}_i }[c_t(\mathbf{x})] \sum_j \left[ \Pr[\mathbf{y}=j\epsilon] \cdot j\epsilon\right] \right)\\ &= \sum_{t \geq 1}w_t \sum_j \left[ (j\epsilon\cdot\Pr[\mathbf{y}=j\epsilon])\left( \E_{ \mathbf{x} \sim \mathcal{D}_i|\mathbf{y}=j\epsilon }[c_t(\mathbf{x})] - \E_{ \mathbf{x} \sim \mathcal{D}_i }[c_t(\mathbf{x})] \right)\right]\\ &\le \sum_{t \geq 1}w_t \sum_j (j\epsilon) \alpha_i \le l \alpha_i \|w\|_1 \end{align*} where the state $S_i$ is $\alpha_i$-multicalibrated. Plugging back into Equation \eqref{eq:sq-error} and rearranging gives \begin{align*} \abs{\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[ \ell_2(\mathbf{y}, g_w(\mathbf{x}))] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [\ell_2(\mathbf{y}, f^\mathcal{S}(\mathbf{x}))] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(g_w(\mathbf{x}) - p_i)^2] } \leq l \alpha_i \|w\|_1. \end{align*} Now averaging over $i \in [m]$ with probability $\mathcal{D}(S_i)$ and plugging in $l=\lceil 1/\epsilon \rceil$ gives the desired inequality. \end{proof} \section{Omnipredictors\xspace for convex loss minimization} \label{sec:binary} In this section we consider the setting of binary labels where $\mathcal{Y} = \ensuremath{\{0,1\}}$. \subsection{Post-processing for nice loss functions} Given an $(B, \epsilon)$-nice loss function, there is a natural post-processing of the canonical predictor $f^\mathcal{S}$ that we will analyze. Rather than choose the value $k^*(p) \in \mathbb{R}$ which minimizes expected loss under $\B{p}$, we restrict ourselves to the best value from $I_\ell$. This restriction only costs us $\epsilon$ by the $\epsilon$-optimality property. \begin{definition} \label{def:k-ell} Given a nice loss function $\ell$, define the function $k_\ell: [0,1] \rightarrow I_\ell$ by \begin{align} \label{eq:def-kp} k_\ell(p) = \argmin_{t \in I_\ell} \E_{\mathbf{y} \sim \B{p}} \ell(\mathbf{y},t). \end{align} Given a partition $\mathcal{S}$ of $\mathcal{X}$, define the $\ell$-optimized hypothesis $h^\mathcal{S}_\ell: \mathcal{X} \rightarrow I_\ell$ as \[ h^\mathcal{S}_\ell(x) = k_\ell \circ f^\mathcal{S}(x). \] \end{definition} Since $\ell$ is convex as a function of $t$, so is \[ \E_{\mathbf{y} \sim \B{p}} \ell(\mathbf{y},t) = p\ell(0,t) + (1- p)\ell(1, t).\] Hence computing $k_\ell$ is a one-dimensional convex minimization problem, a classical problem with several known algorithms \cite{boydBook}. Being able to compute an $\epsilon'$-approximate solution suffices for us, we can absorb the $\epsilon'$ term into the error $\epsilon$, and pretend that $\ell$ is $(B, \epsilon + \epsilon')$-nice instead. We can view the hypothesis $h^\mathcal{S}_\ell$ as a function mapping $\mathcal{S}$ to $I_\ell$, since it is constant on each $S_i \in \mathcal{S}$, and its range is $I_\ell$. A simple consequence of the definition is that it is the best function in this class for minimizing expected loss. \begin{corollary} \label{cor:optimal} For all functions $h: \mathcal{S} \rightarrow I_\ell$, $\ell_\mathcal{D}(h^\mathcal{S}_\ell) \leq \ell_\mathcal{D}(h)$. \end{corollary} \begin{proof} We sample $\i \sim \mathcal{D}$ and then $\mathbf{x}, \mathbf{y} \sim \mathcal{D}_\i$ and show that the inequality holds conditioned on every choice of $\i =i$. Since $\mathbf{y} \sim D_i$ is distributed as $\B{p_i}$, \[ \ell_{\mathcal{D}_i}(h^\mathcal{S}_\ell) = \E_{\B{p_i}}[\ell(\mathbf{y}, k_\ell(p_i))] \leq \E_{\B{p_i}}[\ell(\mathbf{y}, h(S_i))] = \ell_{\mathcal{D}_i}(h) \] where the inequality is by Definition \ref{def:k-ell}. \end{proof} \subsection{Loss minimization through Multicalibration\xspace} \label{sec:main} Our main result in this section is the following theorem. \begin{theorem} \label{thm:key} Let $\mathcal{D}$ be a distribution on $\mathcal{X} \times \ensuremath{\{0,1\}}$, $\mathcal{C}$ be a family of real-valued functions on $\mathcal{X}$ and $\mathcal{L}(B,\epsilon)$ be the family of all $(B, \epsilon)$-nice loss functions. If the partition $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$, then the canonical predictor $f^\mathcal{S}$ is an $(\mathcal{L}, \mathcal{C}, 2\alpha B + \epsilon)$-omnipredictor\xspace. \end{theorem} The following lemma is the key ingredient in our result. Informally it says that $c$ has limited distinguishing power within each state of the partition. Specifically, that $c(x)$ is not much better at minimizing a loss than the function obtained by taking its conditional expectation within each state of the partition $\mathcal{S}$. \begin{lemma} \label{lem:better} Given $\ell \in \mathcal{L}$ and $c \in \mathcal{C}$, define the predictor $\hat{c}: \mathcal{S} \rightarrow I_\ell$ by \[ \hat{c}(x) = \clip\left(\E_{\mathcal{D}_i}[c(x)], I_\ell\right) \ \text{for} \ x \in S_i. \] We have \begin{align} \ell_\mathcal{D}(\hat{c}) \leq \ell_\mathcal{D}(c) + 2\alpha B + \epsilon. \end{align} \end{lemma} \begin{proof} By the convexity of $\ell$ we have \begin{align} \label{eq:use-conv} \ell_\mathcal{D}(c) = \E_{\mathcal{D}}[\ell(\mathbf{y}, c(\mathbf{x}))] = \E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i}\E_{\mathbf{x} \sim \mathcal{D}_\i|\mathbf{y}}[\ell(\mathbf{y}, c(\mathbf{x})] \geq \E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i}\left[\ell\left(\mathbf{y}, \E_{\mathbf{x} \sim \mathcal{D}_\i|\mathbf{y}}[c(\mathbf{x})]\right)\right]. \end{align} By Lemma \ref{lem:tech}, \[ \ell\left(\mathbf{y}, \E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]\right) \geq \ell\left(\mathbf{y}, \clip\left(\E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})], I_{\ell}\right)\right) - \epsilon.\] Plugging this into Equation \eqref{eq:use-conv}, we get \begin{align} \label{eq:loss-1} \ell_\mathcal{D}(c) \geq \E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i}\left[\ell\left(\mathbf{y}, \clip\left(\E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})], I_{\ell}\right)\right)\right] - \epsilon. \end{align} From the definition of $\hat{c}$, \begin{align} \label{eq:loss-2} \ell_\mathcal{D}(\hat{c}) = \E_{\mathcal{D}}[\ell(\mathbf{y}, \hat{c}(\mathbf{x}))] = \E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i}\left[\ell\left(\mathbf{y}, \clip\left(\E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})], I_{\ell}\right)\right)\right]. \end{align} Subtracting Equation \eqref{eq:loss-1} from Equation \eqref{eq:loss-2} we get \begin{align} \ell_\mathcal{D}(\hat{c}) - \ell_\mathcal{D}(c) \leq & \E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i}\left[\ell\left(\mathbf{y}, \clip\left(\E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})], I_{\ell}\right)\right) - \ell\left(\mathbf{y}, \clip\left(\E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})], I_{\ell}\right)\right) \right] + \epsilon . \label{eq:loss-3} \end{align} Since $\ell$ is $B$-Lipschitz on $I_{\ell}$ and $\clip(t,I_{\ell})$ is $1$-Lipschitz as a function of $t$, \begin{align} \ell\left(\mathbf{y}, \clip\left(\E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})], I_{\ell}\right)\right) & - \ell\left(\mathbf{y}, \clip\left(\E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})], I_{\ell}\right)\right) \notag\\ &\leq B\abs{\clip\left(\E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})], I_{\ell}\right) - \clip\left(\E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})], I_{\ell}\right)}\notag\\ &\leq B\abs{ \E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]}.\label{eq:lipschitz+} \end{align} Plugging this into Equation \eqref{eq:loss-3} gives \begin{align} \ell_\mathcal{D}(\hat{c}) - \ell_\mathcal{D}(c) - \epsilon &\leq B\E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i} \left| \E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]\right|\label{eq:use-this}\\ & = B\E_{\i \sim \mathcal{D}}\left[\sum_{b \in \ensuremath{\{0,1\}}}\Pr_{\mathcal{D}_\i}[\mathbf{y} =b]\left|\E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]\right|\right]\notag\\ &= B\sum_{b \in \ensuremath{\{0,1\}}}\E_{\i \sim \mathcal{D}}\left[\Pr_{\mathcal{D}_\i}[\mathbf{y} =b]\left|\E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]\right|\right]\notag\\ & \leq B \sum_{b \in \ensuremath{\{0,1\}}}\alpha = 2\alpha B\notag, \end{align} where the last inequality follows by the multicalibration condition (Equation \eqref{eq:multicalibration_corollary}). \end{proof} As a consequence we can now prove Theorem \ref{thm:key}. \begin{proof}[Proof of Theorem \ref{thm:key}] Let $h^\mathcal{S}_\ell= k_\ell \circ f^\mathcal{S}$ be the $\ell$-optimized hypothesis. It suffices to show that for any $c \in \mathcal{C}$ \begin{align} \label{eq:key} \ell_\mathcal{D}(h^\mathcal{S}_\ell) \leq \ell_\mathcal{D}(c) + 2\alpha B + \epsilon. \end{align} For any $c \in \mathcal{C}$, we have \[ \ell_\mathcal{D}(h^\mathcal{S}_\ell) \leq \ell_\mathcal{D}(\hat{c}) \leq \ell_\mathcal{D}(c) + 2\alpha B +\epsilon \] where the first inequality is by Corollary \ref{cor:optimal}, which applies since $\hat{c}$ is a function mapping $\mathcal{S}$ to $I_\ell$. The second is by Lemma \ref{lem:better}. \end{proof} Consider the family $\mathrm{Lin}_\mathcal{C}(W)$ of linear combinations over $\mathcal{C}$ of weight at most $W$. By Lemma \ref{lem:linear}, $\mathcal{S}$ is $\alpha W$-approximately multicalibrated\xspace\ for $\mathrm{Lin}_\mathcal{C}(W)$. Applying Theorem \ref{thm:key}, we derive the following corollary. \begin{corollary} \label{cor:lipschitz} Let $\mathcal{D}$ be a distribution on $\mathcal{X} \times \ensuremath{\{0,1\}}$, $\mathrm{Lin}_\mathcal{C}(W)$ be linear functions in $\mathcal{C}$ of with $\onenorm{w} \leq W$ (see eq.~\ref{eq:mLC}) and $\mathcal{L} = \mathcal{L}(B,\epsilon)$ be the family of all $(B, \epsilon)$-nice loss functions. If the partition $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$, then $f^\mathcal{S}$ is an $(\mathcal{L}, \mathrm{Lin}_\mathcal{C}(W), 2\alpha BW + \epsilon)$-omnipredictor\xspace. \end{corollary} To interpret this, assume we have an $(B, \epsilon)$-nice loss function and we wish to have a predictor that is within $2\epsilon$ of any function in $\mathrm{Lin}_\mathcal{C}(W)$. Corollary \ref{cor:lipschitz} says that it suffices to have an $\alpha$-approximately multicalibrated\xspace\ partition where $\alpha = \epsilon/2BW$. Note that algorithms for computing such partitions have running time which is polynomial in $1/\alpha$, which translates to running time polynomial in $BW/\epsilon$. We derive a corollary for sub-populations follows from Theorem \ref{thm:key} and \ref{thm:sub-pop}. For two families of functions $\mathcal{T}, \mathcal{P}: \mathcal{X} \rightarrow \mathbb{R}$, we define their product as \[ \mathcal{T} \times \mathcal{P} = \{c: c(x) = T(x)P(x), T \in \mathcal{T}, P \in \mathcal{P} \}. \] Note that in the case when $T \in \mathcal{T}$ is binary-valued, $\mathcal{T} \times \mathcal{P}$ contains the restriction of every $P \in \mathcal{P}$ to the support of $T$. \begin{corollary} \label{cor:sub_pop} Let $\mathcal{D}$ be a distribution on $\mathcal{X} \times \ensuremath{\{0,1\}}$, $\mathcal{T}$ be a family of binary-valued functions on $\mathcal{X}$, $\mathcal{P}$ be a family of real-valued functions and $\mathcal{L}(B,\epsilon)$ be the family of all $(B, \epsilon)$-nice loss functions. Let the partition $\mathcal{S}$ be $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{T} \times \mathcal{P}, \mathcal{D}$. For $T \in \mathcal{T}$, let $\alpha'=\alpha(1 + \infnorm{\mathcal{P}})/\mathcal{D}(T)$. Then the canonical predictor $f^\mathcal{S}$ is an $(\mathcal{L}, \mathcal{P}, 2\alpha' B + \epsilon)$-omnipredictor\xspace for the sub-population $T$. \end{corollary} To informally instantiate this for a simple case, let $\mathcal{T}, \mathcal{P}$ be the class of decision trees of depth $d_1$ and $d_2$ respectively. Let the partition $\mathcal{S}$ be multicalibrated with respect to decision trees of depth $d_1+d_2$. If we now consider any sub-population $T$ identified by decision trees of depth $d_1$, then the above result implies that the canonical predictor $f^\mathcal{S}$ is an omnipredictor\xspace for $T$, when compared against the class of decision trees of depth $d_2$ evaluated on $T$. \subsection{Limits for omnipredictors\xspace from multicalibration\xspace} \label{sec:limits} Corollary \ref{cor:lipschitz} shows that multicalibration\xspace for $\mathcal{C}$ gives omnipredictors\xspace for $\mathrm{Lin}_\mathcal{C}$. It is natural to ask whether we can get omnipredictors\xspace for a richer class of functions using multicalibration\xspace for $\mathcal{C}$. A natural candidate would be thresholds of functions in $\mathcal{C}$: \[ \mathrm{Thr_{\mathcal{C}}} = \{ \ind{c(x) \geq v}: c \in \mathcal{C}, v \in \mathbb{R}\}.\] Another natural extension would be to relax the convexity condition for loss functions in $\mathcal{L}$. We present a simple counterexample which shows that multicalibration\xspace for $\mathcal{C}$ is insufficient to give omnipredictors\xspace for both these classes. This shows that a significant strengthening of the bound from Corollary \ref{cor:lipschitz} might not be possible. \begin{lemma} There exists a distribution $\mathcal{D}$, a set $\mathcal{C}:\mathcal{X} \rightarrow \mathbb{R}$ of functions, and a $0$-multicalibrated\xspace partition $\mathcal{S}$ for $\mathcal{C}, \mathcal{D}$ such that for any $\delta < 1/4$, \begin{itemize} \item $f^\mathcal{S}$ is {\em not} an $(\mathcal{L}, \mathrm{Thr_{\mathcal{C}}}, \delta)$-omnipredictor\xspace for any $\mathcal{L}$ containing the $\ell_1$ loss function. \item $f^\mathcal{S}$ is {\em not} an $(\mathcal{L}, \mathcal{C}, \delta)$-omnipredictor\xspace for any $\mathcal{L}$ containing the (non-convex) loss function $\ell(y, t) = |y - \ind{t \geq 0}|$. \end{itemize} \end{lemma} \begin{proof} Let $\mathcal{D}$ be the distribution on $\ensuremath{\{0,1\}}^3 \times \ensuremath{\{0,1\}}$ where $\mathbf{x} \sim \ensuremath{\{0,1\}}^3$ is sampled uniformly and $\mathbf{y} = \ind{\sum_{i=1}^3 \mathbf{x}_i \equiv 0 \bmod 2}$ is the negated Parity function. Let $\mathcal{C} = \{\sum_i w_i x_i - w_0 \}$ be all affine functions. We claim the trivial partition $\mathcal{S} = \{\ensuremath{\{0,1\}}^3\}$ is $0$-multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$. This is because every $x_i$ is independent of $\mathbf{y}$, so their covariance is $0$. By linearity of expectation, the same is true for all functions in $\mathcal{C}$. Thus $f^\mathcal{S}(x) = 1/2$ for every $x \in \ensuremath{\{0,1\}}^3$. Now consider the $\ell_1$ loss. A simple calculation shows that for every $k:\ensuremath{\{0,1\}} \rightarrow \mathbb{R}$, $\bar{\ell}_1(k \circ f^\mathcal{S}, \mathcal{D}) \geq 1/2$. In contrast $h(x) = \ind{x_1 + x_2 + x_3 \geq 1.5} \in \mathrm{Thr_{\mathcal{C}}}$ gives $\bar{\ell}_1(h, \mathcal{D}) =1/4$, since it gets the two middle layers correct. This proves part (1). To deduce part (2), let $\ell(y, t) = |y - \ind{t \geq 0}|$ and $g(x) = x_1 + x_2 + x_3 -1.5 \in \mathcal{C}$. Note that \[ 1/4 = \bar{\ell}_1(h, \mathcal{D}) = \E_{\mathcal{D}}[|h(\mathbf{x}) - \mathbf{y}|] = \E_{\mathcal{D}}[|\ind{g(\mathbf{x}) \geq 0} - \mathbf{y}|] = \E_{\mathcal{D}} [\ell(\mathbf{y}, g(\mathbf{x}))] = \bar{\ell}(g, \mathcal{D}). \] In contrast, for any $k: [0,1] \rightarrow \mathbb{R}$, it follows that $\bar{\ell}(k \circ f^\mathcal{S}, \mathcal{D}) \geq 1/2$. \end{proof} In part (2), the loss function $|y - \ind{t \geq 0}|$ is not Lipshcitz or differentiable in $t$. We can ensure both these conditions by replacing it with the sigmoid function, which still preserves the correlation with parity, at the cost of some reduction in $\delta$ for which the bound holds \cite{Kalai04}. \eat{ \subsection{Loss minimization through Multi-calibration} In this section, we will prove the following result. \begin{theorem} \label{thm:key} Let $\ell$ be a $(I,B, \epsilon)$-nice loss function $\ell$. Let the partition $\mathcal{S}$ be $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$, and let $h^\mathcal{S}_\ell$ be the $\ell$-optimized hypothesis. Then for any $c \in \mathcal{C}$ and $i \in [m]$, \begin{align} \label{eq:key} E_{\mathcal{D}}[\ell(\mathbf{y}, h^\mathcal{S}_\ell(\mathbf{x})] \leq \E_{\mathcal{D}_i}[\ell(\mathbf{y}, c(\mathbf{x}))] + 2\alpha B + \epsilon. \end{align} \end{theorem} \begin{proof} We will show that \begin{align} \label{eq:key1} E_{\mathcal{D}_i}[\ell(\mathbf{y}, k_\ell(p_i)] \leq \E_{\mathcal{D}_i}[\ell(\mathbf{y}, c(\mathbf{x}))] + 2\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}] B + \epsilon. \end{align} To simplify notation, we denote $|\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y})]|$ by $\alpha_i$. The $\alpha$-approximate multicalibration\xspace\ condition guarantees that \[ \sum_i \mathcal{D}(S_i)\alpha_i \leq \alpha. \] We start with states where $p _i(1 -p_i) > 0$. Assume without loss of generality that $p_i \leq 1/2 \leq 1- p_i$. Recall that $\ell$ is $(I, B, \epsilon)$-nice. Fix $i \in [m]$. Define $z_0, z_1, v_0 , v_1$ by: \begin{align*} z_0 {:=} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} \left[ c(\mathbf{x}) \mid \mathbf{y} = 0\right], & \ \ z_1 {:=} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} \left[ c(\mathbf{x}) \mid \mathbf{y} = 1\right],\\ v_0 = \clip(z_0, I), & \ \ v_1 = \clip(z_1, I). \end{align*} By the definition of multicalibration\xspace\ (Equation \eqref{eq:m-cal-01}) we have \begin{align*} |z_1 - z_0| &= \left|\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} \left[ c(\mathbf{x}) \mid \mathbf{y} = 1\right] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} \left[ c(\mathbf{x}) \mid \mathbf{y} = 0\right]\right| \leq \frac{\alpha_i}{p_i(1 - p_i)}. \end{align*} Since $\ell(0, t)$ is $B$-Lipshcitz on $I$, and $\clip(t, I)$ is $1$-Lipschitz as a function of $t$, \begin{align} \label{eq:not-key} |\ell(0,v_1) - \ell(0, v_0)| \leq B|v_1 - v_0| \leq B|z_1 - z_0| \leq \frac{\alpha_i B}{p_i(1 - p_i)}. \end{align} We now claim the inequalities \begin{align} \label{eq:chain1} \ell(1, v_1) \leq \ell(1, z_1) + \epsilon \leq \E_{\mathcal{D}_i} \left[ \ell(1, c(\mathbf{x}))\mid \mathbf{y} = 1\right] + \epsilon\\ \label{eq:chain2} \ell(0, v_0) \leq \ell(0, z_0) + \epsilon \leq \E_{\mathcal{D}_i} \left[ \ell(0, c(\mathbf{x}))\mid \mathbf{y} = 0\right] + \epsilon \end{align} The first inequality is because clipping only increases the loss by $\epsilon$, and the second is by Jensen's inequality and the definition of $z_0/z_1$. We now have \begin{align*} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[\ell(\mathbf{y}, k_\ell(p_i))] &\leq \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[\ell(\mathbf{y}, v_0)] \ \ \ \ \text{by Definition of } k_\ell \\ & = p_i\ell(1,v_0) + (1- p_i)\ell(0, v_0) \\ & \leq p_i\left(\ell(1, v_1) + \frac{\alpha_i B}{p_i(1 - p_i)} \right)+ (1 - p_i)\ell(0, v_0) \ \ \ \ \text{By Equation} \ \eqref{eq:not-key}\\ & \leq p_i\left(\E_{\mathcal{D}_i} \left[ \ell(1, c(\mathbf{x}))\mid \mathbf{y} = 1\right] + \epsilon\right) + (1 - p_i)\left(\E_{\mathcal{D}_i} \left[ \ell(0, c(\mathbf{x}))\mid \mathbf{y} = 0\right] + \epsilon\right)\\ & + \frac{\alpha_i B}{(1 - p_i)} \ \ \ \ \ \ \ \text{By Equations} \ \eqref{eq:chain1}, \eqref{eq:chain2}\\ & \leq \E_{\mathcal{D}_i}[\ell(\mathbf{y}, c(\mathbf{x})] + 2\alpha_i B + \epsilon. \ \ \ \ \ \ \ \text{Since } 1 - p_i \geq 1/2 \end{align*} which proves Equation \eqref{eq:key1}. In the case where $p_i(1 -p_i) = 0$, assume $p_i =1$ for $S_i$, the case $p_i =0$ is symmetric. Then using Equation \eqref{eq:chain1} we have \[ \ell(1, k_\ell(1)) \leq \ell(1, v_1) \leq \ell(1, z_1) + \epsilon \leq \E_{\mathcal{D}_i}[\ell(1, c(\mathbf{x})] + \epsilon \] where the last inequality uses the fact that $\mathcal{D}_i|\mathbf{y} =1$ is the same as $\mathcal{D}_i$. Note that here $\alpha_i = \CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}] = 0$ since $\mathbf{y}$ is constant, so this is Equivalent to Equation \eqref{eq:key1}. We now average Equation \eqref{eq:key1} over the various states according to $\mathcal{D}(S_i)$ to complete the proof: \begin{align*} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[\ell(\mathbf{y}, f^\ell(\mathbf{x}))] &= \sum_{i \in [m]} \mathcal{D}(S_i)\E_{\mathcal{D}_i}[\ell(\mathbf{y}, t_i)] \leq \sum_{i \in [m]}\mathcal{D}(S_i)\left(\E_{\mathcal{D}_i}[\ell(\mathbf{y}, c(\mathbf{x}))] + 2\alpha_i B + \epsilon\right)\\ & = \E_{\mathcal{D}}[\ell(\mathbf{y}, c(\mathbf{x}))] + 2\alpha B + \epsilon. \end{align*} \end{proof} } \eat{ \begin{lemma} \label{lem:lipschitz} Let $\ell$ be an $(I, B, \epsilon)$-reasonable loss. For any $i \in [m]$ and predictor of the form $g_w(x) = w_0 + \sum_j w_j c_j(x)$, \begin{align*} \E_{(\mathbf{x} ,\mathbf{y}) \sim \mathcal{D}_i} [\ell(\mathbf{y}, t_i)] \leq \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} \left[ \ell(\mathbf{y}, g_w(\mathbf{x}))\right] + \alpha B \|w\|_1 + \epsilon, \end{align*} where $t_i = \arg\min_{t \in I} \E_{(\mathbf{x} ,\mathbf{y}) \sim \mathcal{D}_i} [\ell(\mathbf{y}, t)].$ \end{lemma} \begin{proof} For the proof we fix $i$ so we can drop $i$ subscripts and write $\mathcal{D}=D_i$, $\mathcal{D}^0=\mathcal{D}^0_i$. Define $z_\pm$ by: \begin{align*} z_+ &{:=} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ g_w(\mathbf{x}) \mid \mathbf{y} = 1\right]\\ z_- &{:=} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ g_w(\mathbf{x}) \mid \mathbf{y} = -1\right]. \end{align*} We have \begin{align*} \frac{z_+-z_-}{2} &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0} \left[ \mathbf{y} g_w(\mathbf{x}) \mid \mathbf{y} = 1\right] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0} \left[ \mathbf{y} g_w(\mathbf{x}) \mid \mathbf{y} = -1\right]\\ &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0} \left[ \mathbf{y} g_w(\mathbf{x}) \right]\\ &= w_0 \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0}[\mathbf{y}] + \sum_{j \geq 1}w_j\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0} \left[ \mathbf{y} g_w(\mathbf{x}) \right]\\ \frac{|z_+-z_-|}{2} &\leq \alpha\sum_{j\geq 1}|w_j| \leq \alpha \|w\|_1. \end{align*} In the above we have used the definition of multi-calibration, the fact that $\E_{\mathcal{D}^0}[\mathbf{y}]=0$ and the triangle inequality. Thus $|z_+-z_-|\leq \alpha \|w\|_1$. Let $t_\pm$ be $z_\pm$ clipped to $I$, respectively. It is not difficult to see that clipping can only increase loss by $\epsilon$, e.g., \begin{align} \ell(-1, t_-) \leq \ell(-1, z_-) + \epsilon \leq \E_{\mathcal{D}} \left[ \ell(-1, g_w(\mathbf{x}))\mid \mathbf{y}=-1\right] + \epsilon \end{align} The first inequality is because clipping only increase the loss by $\epsilon$, and the second is by Jensen's inequality and the definition of $z_-$. A similar inequality can be shown for $\ell(1, t_+)$. It is also not hard to see that $|t_+-t_-|\leq \alpha \|w\|_1$ since clipping can only reduce distances. Thus, \begin{align*} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[\ell(\mathbf{y},t)] \leq & \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[\ell(\mathbf{y},t_-)]\\ =& \Pr_\mathcal{D}[\mathbf{y} =-1]\ell(-1,t_-) + \Pr_\mathcal{D}[\mathbf{y} =1]\ell(1, t_-) \\ \leq& \Pr_\mathcal{D}[\mathbf{y} =-1]\ell(-1,t_-) + \Pr_\mathcal{D}[\mathbf{y} =1]\ell(1, t_+) + \alpha \|w\|_1 B \\ \leq& \Pr[\mathbf{y}=-1]\E_{\mathcal{D}} \left[ \ell(-1, g_w(\mathbf{x}))\mid \mathbf{y}=-1\right] + \epsilon \\ & + \Pr[\mathbf{y}=1]\E_{\mathcal{D}} \left[ \ell(1, g_w(\mathbf{x}))\mid \mathbf{y}=1\right] + \alpha \|w\|_1 B\\ =& \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ \ell(\mathbf{y}, g_w(\mathbf{x}))\right] + \epsilon + \alpha \|w\|_1 B. \end{align*} \end{proof} } \eat{ \subsection{Multi-dimensional Lipschitz cost} \newcommand{{l}}{{l}} \paragraph{Assumption.} Suppose there is a convex decision set $T \subseteq \mathbb{R}^d$ and a cost function ${l}:\ensuremath{\{0,1\}} \times T \rightarrow \mathbb{R}$ where both ${l}(0, t)$ and ${l}(1, t)$ are convex and $B$-Lipschitz it $t$. As before, we define the extension ${l}(p, t) = \E_{\mathbf{y} \sim \B{p}}[{l}(\mathbf{y}, t)$. For a partition $\mathcal{S}$, we define \begin{align*} t_i &= \arg\min_{t \in T} {l}(p, t)\\ f^\mathcal{S}_{l}(x) &= t_i \ \forall x \in S_i \end{align*} With this setup we have: \begin{lemma} Let $\mathcal{S}$ be $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$. Then for any $c \in \mathcal{C}$ we have \[ \E_{\mD}[\ell(\mathbf{y}, f^\mathcal{S}_{l}(\mathbf{x})] \leq \ell(\mathbf{y}, c(\mathbf{x})) + \alpha B + \epsilon. \] \end{lemma} \begin{lemma} \label{lem:lipschitz} For any $i \in [m]$ and linear decision function $g^w:\mathcal{X}\rightarrow T$ of the form $g^w(x) = \langle w_{0,k} + \sum_j w_{j,k}(x)\rangle_{k=1}^d$, \begin{align*} \min_{t \in T} \E_{(\mathbf{x} ,\mathbf{y}) \sim \mathcal{D}_i} [\ell(\mathbf{y}, t)] \leq \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} \left[ \ell(\mathbf{y}, g^w(\mathbf{x}))\right] +\alpha B \|w\|_1. \end{align*} \end{lemma} Note that in the above we have assumed that the linear function is bounded to $T$ as well. \begin{proof} For the proof we fix $i$ so we can drop $i$ subscripts and write $\mathcal{D}=D_i$, $\mathcal{D}^0=\mathcal{D}^0_i$. Define decision vectors $t^\pm \in T$ by: \begin{align*} t^+ &{:=} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ g^w(\mathbf{x}) \mid \mathbf{y} = 1\right]\\ t^- &{:=} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ g^w(\mathbf{x}) \mid \mathbf{y} = -1\right]. \end{align*} For any $k \in [d],$ we have: \begin{align*} \frac{t^+_k-t^-_k}{2} &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0} \left[ \mathbf{y} g^w_k(\mathbf{x}) \mid \mathbf{y} = 1\right] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0} \left[ \mathbf{y} g^w_k(\mathbf{x}) \mid \mathbf{y} = -1\right]\\ &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0} \left[ \mathbf{y} g^w_k(\mathbf{x}) \right]\\ &= w_{0,k} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0}[\mathbf{y}] + \sum_{j \geq 1}w_{j,k}\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}^0} \left[ \mathbf{y} g^w_k(\mathbf{x}) \right]\\ \frac{\|t^+-t^-\|}{2} &\leq \frac{\|t^+-t^-\|_1}{2} \leq\alpha\sum_{j\geq 1, k \in [d]}|w_{j,k}| \leq \alpha \|w\|_1 \end{align*} In the above we have used the definition of multi-calibration, the fact that $\E_{\mathcal{D}^0}[\mathbf{y}]=0$ and the triangle inequality. Thus $\|t^+-t^-\|\leq \|t^+-t^-\|_1 \leq \alpha \|w\|_1$. By Jensen's inequality, \begin{align} {l}(-1, t^-) \leq \E_{\mathcal{D}} \left[ {l}(-1, g^w(\mathbf{x}))\mid \mathbf{y}=-1\right], \end{align} and similarly for ${l}(1, t^+)$. Then, since $\|t^--t^+|\leq 2\alpha \|w\|_1$ and $c(1, \cdot)$ is $B$-Lipschitz, $c(1, t^-)\leq c(1, t^+) + 2\alpha \|w\|_1 B$, \begin{align*} \min_{t \in T}\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[{l}(\mathbf{y},t)] \leq & \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[{l}(\mathbf{y},t^-)]\\ =& \Pr_\mathcal{D}[\mathbf{y} =-1]{l}(-1,t^-) + \Pr_\mathcal{D}[\mathbf{y} =1]{l}(1, t^-) \\ \leq& \Pr_\mathcal{D}[\mathbf{y} =-1]{l}(-1,t^-) + \Pr_\mathcal{D}[\mathbf{y} =1]\left({l}(1, t^+) + 2\alpha \|w\|_1 B\right) \\ \leq& \Pr[\mathbf{y}=-1]\E_{\mathcal{D}} \left[ {l}(-1, g^w(\mathbf{x}))\mid \mathbf{y}=-1\right] + \\ & \Pr[\mathbf{y}=1]\E_{\mathcal{D}} \left[ {l}(1, g^w(\mathbf{x}))\mid \mathbf{y}=1\right] + 2 \alpha \|w\|_1 B Pr[\mathbf{y}=1]\\ =& \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ {l}(\mathbf{y}, g^w(\mathbf{x}))\right] + Pr[\mathbf{y}=1] \cdot 2 \alpha \|w\|_1 B . \end{align*} If $\Pr[\mathbf{y}=1]\leq 1/2$, then the above is the lemma statement. Otherwise, an analogous chain of inequalities using $t^+$ instead of $t^-$ shows gives the same bound above with $\Pr[\mathbf{y}=-1]$, which completes the proof. \end{proof} } \eat{ For $p \in [0,1]$, let $\mathbf{y} \sim \B{p}$ denote the Bernoulli random variable with parameter $p$. We can extend $\ell$ to a function $\ell: [0, 1] \times \mathbb{R} \rightarrow \mathbb{R}^+$ by defining \begin{align} \label{eq:def-lpt} \ell(p, t) = \E_{\mathbf{y} \sim \B{p}}[\ell(\mathbf{y},t)] = p\ell(1, t) + (1 - p)\ell(0, t). \end{align} to be the expected loss when we predict $t$ and the true label is $\mathbf{y} \sim \B{p}$. It follows that $\ell(p, t)$ is a non-negative convex function of $t$ for every $p$. We consider predictors obtained from a approximately multicalibrated\xspace\ partition by a simple post-processing step. To motivate these predictors, imagine first that we know the ground-truth values $f^*(x) = \E_\mathcal{D}[\mathbf{y}|\mathbf{x} = x]$ for every $x \in \mathcal{X}$. How would we make predictions to minimize our expected loss? To answer this question we need some notation. Define the function $k^*: [0,1] \rightarrow \mathbb{R}$ by \[ k^*(p) = \arg\min_{t \in \mathbb{R}} \ell(p,t). \] If $\ell(p, t)$ does not have a unique minimum, then there might be multiple choices for $k^*(p)$, and we can break ties arbitrarily. Note that $k^*$ depends on $\ell$ but is independent of the distribution $\mathcal{D}$ and the dataset. For instance, for the $\ell_1$ loss, $\ell_1(y, t) = |y -t|$, we have $k^*(p) = \mathbbm{1}^{\geq 0}(p -1/2)$, whereas for the $\ell_2$ loss $\ell_2(y,t) = (y -t)^2$, we have $k^*(p) = p$. Returning to the problem of loss minimization, for a point $x$, we suffer expected loss $\ell(f^*(x), t)$. Hence, by the definition of $k^*$, a prediction strategy which minimizes the expected loss over all predictors is to predict $k^*(f^*(x))$ for every $x \in \mathcal{X}$. The trouble is that this require knowledge of $f^*$. Now suppose $\mathcal{S}$ is a approximately multicalibrated\xspace\ partition for $\mathcal{C}, \mathcal{D}$. For $x \in S_i$, the value $p_i = \E_{\mathcal{D}_i}[\mathbf{y}]$ represents our best guess for $f^*(x)$. Hence it is natural to predict $k^*(p_i)$ at points in $S_i$ to minimize the loss. In what follows, we will prove that this predictor compares favorably to the best linear predictors of bounded $\ell_1$ norm. \subsection{Lipschitz loss functions and Predictors} } \section{Improved bounds for $\ell_1$ and $\ell_2$} In this section, we proved better bounds for $\ell_1$ and $\ell_2$ loss. \subsection{$\ell_1$ loss and agnostic learning} \section{Introduction} In machine learning, it is well-known that the best classifier may depend heavily on the choice of a loss function, and therefore correctly modeling the loss function is crucial for success in many applications. Modern machine learning libraries such as PyTorch, Tensorflow, and scikit-learn each offer a choice of over a dozen loss functions. However, this poses a challenge in applications where the loss is not known in advance or multiple losses may be used. For motivation, suppose you are training a binary classifier to predict whether a person has a certain medical condition ($y=1$), such as COVID-19 or some heart condition, given their attributes $x$. The cost for misclassification may vary dramatically, depending on the application. For an infectious disease, the question of whether an individual should be allowed to go out for a stroll is different than whether a person should be allowed to go to work in a nursing home. Similarly, deciding on whether to advise a daily dose of aspirin carries very different risks than recommending cardiac catheterization. Furthermore, medical interventions that may be developed in the future may carry yet other, unforeseen, risks and benefits that may require retraining with a different loss function. We adopt the following problem setup: we are given a distribution $\mathcal{D}$ on $\mathcal{X} \times \mathcal{Y}$ where $\mathcal{X}$ is the domain and $\mathcal{Y}$ is the set of labels (for example $\mathcal{Y}$ can be $\ensuremath{\{0,1\}}$ or $[0,1]$). On each $x$, we take an action $t(x) \in \mathbb{R}$, and suffer loss $\ell(y,t(x))$ which depends on the label $y$ and the action $t(x)$. We will refer to the function $t:\mathcal{X} \rightarrow \mathbb{R}$ which maps points in the domain to actions as the hypothesis. Our goal is to find a hypothesis that minimizes $\E_\mathcal{D}[\ell(\mathbf{y}, t(\mathbf{x}))]$ in comparison to some reference class of hypotheses.\footnote{Such a loss function that is the expectation of a loss for individual examples is called a decomposable loss in the literature.} We will refer to a function $f$ which maps $\mathcal{X}$ to probability distributions over $\mathcal{Y}$ as a predictor. The goal of a predictor is to model the conditional distribution of labels $\mathbf{y}|\mathbf{x} =x$ for every point in the domain. \eat{We will refer to a function $f: \mathcal{X} \rightarrow [0,1]$ as a predictor. A predictor's goal is to model the conditional probabilities $\E[$ } A classic example of different optimal hypotheses for different loss functions is the $\ell_2$ vs.\ $\ell_1$ losses which are minimized by the mean and median respectively. Consider a joint distribution $\mathcal{D}$ on $\mathcal{X} \times [0,1]$, where $\mathbf{x} \in \mathcal{X}$ is a set of attributes (given) and $\mathbf{y} \in [0,1]$ is an outcome. Consider an $x$ such that the corresponding $y$ is uniform in $[0.8,1]$ with probability $0.6$ and 0 with probability $0.4$. In this case, to minimize the expected $\ell_2$ loss $\ell(y, t) = (y-t)^2$ you would set $t(x)=0.45$, whereas to minimize the expected $\ell_1$ loss $\ell(y, t) = |y-t|$ you would set $t(x)=0.83$. Not only is $t$ different for the two losses, you cannot learn one from the other. In other words, learning to minimize the $\ell_2$ loss looses information that is necessary to minimize the $\ell_1$ loss and vice versa. \begin{comment} A classic example of different predictors for different loss functions is the $\ell_2$ vs.\ $\ell_1$ losses which are minimized by the average and median respectively. Consider a joint variable $(x,y)$, where $x$ is a set of attributes (given) and $y\in \{0,1\}$ is an outcome. A predictor $t$, trying to predict $y$ assigns a real-value $t(x)$ to each individual $x$. As a simple example, assume that $y$ is $1$ for $0.6$ of the individuals and $0$ for the rest. Assume also that the set of $1$'s is a random (or pseudorandom) subset. In this case, to minimize the expected $\ell_2$ loss $\ell(y, t) = (y-t)^2$ you would set $t\equiv 0.6$, whereas to minimize the expected $\ell_1$ loss $\ell(y, t) = |(y-t)|$ you would set $t\equiv 1$. \end{comment} The phenomenon that there is no simple way to get one loss-minimizing predictor from another is not unique to $\ell_2$ vs.\ $\ell_1$ losses. Consider the distribution illustrated in Figure \ref{fig:1}, which is known as a nested halfspace \cite{nested07}. Consider a common and simple family of loss functions where $\ell(y, t) = c_y |y-t|$ where $y \in \{0, 1\}$ and $c_0, c_1 \geq 0$ are the costs of false positives and false negatives respectively. Even for linear classification, as the ratio $c_0/c_1$ varies, a different direction is optimal. The standard ML approach of minimizing a given loss would require separate classifiers for each loss. There is no clear way to infer the optimal classifier for one set of costs from the classifier for another; applying standard post-processing techniques, such as Platt Calibration \cite{Platt99probabilisticoutputs} or Isotonic Regression \cite{isotonic01}, to the predictions so that $\Pr[y=1|t=z] \approx z$ will not fix the issue since the optimal direction is different. \subsection{Omnipredictors\xspace: one predictor to rule them all} This paper advocates a new paradigm for loss minimization: train a single predictor that could later be used for minimizing a wide range of loss functions, without having to further look at the data. Why should such predictors exist, and are they computationally tractable? One source of optimism is that the {\em ground-truth} predictor $f^*$ does allow exactly that. First consider the case of Boolean labels, and let $\mathcal{D}$ denote a distribution on $\mathcal{X} \times \ensuremath{\{0,1\}}$ (our results also apply to real-valued outcomes). We define $f^*(x) = \E_{\mathbf{y} \sim \mathcal{D}} [\mathbf{y}|x] \in [0,1]$ to be the conditional expectation of the label for $\mathbf{x}$. The value $t(x)$ which minimizes the loss $\E_{\mathbf{y}|x}[\ell(\mathbf{y},t(x))]$ depends only on $f^*(x)$. Furthermore, as long as $\ell$ is smooth and easy to compute, $t$ can easily be computed from $f^*$. We denote the univariate post-processing function that optimizes loss $\ell$ given true probabilities by $k_{\ell}^*: [0,1] \rightarrow \mathbb{R}$. So for example for $\ell_2(y, t)= (y -t)^2$, we have $k_{\ell_2}^*(p)=p$ and for $\ell_1(y,t) = |y -t|$, $k_{\ell_1}^*(p)= \ind{p \geq 1/2}$. \begin{SCfigure} \includegraphics[width=2.5in]{fig1_multicalibration.png} \caption{Binary classification with target function $\Pr[y=1|x] = \frac{x_1}{x_1+x_2}$ for $x \in [0.1,1]^2$. As can be seen from the level sets, the direction of the optimal linear classifier varies depending on the cost of false positives and negatives. This example is learned to near optimal loss for any loss with fixed costs of false-positives and false-negatives by an omnipredictor for the class ${\cal C}=\{x_1,x_2\}$.\label{fig:1}} \end{SCfigure} For every loss function $\ell$, the composition of $f^*$ and $k_{\ell}^*$ minimizes the loss $\ell$, even conditioned on complete knowledge of $\mathcal{D}$. The connection between perfect predictors and choosing the optimal action is well understood and plays an important role in the Statistics literature on proper scoring rules and forecasting (cf.\ \cite{Schervish}). But learning $f^*$ from samples from $D$ is information-theoretically and computationally impossible in general. The natural approach is to learn a model $f$ for $f^*$ and then compose $k_\ell^*$ with $f$. Common instantiations of this approach (such as using logistic regression to model $f$) do not yield particularly strong guarantees in the realistic non-realizable setting where $f^*$ does not come from the class of model distributions (see the further discussion in Section \ref{sec:related}). {\bf Our main conceptual contribution is to introduce the notion of Omnipredictors\xspace}, which provide a framework to derive strong rigorous guarantees using this composition approach even in the non-realizable setting. The goal of an omnipredictor\xspace\ is to learn a predictor $f$ that could replace $f^*$ for the purpose of minimizing any loss from a class $\mathcal{L}$ compared to some hypothesis class $\mathcal{C}$. For a family $\mathcal{L}$ of loss functions, and a family $\mathcal{C}$ of hypotheses $c: \mathcal{X} \rightarrow \mathbb{R}$, we introduce the notion of an {\bf (${\cal L},\mathcal{C}$)-omnipredictor\xspace}, which is a predictor $f:\mathcal{X} \rightarrow \ensuremath{[0,1]}$ with the property that for every loss function $\ell\in{\cal L}$, there is a post-processing function $k_{\ell}$ such that the expected loss of the composition $k_{\ell} \circ f$ measured using $\ell$ is almost as small as that of the best hypothesis $c\in \mathcal{C}$. \subsection{Omnipredictors\xspace for convex loss minimization} Omnipredictors\xspace can replace perfect predictors for the sake of minimizing loss in $\cal L$ compared with the class $\mathcal{C}$. In this sense they {\em extract all the predictive power} of $\mathcal{C}$ for such tasks. The key questions are of efficiency and simplicity: how strong a learning primitive do we need to assume to get an omnipredictor\xspace for $\mathcal{L},\mathcal{C}$, and how complex is the predictor. The main result of this paper is that {\bf one can efficiently learn simple omnipredictors\xspace for broad classes of loss functions and hypotheses, from weak learning primitives}. \paragraph{Our main result.} We show that for any hypothesis class $\mathcal{C}$, a {\em weak agnostic learner} for $\mathcal{C}$ is sufficient to efficiently compute an $(\mathcal{L}, \mathcal{C})$-omnipredictor\xspace where $\mathcal{L}$ consists of all decomposable convex loss functions obeying mild Lipshcitz conditions; it includes popular loss functions such as the $\ell_p$ losses for all $p$, the exponential loss and the logistic loss. Weak agnostic learnability captures a common modeling assumption in practice, and is a well-studied notion in the computational learning literature \cite{SBD2, KalaiMV08, kk09, feldman2009distribution}. The weak agnostic learning assumption says that if there is a hypothesis in $\mathcal{C}$ that labels the data reasonably well (say with $0$-$1$ loss of $0.7$), then we can efficiently find one that has a non-trivial advantage over random guessing (say with $0$-$1$ loss of $0.51$). In essence, our main result derives strong optimality bounds for a broad and powerful class of loss functions starting from a weak optimality condition for the $0$-$1$ loss. Perhaps surprisingly, our results are obtained not via the machinery of convex optimization, but by drawing a connection to work on fairness in machine learning, specifically the notion of multicalibration\xspace \cite{hkrr2018}. Multicalibration\xspace is a notion motivated by the goal of preventing unfair treatment of protected sub-populations in prediction; it does not explicitly consider loss minimization. We draw a connection to omnipredictors\xspace using a covariance-based recasting of the notion of multicalibration\xspace, that clarifies the connection of multicalibration\xspace\ to the literature on boosting \cite{kalai2005boosting, Kalai04, kk09}. A multicalibrated predictor satisfying this definition can be computed by a branching program, building on existing work in the literature on boosting \cite{MansourM2002, kalai2005boosting, Kalai04} and multicalibration \cite{gopalan2021multicalibrated}. This new connection shows that the well-known boosting by branching programs algorithms \cite{ KearnsM99, MansourM2002} yield multicalibrated predictors and can in fact be used to derive strong guarantees for a broad family of convex loss functions. The post-processing function $k_{\ell}$ used in our positive results is essentially $k^*_{\ell}$ with small modifications. As the example in Figure \ref{fig:1} demonstrates, even in natural cases, an (${\cal L},\mathcal{C}$)-omnipredictor\xspace cannot be a function in $\mathcal{C}$; in other words, the learning task we solve is inherently not proper. \paragraph{Omnipredictors\xspace for larger classes.} An advantage of our covariance-based notion of multicalibration\xspace is that it is closed under linear combinations. We use this to show that any multicalibrated\xspace\ predictor for $\mathcal{C}$ is in fact an $( \mathcal{L},\mathrm{Lin}_\mathcal{C})$-omnipredictor\xspace where $\mathrm{Lin}_\mathcal{C}$ consists of linear combinations of functions in $\mathcal{C}$. We give negative results for slightly larger classes, showing that a multicalibrated\xspace\ predictor for $\mathcal{C}$ is not necessarily an omnipredictor\xspace for the class $\mathrm{Thr_{\mathcal{C}}}$ which consist of thresholds of functions in $\mathcal{C}$. Similarly, it is need not be an omnipredictor\xspace for the class $\mathcal{C}$ but with non-convex loss functions. This shows that the connection between multicalibration\xspace and omnipredictors\xspace that we present is fairly tight. \paragraph{Omnipredictors\xspace for multi-group loss minimization} A very recent line of research defines multi-group notions of loss minimization~\cite{BlumLyk20,RothblumYon21}.\footnote{The notion of loss in~\cite{RothblumYon21} is more general than in this paper and includes global functions of loss rather than the expectation of loss on individual elements. See further comparison in Section~\ref{sec:related}.} Multi-group loss minimization is well motivated from the point of view of fairness as it guarantees that no sub-population's loss is sacrificed for the sake of global loss minimization. Say we have a collection of sub-populations $\cal T$ and hypotheses $\cal P$ and seek to take actions such that for every set $T \in \cal T$, our actions can compare with the best hypothesis in $P \in \cal P$ for that sub-population $T$. Indeed, one may wish to vary the loss function for various subgroups: say in a medical scenario where different age-groups are known to react differently to the same treatment. We derive strong multi-group loss minimization guarantees using the closure of multicalibration\xspace under conditioning on subsets in $\mathcal{C}$. We show that in the scenario above, a multicalibrated\xspace predictor for $\mathcal{T} \times \mathcal{P} = \{ T \cdot P, T \in \mathcal{T}, P \in \mathcal{P}\}$ gives an $(\mathcal{L}, \mathcal{P})$-omnipredictor\xspace for every sub-population $T \in \cal T$. Hence given a sub-population $T \in \cal T$ and a loss $\ell \in \mathcal{L}$, the predictions of the omnipredictor\xspace can be post-processed to be competitive with the best hypothesis from $\cal P$ for that loss function $\ell$ and sub-population $T$. \paragraph{Omnipredictors\xspace for real-valued labels.} We extend the notion of omnipredictors\xspace\ to the setting where the labels come from an arbitrary subset $\mathcal{Y} \subseteq \mathbb{R}$. Our primary interest is in multi-class prediction where $\mathcal{Y} = [k]$ and the bounded real-valued setting where $\mathcal{Y} = \ensuremath{[0,1]}$. We show that omnipredictors\xspace can be learned in this setting, for similar families of loss functions, again assuming weak learnability of $\mathcal{C}$. We also show a stronger bound for the $\ell_2$ loss than what the general theorem implies. \subsection{Multicalibration\xspace and agnostic boosting} One of our contributions in this work is to formalize and leverage the connections between multicalibration\xspace\ and the literature on agnostic boosting. We propose a covariance-based recasting of the notion of multicalibration\xspace, inspired by the literature on boosting \cite{Kalai04, kk09}. We show that this definition has several advantages, for instance it implies some general closure properties for multicalibration\xspace. In the other direction, our work suggests {\bf multicalibration\xspace as a solution concept for agnostic boosting}. By specializing our main result on omnipredictors\xspace to the $\ell_1$ loss, we derive a new proof of the classic result of \cite{KKMS08} on agnostic learning. We elaborate on these connections in this subsection. \paragraph{A covariance-based formulation of multicalibration\xspace.} Calibration has been well-studied in the statistics literature in the context of forecasting \cite{Dawid}. It was introduced to the algorithmic fairness literature by \cite{KleinbergMR17}. In the setting of Boolean labels, we are given a distribution $\mathcal{D}$ on $\mathcal{X} \times \ensuremath{\{0,1\}}$ of labelled examples, and wish to learn a predictor $f: \mathcal{X} \rightarrow [0,1]$, where $f(x)$ is our model for $\E_\mathcal{D}[\mathbf{y}|x]$. The predictor $f$ is (approximately) calibrated if for every value $v$ in its range we have that $\Pr[y=1|f(x)=v] \approx v$. This means that the prediction $f(x)$ can be interpreted as a probability that is correct in expectation over individuals in the same level set of $f$. By itself, calibration is a very weak property, both in terms of fairness as well as in terms of accuracy. \eat{Consider a set $T\subseteq \mathcal{X}$ for which half of the times $y=1$ and half of the times $y=0$. A predictor $p$ that $\forall x\in T$ sets $p(x)=1/2$ is calibrated on $T$ but has very little predictive power. Furthermore, if $T$ is a protected set, such $p$ may be the source of unfair discrimination towards those members of $T$ that see a positive outcome (or a negative outcome, depending on context). } This motivated \cite{hkrr2018} to introduce the notion of multicalibration that asks for $f$ to be calibrated on a rich collection of subgroups $\mathcal{C}$ rather than just a few protected sets. We draw a connection to omnipredictors\xspace by introducing a covariance-based recasting of the notion of multicalibration\xspace, that clarifies the connection to the literature on boosting \cite{Kalai04, kalai2005boosting, kk09}. Prior definitions consider multicalibration\xspace for a family $\mathcal{C}$ of sets or equivalently Boolean functions $c: \mathcal{X} \rightarrow \ensuremath{\{0,1\}}$, whereas we allow arbitrary real-valued functions. Rather than work with predictors, we define multicalibration\xspace for partitions, inspired by the recent work of \cite{gopalan2021multicalibrated} in the unsupervised setting. A partition $\mathcal{S} = \{S_1, \ldots, S_m \}$ of the domain is a collection of disjoint subsets whose union is $\mathcal{X}$. Intuitively, we want these sets to be (approximate) level sets for $f^*$. We let $\mathcal{D}_i$ denote the distribution $\mathcal{D}$ conditioned on $\mathbf{x} \in S_i$. The partition $\mathcal{S}$ gives a {\em canonical predictor} $f^\mathcal{S}$ where for each $x \in S_i$, we predict $f^\mathcal{S}(x) = \E_{\mathcal{D}_i}[\mathbf{y}]$. In analogy to boosting (see, e.g., \cite{Kalai04, kalai2005boosting, kk09}), we phrase multicalibration\xspace in terms of the covariance\footnote{Recall that $\CoVar[\mathbf{z}_1\mathbf{z}_2] = \E[\mathbf{z}_1\mathbf{z}_2] - \E[\mathbf{z}_1]\E[\mathbf{z}_2]$} between $c(\mathbf{x})$ and $\mathbf{y}$ conditioned on each state $S_i$ of the partition. We say that $\mathcal{S}$ is $\alpha$-multicalibrated\xspace for $\mathcal{C}$ if for every $i \in [m]$ and $c \in \mathcal{C}$, \begin{align} \label{eq:m-cal-int} \abs{\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}]} \leq \alpha. \end{align} In reality, we will weaken the definition to only hold in expectation under $\mathcal{D}$ rather than require it for every state of the partition, but we ignore this distinction for now. While our definition is formulated differently, we show that it matches the original definition when $\mathcal{C}$ consists of Boolean functions (see Lemma \ref{lem:eq-boolean} and the discussion in Appendix \ref{app:def-mcab}). This lets us adapt existing algorithms in the literature \cite{MansourM2002, Kalai04, gopalan2021multicalibrated} to give an efficient procedure to compute multicalibrated partitions, assuming a weak agnostic learner for the class $\mathcal{C}$. Working with covariance which is bilinear lets us derive powerful closure properties for multicalibration\xspace. For instance, if $f$ is multicalibrated with respect to $\mathcal{C}$ it is also multicalibrated (with some deterioration in parameters) with respect to the class $\mathrm{Lin}_\mathcal{C}$ of (sparse) linear combinations of $\mathcal{C}$. We also show that conditioning on sets in $\mathcal{C}$ preserves multicalibration\xspace. \paragraph{Agnostic boosting from multicalibration\xspace.} The problem of agnostically learning a class $\mathcal{C}$ is, given samples from a distribution $\mathcal{D}$ on $\mathcal{X} \times \ensuremath{\{0,1\}}$, find a binary classifier $f:\mathcal{X} \rightarrow \ensuremath{\{0,1\}}$ whose classification error aka $0$-$1$ loss defined as $\mathrm{err}(f) = \Pr_{\mathcal{D}}[f(\mathbf{x}) \neq \mathbf{y}]$ is not much larger than that of the best classifier from $\mathcal{C}$. The boosting approach to agnostic learning is to start from a weak agnostic learner, which only guarantees some non-trivial correlation with the labels, and boost it to obtain a classifier that agnostically learns $\mathcal{C}$ \cite{SBD2, KalaiMV08, feldman2009distribution}. Our work suggests multicalibration\xspace as a solution concept for agnostic boosting. Indeed, our definition of multicalibration\xspace based on covariance parallels that of \cite{Kalai04, kalai2005boosting}, who use covariance as a splitting criterion. Hence when the algorithms of \cite{MansourM2002, Kalai04, kalai2005boosting} terminate, they have found a multicalibrated\xspace partition. Viewed in this light, our results show that these algorithms give a broad and powerful guarantee beyond just $0$-$1$ loss: they are competitive with sparse linear combinations over $\mathcal{C}$ in optimizing a large family of convex, Lipschitz loss functions (with a simple post-processing step). While AdaBoost or Logistic regression are known to minimize the exponential and logistic loss respectively over sparse linear combinations of $\mathcal{C}$ \cite{SSbook}, no similar result was known for algorithms based on branching programs \cite{MansourM2002, Kalai04, kalai2005boosting}. Let us now focus on $0$-$1$ loss. Since $0$-$1$ loss for Boolean functions equals $\ell_1$ loss, our results apply to it. We show that for any multicalibrated\xspace partiton $\mathcal{S}$, the predictor $k_{\ell_1} \circ f^\mathcal{S}$ is competitive not just with the best classifier in $\mathcal{C}$, but with the best classifier in the larger class $\mathcal{H}$ of functions that are approximated (in $\ell_1$) by linear combinations of $\mathcal{C}$. This lets us re-derive the classic result of \cite{KKMS08} on agnostic learning. While not a new result, we feel that our treatment clarifies and unifies existing results (see Theorem \ref{thm:ag} and the comments following it). It strengthens known results on the noise-tolerant boosting abilities of such programs \cite{kalai2005boosting, KalaiMV08}. Further, we show examples where $\mathrm{err}(k_{\ell_1} \circ f^\mathcal{S})$ is markedly better than any linear combination of $\mathcal{C}$, showing that multicalibration\xspace is a stronger solution concept than those considered previously. \subsection{Technical overview: Omnipredictors\xspace from multicalibration\xspace} Let $\ell: \ensuremath{\{0,1\}} \times \mathbb{R} \rightarrow \mathbb{R}$ be a loss function that takes a label $y \in \mathcal{Y}$ and an action $t \in \mathbb{R}$ as arguments. A hypothesis $t: \mathcal{X} \rightarrow \mathbb{R}$ which prescribes an action for every point in the domain suffers a loss of $E_\mathcal{D}[\ell(\mathbf{y}, t(\mathbf{x})]$. Our main technical result states that if $\mathcal{S}$ is multicalibrated\xspace, then $f^\mathcal{S}$ is an $(\mathcal{L},\mathcal{C})$-omnipredictor\xspace where $\mathcal{L}$ consists of all convex losses satisfying some mild Lipschitz conditions. Here for simplicity, we make the stronger assumption that the loss $\ell(y, t)$ is convex and Lipschitz everywhere as a function of $t$. We do not assume anything about the relation between $\ell(0,t)$ and $\ell(1,t)$. We sketch how multicalibration\xspace leads $f^\mathcal{S}$ to be an omnipredictor\xspace, emphasizing intuition over rigor. We will argue that the loss $\E_\mathcal{D}[\ell(\mathbf{y}, k^*_\ell(f^\mathcal{S}(\mathbf{x}))]$ is not much more than $\E_\mathcal{D}[\ell(\mathbf{y},c(\mathbf{x}))]$ for any $c \in \mathcal{C}$. We fix a state $S_i \in \mathcal{S}$ and analyze the loss suffered by $c(x)$ under $\mathcal{D}_i$ as follows. \begin{enumerate} \item {\bf Reduction to predicting two values:} In general, $c(x)$ could take on many values under $\mathcal{D}_i$. However, since the goal is to minimize $\E_{\mathcal{D}_i}[\ell(\mathbf{y}, c(\mathbf{x}))]$, we can {\em pretend} that $c$ takes only two values, $\E_{\mathcal{D}_i|\mathbf{y} =0}[c(\mathbf{x})]$ whenever $\mathbf{y} =0$ and $\E_{\mathcal{D}_i|\mathbf{y} = 1}[c(\mathbf{x})]$ whenever $\mathbf{y} =1$ (we say pretend since the actions taken can only depend on $x$ and not on $y$). By the {\em convexity} of the loss functions, this can only reduce the expected loss. \item {\bf Reduction to predicting one value: } A consequence of multicalibration\xspace, which follows from the definition of covariance, is that conditioning on the label $\mathbf{y} =b$ does not change the expectation of $c(\mathbf{x})$ much. Formally for $b \in \ensuremath{\{0,1\}}$, \begin{align} \Pr_{\mathcal{D}_i}[\mathbf{y} = b]\left|\E_{\mathcal{D}_i|\mathbf{y} = b}[c(\mathbf{x})] - \E_{\mathcal{D}_i}[c(\mathbf{x})]\right| \leq \alpha. \label{eq:multicalibration_corollary_int} \end{align} Since the loss functions $\ell(b, t)$ are {\em Lipschitz} in $t$ for $b \in \ensuremath{\{0,1\}}$, we can replace $\E_{\mathcal{D}_i|\mathbf{y} = b}[c(\mathbf{x})]$ with $\E_{\mathcal{D}_i}[c(\mathbf{x})]$ with only a small increase in the loss. At this point, we have reduced to the case where $c$ predicts the constant value $\E_{\mathcal{D}_i}[c(\mathbf{x})]$ under $\mathcal{D}_i$. \item {\bf The best value: } Let $\E_{\mathcal{D}_i}[\mathbf{y}] = p_i$, thus $\mathbf{y}$ is distributed as a Bernoulli random variable with parameter $p_i$. Thus, the best single value to predict is $k^*_\ell(p_i)$, which is the minimizer of the expected loss $p_i \ell(0, t) + (1 - p_i)\ell(1, t)$. But we defined $f^\mathcal{S}(x) = p_i$ for all $x \in S_i$, so $k^*_\ell(p_i) = k^*_\ell(f^\mathcal{S}(x)$). \end{enumerate} We conclude that post-processing the predictions $f^\mathcal{S}$ by the function $k^*_\ell$ is nearly as good as any $c \in \mathcal{C}$ for minimizing expected loss under $\mathcal{D}$ for any convex, Lipschitz loss function $\ell$ (up to an additive error that goes to $0$ with $\alpha$). Hence $f^\mathcal{S}$ is an $(\mathcal{L}, \mathcal{C})$-omnipredictor\xspace. As a consequence, having a weak agnostic learner for $\mathcal{C}$ suffices to learn a predictor that can minimize any such loss function competitively to predictors in $\mathcal{C}$, even without knowing the loss function in advance. \eat{ Our {\bf main result} is that {\em every $\tilde{f}$ that is multicalibrated with respect to $\mathcal{C}$ is also $({\cal L},\mathcal{C})$-omnipredictor\xspace, where ${\cal L}$ contains all convex loss functions with some mild Lipshitz condition} (See Theorem~\ref{} for a formal statement). \UW{Here we switched from multi calibrated partitions to multi calibrated predictors. Instead of saying every $\tilde{f}$ we should say every canonical predictor of a multi-calibrated partition.} The main result implies that loss-oblivious loss-minimization through omnipredictors\xspace is feasible. In addition, we show the following: \begin{itemize} \item Using the aforementioned closure properties for multicalibration, we obtain that multicalibration with respect to $\mathcal{C}$ implies omnipredictor\xspace with respect to sparse linear combinations of functions from $\mathcal{C}$. \item As a corollary of our main result, loss minimization for a wide family of loss functions reduces to distribution-specific weak-agnostic learning. \item We extend our results to real-valued outcomes by generalizing omnipredictors\xspace to this context and showing that multicalibration for real-valued outcomes (which can be learned via~\cite{Jung20}) implies omnipredictors\xspace. \item We look more closely at $\ell_2$ and $\ell_1$ losses and give stronger results than for generic loss functions. In particular, we demonstrate that multicalibration can be strictly better than every function in $\mathcal{C}$. \end{itemize} \PG{Say more about results in the agnostic setting}} \subsection{Organization of this paper} We survey related work in Section \ref{sec:related}, and set up notation in Section \ref{sec:notation}. We define the notion of omnipredictors\xspace in Section \ref{sec:omni}. We introduce our notion of multicalibration\xspace in Section \ref{sec:mcab} and derive closure properties for it in Section \ref{sec:closure}. A detailed discussion of how our definition compares to previous definitions can be found in Appendix \ref{app:def-mcab}. We prove our main result on $(\mathcal{L}, \mathcal{C})$-omnipredictors\xspace for binary labels (Theorem \ref{thm:key}) in Section \ref{sec:binary}, along with the extensions to $\mathrm{Lin}_\mathcal{C}$ (Corollary \ref{cor:lipschitz}), and its application to multi-group loss minimization (Corollary \ref{cor:sub_pop}). Section \ref{sec:limits} shows that multicalibration\xspace for $\mathcal{C}$ does not yield omnipredictors\xspace for thresholds of $\mathcal{C}$ or for non-convex losses. Section \ref{sec:ag} presents applications of our results to agnostic learning, and an example showing that multicalibration\xspace can give stronger guarantee than $\mathrm{OPT}(\mathrm{Lin}_\mathcal{C})$. We present the extension to the real valued setting in Section \ref{sec:real}, and derive a stronger bound for $\ell_2$ loss in Theorem \ref{thm:ell_2}. We present an algorithm for computing multicalibrated partitions in Section \ref{sec:algo}. \eat{ The guarantees we present for omnipredictors\xspace are reminiscent of agnostic boosting \cite{KearnsM99, MansourM2002, Kalai04} in the sense that they apply to a larger class ${\cal H} \supset {\cal C}$ using a learner for ${\cal C}$. Agnostic boosting guarantees a 0-1 loss $|y-t|$ close to the optimal in ${\cal H}$. In fact, as we point out in Section \ref{sec:boosting}, omnipredictor\xspace guarantees are stronger. First, they imply optimality with respect to ${\cal H}$ just as agnostic boosting algorithms do. Second, we give a simple example illustrating where omnipredictors\xspace guarantee loss below the best in ${\cal H}$. Third, of course omnipredictors\xspace apply to more general families of loss functions than 0-1 loss. Note that noiseless boosting (e.g., AdaBoost \cite{freund1997decision}) and PAC learning, more generally, are not interesting for omnipredictors\xspace as in such a ``realizable'' setting one can achieve $\epsilon$ error, which implies low loss with respect to all bounded loss functions. } \eat{ \subsection{Our Contributions} The main contribution of this paper is introducing the notion of omnipredictors\xspace as an effective method of learning for loss-minimization that doesn't depend on the loss function at the time of learning. We show how to implement omnipredictors\xspace through a connection to multicalibrated predictors. We conclude that distribution-specific weak-agnostic learning is sufficient for minimizing every convex loss-function that satisfies some mild Lipschitz conditions. Beyond these contributions, we make a sequence of additional, technical and conceptual contributions, including: \begin{itemize} \item We give a new formulation of multicalibration that identifies with the original definition in the basic setting but generalizes well to real valued functions $c$ (instead of the indicators of sets) and to real-valued outcomes. This characterization also allows us to prove a useful closure properties with respect to sparse linear combinations and with respect to subsets. \item We give stronger results for two of the most important loss functions: $\ell_2$ and $\ell_1$ (classification loss), showing that at times multicalibration can do strictly better than any function in $\mathcal{C}$. \item We demonstrate that multicalibration is a strong solution concept for agnostic boosting by {\bf clarifying/ simplifying/ strengthening} previous work in the area. {\bf be more specific?} \item We show how to provide omnipredictors\xspace that allow for the simultaneous minimization of the loss function on a large collection of sub-groups, without knowing the exact loss functions a-priori. \end{itemize} } \section{Differentiable loss functions} The assumptions in the previous section do not apply for some commonly used loss functions including the exponential loss $\ensuremath{\ell_{\exp}}(y, \hat{y}) =\exp(-y\hat{y})$ and logistic loss, given by $\llog(y, \hat{y}) = \log(1 + \exp(-y\hat{y}))$, since for both these functions, the minima occur as $\hat{y}$ goes to $-\infty$. We postulate properties that these (and other) loss functions have which suffice to prove that multicalibration\xspace\ gives near optimal predictors. We require our loss functions to differentiable as a function of $\hat{y}$, and we use $\ell'(y, \hat{y})$ to denote $\partial \ell/\partial \hat{y}$. Consider the state $S_i$ where $\E_{\mathcal{D}_i}[\mathbf{y}] = \eta_i$. What constant value $t_i$ should we predict to minimize the loss? Let $\mathbf{y} \sim \eta_i$ denote a random variable $\mathbf{y} \in \ensuremath{ \{\pm 1\} }$ with expectation $\eta_i$. Define the expected loss function \begin{align} \label{ew:def-bar-l} \bar{\ell}(\eta_i, t) = \E_{\mathbf{y} \sim \eta_i} [\ell(\mathbf{y}, t)] = \frac{1 + \eta_i}{2}\ell(1, t) + \frac{1 - \eta_i}{2}\ell(-1, t). \end{align} and note that it is also convex and differentiable. Differentiating with respect to $t$, minima must satisfy the equation \begin{align} \label{eq:key} (1 + \eta_i)\ell'(1, t) + (1 - \eta_i)\ell'(-1, t) = 0. \end{align} The properties we need from our loss functions are that there exist minima where the derivative of $\ell$ is not too large. We state this formally below: There exists $B >0$ so that for every $\eta_i \in (-1,1)$ there exists $t_i \in \mathbb{R}$ satisfying the following conditions: \begin{enumerate} \item {\bf (Minimizes $\bar{\ell}$.)} $t_i$ is a minimum for $\bar{\ell}(\eta_i, t)$, hence it satsifies Equation \eqref{eq:key}; \item {\bf (Boundedness.)} $|\ell'(1, t_i)(1 + \eta_i)| = |\ell'(-1, t_i)(1 - \eta_i)| \leq B$. \end{enumerate} Note that the Equality in the boundedness condition is a consequence of Equation \eqref{eq:key}, \begin{lemma} \label{lem:lgt} The logistic loss satisfies the condition above with $B =1/2$. \end{lemma} \begin{proof} For the logistic loss \begin{align*} \ensuremath{\ell_{\mathrm{lgt}}}(y, t) = \log(1 + \exp(-yt))\\ \ensuremath{\ell_{\mathrm{lgt}}}'(y, t) = \frac{-y\exp(-yt)}{1 + \exp(-yt)} = \frac{-y}{1 + \exp(yt)} \end{align*} Hence Equation \eqref{eq:key} can be rewritten as \begin{align*} \frac{ 1 + \eta_i}{1 + \exp(t_i)} &= \frac{1 - \eta_i}{1 + \exp(-t_i)}\\ \exp(t_i) &= \frac{1 + \eta_i}{1 - \eta_i} \end{align*} which has a unique solution for every $\eta_i \in (-1, 1)$. Moreover, this solution satisfies \begin{align*} |\ell'(1, t_i) (1 + \eta_i)| = \frac{1 + \eta_i}{1 + (1 + \eta_i)/(1 - \eta_i)} = \frac{1 - \eta_i^2}{2} \leq \fr{2}. \end{align*} \end{proof} \begin{lemma} \label{lem:exp} The exponential loss satisfies the condition with $B =1$. \end{lemma} \begin{proof} Since $\ensuremath{\ell_{\exp}}(y,t) = \exp(- yt)$, we have $\ensuremath{\ell_{\exp}}'(y, t)= - y\exp(-yt)$. Hence Equation \eqref{eq:key} can be written as \begin{align*} (1 + \eta_i)\exp(- t_i) &= (1 - \eta_i)\exp(t_i)\\ \exp(2t_i) &= \frac{1 + \eta_i}{1 - \eta_i} \end{align*} which has a unique solution for $\eta_i \in (-1, 1)$. Further \begin{align*} |\ell'(1, t_i)|( 1+ \eta_i) &= \exp(-t_i)(1 + \eta_i) = \sqrt{\frac{1 - \eta_i}{1 + \eta_i}}(1 + \eta_i) = \sqrt{1 - \eta_i^2} \leq 1. \end{align*} \end{proof} Unlike for logistic loss, for exponential loss, $|\ensuremath{\ell_{\exp}}'(1, t_i)|$ by itself might be unbounded, so the extra $(1 + \eta_i)$ factor in the boundedness condition is important. \subsection{Multicalibration for differentiable losses} Consider a approximately multicalibrated\xspace\ partition $\mathcal{S}$, and a loss function $\ell$ satisfying these conditions. Consider the predictor $f_\mathcal{S}$ such that $f_\mathcal{S}(x) = t_i$ for all $x \in S_i$. We will show that restricted to each state $S_i$, $t_i$ is nearly a local minimum for the space of all small-norm linear functions in $\mathcal{C}$. Since $f_\mathcal{S}$ is near-optimal for each state $S_i$ in the partition, it must be near-optimal overall. There are two steps to our proof: \begin{enumerate} \item Show that multicalibration\xspace\ implies that the gradient at $t_i$ is small (in $\ell_\infty$). \item Show that the gradient condition implies that $t_i$ is near optimal for minimizing the expected loss over the space of all linear functions with small $\ell_1$ norm. \end{enumerate} Let us consider a classifier of the form $g_w(x) = w_0 + \sum_{j \geq 1} w_jc_j(x)$ where $w = \{w_j\}$ is the vector of parameters. The loss $L(w)$ of this classifier is given by \begin{align*} L(w) &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} \left[ \ell(\mathbf{y} g_w(\mathbf{x}))\right] \end{align*} Let $w^* = (t_i, \bf{0})$ denote the vector where $w_0 = t_i$ and $w_j = 0$ for all $j \geq 1$, so that $g_{w^*}(x) = t_i$. \begin{lemma} \label{lem:grad} Let $\grad L(w)$ denote the gradient of the loss function at $w$. Then we have \begin{align*} \fp{L}{w_0}(w^*) & = 0\\ \forall j\geq 1, \ \abs{\fp{L}{w_j}(w^*)} & \leq \alpha B \end{align*} \end{lemma} \begin{proof} We first verify the claim for $w_0$. Differentiating wrt $w_0$ and plugging in $w_0 = t_i$ gives \[ \fp{L}{w_0}(w^*) = \frac{1 + \eta_i}{2}\ell(1, t_i) + \frac{1 - \eta_i}{2}\ell(-1, t_i) = 0.\] Differentiating with respect to $w_j$ for $j \geq 1$, we get \begin{align*} \fp{L}{w_j} &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ \ell'(\mathbf{y}, g_w(\mathbf{x})) c_j(\mathbf{x}) \right] \end{align*} Plugging in $w = w^*$ so that $g_{w^*}(x) = t_i$, we get \begin{align*} \fp{L}{w_j}(w^*) &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ \ell'(\mathbf{y}, t_i) c_j(\mathbf{x}) \right] \\ &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ \ell'(1, t_i) c_j(\mathbf{x})\frac{1 + \mathbf{y}}{2} + \ell'(-1, t_i) c_j(\mathbf{x})\frac{1 - \mathbf{y}}{2} \right] \\ &= \frac{\ell'(1, t_i)}{2} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ c_j(\mathbf{x})(1 + \mathbf{y}) + \frac{\ell(-1, t_i)}{\ell'(1, t_i)}c_j(\mathbf{x})(1 - \mathbf{y}) \right] \\ &= \frac{\ell'(1, t_i)}{2} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[ c_j(\mathbf{x})(1 + \mathbf{y}) - \frac{1 + \eta_i}{1 - \eta_i} c_j(\mathbf{x})(1 - \mathbf{y}) \right] \\ &= \frac{\ell'(1, t_i)}{2(1 - \eta_i)} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} \left[c_j(\mathbf{x})(1 + \mathbf{y})(1 - \eta_i) - c_j(\mathbf{x})(1 - \mathbf{y})(1 + \eta_i) \right] \\ &= \frac{\ell'(1, t_i)}{1 - \eta_i}\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[c_j(\mathbf{x})(\mathbf{y} - \eta_i)] \end{align*} Hence by multicalibration\xspace\ and the Boundedness condition, \begin{align*} \left\lvert \fp{L}{w_j}(w^*)\right\rvert \leq \frac{|\ell'(t_i)| \alpha(1 - \eta_i^2)}{1 - \eta_i} = |\ell'(t_i)|(1 +\eta_i)\alpha \leq B \alpha \end{align*} \end{proof} Recall that $f^\ell_\mathcal{S}: \mathcal{X} \rightarrow \mathbb{R}$ is the classifier where $f^\ell_\mathcal{S}(x) =t_i$ for all $x \in S_i$, and that $g_w(x) = w_0 + \sum_{j \geq 1} w_jc_j(x)$ is a linear classifier. The next lemma is a simple consequence of convexity. \begin{lemma} \label{lem:convex} For classifiers $f^\ell_\mathcal{S}$ and $g_w$ as above, we have \[ \E_{\mathcal{D}}[\ell(\mathbf{y}, f^\ell_\mathcal{S}(\mathbf{x}))] \leq \E_{\mathcal{D}}[\ell(\mathbf{y}, g_w(\mathbf{x}))]+ \alpha B \|w\|_1. \] \end{lemma} \begin{proof} We will prove that for every $i \in [m]$, \[ \E_{\mathcal{D}_i}[\ell(\mathbf{y}, t_i)] \leq \E_{\mathcal{D}_i}[\ell(\mathbf{y}, g_w(\mathbf{x}))]+ \alpha B \|w\|_1. \] The claim then follows by averaging over the states. We use the following property of (differentiable) convex functions $c: \mathcal{X} \rightarrow \mathbb{R}$: for all $y, x$, \[ c(y) \geq c(x) + (y -x ) \cdot \nabla c (x).\] We now take $c = L$, $y = w$ and $x = w^*$ so that \[ L(w) \geq L(w^*) + (w - w^* ) \cdot \nabla L (w^*).\] We bound $|(w - w^* ) \cdot \nabla L (w^*)|$ using Holder's inequality. Firstly, the $0$ co-ordinate of the gradient is $0$ since \[ \fp{L}{w_0}(w^*) = 0 \] hence it does not contribute to the inner product. For $j \geq 1$, since $w^*_j =0$ we have \[ \sum_{j \geq 1}|w_j - w_j^*| = \sum_{j \geq 1}|w_j| = \|w\|_1. \] Whereas $\|\nabla L (w^*)\|_\infty \leq \alpha B$. So by Holder' inequality \[ |(w - w^* ) \cdot \nabla L (w^*)| \leq \alpha B \|w\|_1\] which implies that \[ L(w^*) \leq L(w) + \alpha B \|w\|_1. \] To complete the proof, we observe that \begin{align*} L(w^*) = \E_{\mathcal{D}_i}[\ell(\mathbf{y}, t_i)], \ \ L(w) = \E_{\mathcal{D}_i}[\ell(\mathbf{y}, g_w(\mathbf{x}))]. \end{align*} \end{proof} \section{Introduction} We show that a multicalibrated predictor with respect to the class $\mathcal{C}$ achieves smaller classification error than each of the concepts in the class $\mathcal{C}$. \begin{theorem} Consider a binary classification task with some joint distribution $\mu$ over the pair $(x,y)$ of datapoint $x\in \mathcal{X}$ and label $y\in \{0,1\}$. Let $f: \mathcal{X}\rightarrow[0,1]$ be any $\alpha$-multicalibrated predictor with respect to $\mathcal{C}$, and let $\bar{f}: \mathcal{X}\rightarrow \{0,1\}$ be the thresholded version of the predictor $f$, i.e. $\bar{f}(x)=\mathbf{1}(f(x)>0.5)$. Then, \begin{align} \Pr_{(x,y)\sim \mu}[\bar{f}(x)\ne y] \le \min _{c\in\mathcal{C}}\Pr_{(x,y)\sim \mu}[c(x)\ne y] + \alpha. \end{align} \end{theorem} \begin{proof} We first consider the special case when $\alpha=0$ since it is easiest to see the intuition there. Let $c^*=\argmin _{c\in\mathcal{C}}\Pr_{(x,y)\sim \mu}[c(x)\ne y]$. Consider any set $S$ in the partition given by the multicalibrated predictor $f$. We claim that if the predictions of $\bar{f}$ and $c^*$ differ in the set $S$, then $\bar{f}$ must be at least as good as $c^*$ in expectation over the datapoints in the set $S$. Let $C_1^*=\{x:c^*(x)=1\}$ and $C_0^*=\{x:c^*(x)=0\}$. Let $f(x)=p_S$ for $x\in S$. We first consider the case when $p_S>0.5$. In this case, $\bar{f}$ assigns the label 1 to all datapoints in $S$, and disagrees with $c^*$ on $T=C_0^*\cap S$. However, by the multicalibration property, \begin{align*} \E_{(x,y)\sim \mu|x\in T}[y]=p_S>0.5. \end{align*} Therefore $\bar{f}$ must achieve strictly better prediction error than $c^*$ on $T$. Since they have the same prediction on the set $S-T$, $\tilde{f}$ must achieve strictly better prediction error than $c^*$ on the overall set $S$. An analogous argument shows that $\bar{f}$ is strictly better than $c^*$ when $p_S<0.5$, and is as good as $c^*$ when $p_S=0.5$. Therefore, $\bar{f}$ achieves overall prediction error at least as good as $c^*$. We now consider the general case when $\alpha \ne 0$. Following the same argument as above, consider a set $S$ where the predictions of $\bar{f}$ and $c^*$ differ, and let $f(x)=p_S>0.5$ for $x\in S$. Let $T=C_0^*\cap S$ be defined as above. Note that by $\alpha$-multicalibration, \begin{align*} p_S-\alpha \le \E_{(x,y)\sim \mu|x\in T}[y]. \end{align*} This implies, \begin{align*} \Pr_{(x,y)\sim \mu|x\in T}[\bar{f}(x)\ne y]&\le 1-p_S+\alpha\\ \Pr_{(x,y)\sim \mu|x\in T}[c^*(x)\ne y]&\ge p_S-\alpha. \end{align*} Therefore, \begin{align*} \Pr_{(x,y)\sim \mu|x\in T}[\bar{f}(x)\ne y]-\Pr_{(x,y)\sim \mu|x\in T}[c^*(x)\ne y]&\le 1-2p_S+\alpha\le \alpha. \end{align*} Since $\bar{f}$ and $c^*$ have the same prediction on the set $S-T$, \begin{align*} \Pr_{(x,y)\sim \mu|x\in S}[\bar{f}(x)\ne y]-\Pr_{(x,y)\sim \mu|x\in S}[c^*(x)\ne y]\le \alpha. \end{align*} By an analogous argument, we can also show the above claim for the case when $p_S\le 0.5$. Therefore by taking the expectation over all sets $S$ in the partition, \begin{align*} \Pr_{(x,y)\sim \mu}[\bar{f}(x)\ne y]-\Pr_{(x,y)\sim \mu}[c^*(x)\ne y]\le \alpha. \end{align*} \end{proof} We show a simple example of a $p$-biased distribution where multicalibration with respect to the individual coordinates yields much smaller prediction error than any of the individual coordinates. \begin{proposition} Consider the distribution $P$ over $(x,y)$ where the distribution of the datapoint $x$ is uniform on the domain $\mathcal{X}=\{0,1\}^n$ and the label $y$ is 0 for all $x$. Similarly, consider the distribution $Q$ over $(x,y)$ where the distribution of the datapoints $x$ is a $p$-biased distribution on the domain $\mathcal{X}$ for some $p<1/3$ and the label $y$ is 1 for all $x$. Let $\mu=(P+Q)/2$. Let $\mathcal{C}=\{x_i,i\in [n]\}$ be the hypothesis class which has the indicator functions on all the coordinates and let $f$ be any $\alpha$-multicalibrated predictor with respect to $\mathcal{C}$. Then for some constant $\gamma>0$, \begin{align} \Pr_{(x,y)\sim \mu}[f(x)\ne y]\le e^{-\gamma n} < \min _{c\in\mathcal{C}}\Pr_{(x,y)\sim \mu}[c(x)\ne y]=p/2. \end{align} \end{proposition} \begin{proof} (can add this if we plan on keeping this result) \end{proof} We show that multicalibration with respect to the individual coordinates lets us learn halfspaces with random noise, for any underlying distribution over the datapoints. \begin{theorem} Consider a binary classification task over the domain $\mathcal{X}=\{0,1\}^n$ with some distribution $D$ over the datapoints $x\in \mathcal{X}$. Let $w$ be a vector in $\mathbb{R}^n$ such that each coordinate $w_i$ of $w$ is an integer, and let $h(x):\mathbb{R}^n\rightarrow\{\pm 1\}$ be the halfspace $h(x) = \mathbbm{1}^{\geq 0}(w^Tx)$. Let the label $y$ of any datapoint $x_i$ be $y=h(x)\cdot\eta(x)$, where $\eta(x)\in \{\pm1\}$ is a random variable independent of $x$ which is 1 with probability $(1-\epsilon)$ and $-1$ with probability $\epsilon$, for some $\epsilon\le 0.5$. Let the concept class $\mathcal{C}=\{x_i,i\in [n]\}$ consist of the indicator functions on all the coordinates. Then, for any predictor $f$ which $\alpha$-multicalibrated with respect to $\mathcal{C}$ for $\alpha=\gamma/\onenorm{w}$, \begin{align} \Pr_{(x,y)\sim \mu}[f(x)\ne y]\le \epsilon + \gamma/2. \end{align} \end{theorem} \begin{proof} We will show that if $h(x)$ is not constant on each set of the partition corresponding to the $\alpha$-multicalibrated predictor, then the partition cannot be $\alpha$-multicalibrated. Consider any set $S$ of the partition. Let $\E_{(x,y)\sim D|_S}[y]=\bar{y}_S$. Henceforth, all our expectations and probabilities will be with respect to the distribution $(x,y)\sim D|_S$ and hence we drop the subscript for brevity. We can write, \begin{align*} \E[(y-\bar{y}_S)w^Tx] &= \E[yw^Tx]- \bar{y}_S)\E[w^Tx]\\ &= \E[h(x)w^Tx\cdot \eta(x)] - \bar{y}_S\E[w^Tx]\\ &= \E[\eta(x)]\cdot \E[\mathbbm{1}^{\geq 0}(w^Tx)w^Tx] - \bar{y}_S\E[w^Tx]\\ &= (1-2\epsilon) \E[|w^Tx|]- \bar{y}_S\E[w^Tx]. \end{align*} Note that since the noise $\eta(x)$ is independent of the datapoint $x$, $\bar{y}_S=\E[h(x)\cdot \eta(x)]={(1-2\epsilon)\E[h(x)]}$. Therefore we can simplify the above expression as follows, \begin{align*} \E[(y-\bar{y}_S)w^Tx] &= (1-2\epsilon) \E[|w^Tx|]-(1-2\epsilon)\E[h(x)]\E[w^Tx]\\ &\ge (1-2\epsilon)\E[|w^Tx|](1-|\E[h(x)]|). \end{align*} Note that $|w^Tx| \ge 1\; \forall \;x$ since each coordinate of $w_i$ is an integer, $x\in \{\pm 1\}^n$ and $w^Tx\ne 0$. Therefore, \begin{align} \E[(y-\bar{y}_S)w^Tx] &\ge (1-2\epsilon)(1-\E[h(x)]).\label{eq:discriminator} \end{align} Now, we rewrite the left hand side of the above equation as follows, \begin{align*} \E[(y-\bar{y}_S)w^Tx] &= \E[y(\sum_i w_ix_i)]-\bar{y}_S\sum_i \E[w_ix_i]\\ &= \sum_i w_i\E[yx_i]-\bar{y}_S\sum_i w_i\E[x_i]\\ &=\sum_i w_i \E[y|x_i=1]\Pr[x_i=1] - \bar{y}_S\sum_i w_i \Pr[x_i=1]\\ &= \sum_i w_i ( \Pr[x_i=1] (\E[y|x_i=1]-\bar{y}_S) \\ &\le \sum_i |w_i| \max_i | \Pr[x_i=1] (\E[y|x_i=1]-\bar{y}_S) |\\ &= \onenorm{w} \max_i |\E[y|x_i=1]-\bar{y}_S|. \end{align*} Therefore by \eqref{eq:discriminator}, \begin{align*} \max_i |\E[y|x_i=1]-\bar{y}_S| \ge \frac{(1-2\epsilon)(1-|\E[h(x)]|)}{\onenorm{w}}. \end{align*} Now, if $f$ is $\alpha$-multi-calibrated for $\alpha=\gamma/\onenorm{w}$ then, \begin{align} \frac{(1-2\epsilon)(1-|\E[h(x)]|)}{\onenorm{w}} &\le \frac{\gamma}{\onenorm{w}},\nonumber\\ \implies |\E[h(x)]| &\ge 1-\frac{\gamma}{1-2\epsilon}.\label{eq:bias1} \end{align} Note that the prediction $b_S$ of the multicalibrated predictor $f$ on the set $S$ is $b_S=\mathbbm{1}^{\geq 0}(\bar{y}_S)={\mathbbm{1}^{\geq 0}((1-2\epsilon)\E[h(x)])}=\mathbbm{1}^{\geq 0}(\E[h(x)]$, since $\epsilon\le 0.5$. Note that, \begin{align} \Pr[h(x)=b]=\frac{1+|\E[h(x)]}{2} &\ge 1-\frac{\gamma}{2(1-2\epsilon)}\label{eq:bias2} \end{align} where we use \eqref{eq:bias1} to get the lower bound. The error of $\bar{f}$ on the set $S$ is, \begin{align*} \Pr[\bar{f}\ne y] &= \epsilon \Pr[h(x)=b] + (1-\epsilon) (1- \Pr[h(x)=b])\\ &= 1-\epsilon -\Pr[h(x)=b](1-2\epsilon). \end{align*} Since $\epsilon\le 0.5$, we can use \eqref{eq:bias2} to obtain, \begin{align*} \Pr[\bar{f}\ne y] &\le 1-\epsilon -(1-\frac{\gamma}{2(1-2\epsilon)})(1-2\epsilon)\\ &\le \epsilon + \gamma/2. \end{align*} Since the above is true for any set $S$ in the partition, the result follows. \eat{ To begin, we first consider the case where $\E_{x\sim D|_S}[g(x)]=0$. \begin{lemma}\label{lem:balanced} For any set $S$ in the partition, consider some distribution $P$ over $x\in S$ such that $\E_{x\sim P}[g(x)]=0$. Let $\alpha_0=\frac{\epsilon}{\onenorm{w}}$. Then there exists some coordinate $x_i$ such that either, \begin{align*} \min\{|\E_{x\sim P|_{x_i=1}}[y]|,| \E_{x\sim P|_{x_i=-1}}[y]|\} > \alpha_0. \end{align*} This implies that the set $S$ is not $\alpha_0$-calibrated for at least one of $S\cap x_i=1$ and $S\cap x_i=0$. \end{lemma} \begin{proof} We will use the following discriminator lemma which intuitively says that any halfspace must be correlated with one of the coordinates. \begin{lemma}\label{lem:discriminator} Consider any halfspace $g(x) = \mathbbm{1}^{\geq 0}(w^Tx)$ where every coordinate $w_i$ of $w$ is an integer. Then for any probability distribution $D$ over $x\in \mathcal{X}$, there must be some $x_i$ such that, $$\left|\E_{x\sim D} [g(x)x_i]\right|\ge \frac{1}{\onenorm{w}}.$$ \end{lemma} \begin{proof} Note that $|w^Tx| \ge 1$ since each coordinate of $w_i$ is an integer, $x\in \{\pm 1\}^n$ and $w^Tx\ne 0$. Therefore, \begin{align*} \E[g(x)w^Tx] = \E[\mathbbm{1}^{\geq 0}(w^Tx)w^Tx]= \E[|w^Tx|] \ge 1. \end{align*} We can rewrite the above as follows, \begin{align*} \E[g(x) w^T x] = \E[g(x)(\sum_i w_i x_i)] = \sum_i w_i \E[g(x) x_i] \ge 1. \end{align*} Therefore, \begin{align*} \sum_i |w_i|\max_i|\E[g(x) x_i]| &\ge 1\\ \implies \max_i|\E[g(x) x_i]| &\ge \frac{1}{\onenorm{w}}. \end{align*} \end{proof} Since the noise $\eta_i$ is independent, \begin{align*} \E_{x\sim P} [yx_i] = \E_{x\sim P} [g(x)x_i\cdot \eta_i]=\E_{x\sim P} [g(x)x_i]\cdot \E[\eta_i] =\epsilon\E_{x\sim P} [g(x)x_i]. \end{align*} It then follows using Lemma \ref{lem:discriminator} that there exists some coordinate $x_i$ such that, \begin{align} \left|\E_{x\sim P} [yx_i]\right| \ge \frac{\epsilon}{\onenorm{w}}.\label{eq:distinguish} \end{align} We claim that this implies that the set is not $\alpha_0$-calibrated with respect to $x_i$, for $\alpha_0=\frac{\epsilon}{\onenorm{w}}$. Let $p_1=\E_{x\sim P|_{x_i=1}}[y]$ and $p_2=\E_{x\sim P|_{x_i=-1}}[y]$. Note that, \begin{align*} \E_{x\sim P} [yx_i]=p_1\cdot \Pr_{x\sim P}[x_i=1] -p_2\cdot \Pr_{x\sim P}[x_i=-1]. \end{align*} Therefore, by \eqref{eq:distinguish}, $\min\{p_1,p_2\}\ge \alpha_0$. If $\alpha<\alpha_0$, this implies that the $\alpha_0$-calibration condition is not satisfied for at least one of $S\cap x_i=1$ and $S\cap x_i=0$. \end{proof} We now consider the case when $\E_{x\sim D|_S}[g(x)]=\beta$. Our argument works by reweighing the distribution $D|_S$ to reduce to the case when $\E_{x\sim D|_S}[g(x)]=0$ and then using the Lemma \ref{lem:balanced}. For all $x\in S$ and some constants $\gamma_1$ and $\gamma_2$, define a new distribution $D'|_S$ by reweighing $x$ such that $g(x)=1$ by $\gamma_1$ and $x$ such that $g(x)=-1$ by $\gamma_2$. We choose $\gamma_1=1/(1+\beta)$ and $\gamma_2=1/(1-\beta)$ which ensures, \begin{gather*} \Pr_{x\sim D'|_S}[x:g(x)=1] = \Pr_{x\sim D'|_S}[x:g(x)=-1] = 1/2,\\ \implies \E_{x\sim D'|_S}[g(x)]=0. \end{gather*} } \end{proof} We show that halfspaces are not agnostically learnable with the individual coordinates being the weak learners. \begin{proposition} Consider a binary classification task with some distribution $D$ over the datapoints $(x,y)$ where $x \in \{0,1\}^{n}$ and $y \in\{\pm 1\}$. Let the concept class $\mathcal{C}=\{x_i,i\in [n]\}$ consist of the indicator functions on all the coordinates. Then there exists a distribution $D$ such that the class of halfspaces $h(x) = \mathbbm{1}^{\geq 0}(w^Tx)$ is not agnostically learnable using a weak learner for the class $\mathcal{C}$. \end{proposition} \begin{proof} Consider the distribution on $(x, y)$ where $y = x_1 \oplus x_2 \oplus x_3$ is the parity function on the first three variables. Then the labels are uncorrelated with any $x_i$. However the majority of $(x_1, x_2, x_3)$ is correct with probability $3/4$. \end{proof} We show that a multicalibrated predictor with respect to the class $\mathcal{C}$ achieves smaller regression error than any sparse linear combination of the concepts in the class $\mathcal{C}$. \begin{theorem} Consider a binary classification task with some distribution $D$ over the datapoints in the domain $\mathcal{X}$. Let $p^*(x)$ be the conditional distribution of the label $y$ for any $x$. Consider some concept class $\mathcal{C}$ with cardinality $|\mathcal{C}|$ with concepts $\{c_i(x):i \in [|\mathcal{C}|]\}$ where $c_i(x) : \mathcal{X}\rightarrow \{0,1\}$. Let ${\mathcal{G}}$ be the class of functions ${\mathcal{G}}=\{\sum_i w_i c_i(x): w_i \in \mathbb{R}^{|\mathcal{C}|}, \onenorm{w}=W\}$. Let $f$ be any $\alpha$-multicalibrated predictor with respect to $\mathcal{C}$. Then for any $g\in \mathcal{G}$, \begin{align} \E\norm{g(x)-p^*(x)}^2 &\ge \E\norm{ f(x)-p^*(x)}^2+ \E\norm{g(x)- f(x)}^2 -2\alpha\onenorm{w}. \end{align} \end{theorem} \begin{proof} Consider any set $S$ of the partition. Let $\E_{(x,y)\sim D|_S}[p^*(x)]=\bar{y}_S$. Henceforth, all our expectations and probabilities will be with respect to the distribution $(x,y)\sim D|_S$ and hence we drop the subscript for brevity. Note that $f(x) = \bar{y}_S$ for $x\in S$. For any predictor $g(x)$, we can write, \begin{align} \E\norm{g(x)-p^*(x)}^2 &=\E\norm{(g(x)- \bar{y}_S) - ( p^*(x)-\bar{y}_S)}^2\nonumber\\ &= \E\norm{g(x)- \bar{y}_S}^2 + \E\norm{ p^*(x)-\bar{y}_S}^2 +2\E[(g(x)- \bar{y}_S)(p^*(x)-\bar{y}_S)]\nonumber\\ &= \E\norm{g(x)- \bar{y}_S}^2 + \E\norm{ p^*(x)-\bar{y}_S}^2 +2\E[g(x)(p^*(x)-\bar{y}_S)]\label{eq:regression} \end{align} where the last step follows since $\E[p^*(x)]=\bar{y}_S$. Since $g(x) = \sum_i w_i c_i(x)$, \begin{align*} \E[g(x)(p^*(x)-\bar{y}_S)] &= \sum_i w_i \E[c_i(x)(p^*(x)-\bar{y}_S)]\\ &= \sum_i w_i (\E[c_i(x)p^*(x)]-\bar{y}_S\E[c_i(x)])\\ &= \sum_i w_i (\E[p^*(x)|c_i(x)=1]\Pr[c_i(x)=1]-\bar{y}_S\Pr[c_i(x)=1])\\ &= \sum_i w_i \Pr[c_i(x)=1] (\E[p^*(x)|c_i(x)=1]-\bar{y}_S). \end{align*} Therefore, \begin{align*} | \E[g(x)(p^*(x)-\bar{y}_S)]| &\le \sum_i |w_i| |\E[p^*(x)|c_i(x)=1]-\bar{y}_S|\\ &\le \sum_i |w_i| \max_i |\E[p^*(x)|c_i(x)=1]-\bar{y}_S|\\ &= \onenorm{w}\max_i |\E[p^*(x)|c_i(x)=1]-\bar{y}_S|. \end{align*} Note that if $f$ is $\alpha$-multi-calibrated, then \begin{align*} \max_i |\E[p^*(x)|c_i(x)=1]-\bar{y}_S| \le \alpha. \end{align*} Therefore if $f$ is $\alpha$-multi-calibrated, \begin{align*} | \E[g(x)(p^*(x)-\bar{y}_S)]| &\le \alpha\onenorm{w}. \end{align*} Plugging this into \eqref{eq:regression}, \begin{align*} \E\norm{g(x)-p^*(x)}^2 &\ge \E\norm{g(x)- \bar{y}_S}^2 + \E\norm{ p^*(x)-\bar{y}_S}^2 -2\alpha\onenorm{w}. \end{align*} Since this is true for any $S$, averaging over all sets $S$ in the partition gives the desired result. \end{proof} \begin{theorem} Consider a regression task with some distribution $D$ over the datapoints in the domain $\mathcal{X}$. Let the conditional distribution $p^*(x)$ of the label $y$ for any $x$ be $u(\sum_{i=1}^n w_i x_i)$, for some monotonic and $L$-Lipchitz function $u$. Let the concept class $\mathcal{C}$ be the set of all thresholds on the individual coordinates, i.e. $\mathcal{C}=\{I(x_i \diamond \theta):i \in [n], \theta\in \mathbb{R}, \diamond \in \{>,<,\ge, \le \}\}$. Let $f$ be any $\alpha$-multicalibrated predictor with respect to $\mathcal{C}$. Then, \begin{align} \E\norm{f(x)-p^*(x)}^2 \le \alpha L\onenorm{w}. \end{align} \end{theorem} \begin{proof} Consider any set $S$ in the partition corresponding to the multicalibrated predictor $f$. Define $\sigma_{p^*|S}^2=\E_{|S}[(p^*(x)-\E_{|S}[p^*(x)])^2]$ as the variance of $p^*$ in the set $S$. Henceforth, all our expectations and probabilities will be with respect to the distribution $(x,y)\sim D|_S$ and hence we drop the subscript for brevity. By Lemma 4 of [Adam's awesome paper], there exists an $i\in [n] , \theta\in \mathbb{R},$ and $\diamond \in \{>,<,\ge, \le \}$ such that, \begin{align*} \E[p^*(x)|I(x_i \diamond \theta)]\Pr[x_i \diamond \theta]-\E[p^*(x)]\Pr[x_i \diamond \theta]\ge \frac{\sigma_{p^*|S}^2}{L\onenorm{w}}. \end{align*} But by $\alpha$-multicalibration, \begin{gather*} |\E[p^*(x)|I(x_i \diamond \theta)]-\E[p^*(x)]|\le \alpha, \\ \implies |\E[p^*(x)|I(x_i \diamond \theta)]\Pr[x_i \diamond \theta]-\E[p^*(x)]\Pr[x_i \diamond \theta]|\le \alpha. \end{gather*} Therefore, $\alpha$-multicalibration implies that, \begin{align*} \frac{\sigma_{p^*|S}^2}{L\onenorm{w}} \le \alpha. \end{align*} Note that $f(x)=\E_{|S}[p^*(x)]$ for all $x\in S$. Therefore, for all $x\in S$, \begin{align*} \E[(f(x)-p^*(x))^2]\le \alpha L\onenorm{w}. \end{align*} Since this is true for every set $S$, by averaging over all sets $S$ we get the final result. \end{proof} \section{Simplifying and characterizing agnostic boosting} In this section we characterize agnostic boosting -- it is equivalent to just learning linear combinations of weak learners!? The intuition is that one can define an inner product $cor(h, f) =E[h(x)f(x)]$ and argue that if class $H$ is weak-agnostic-learned by $C$ then $H$ is close to $span(C)$. Let $Y=\{-1,1\}$ and let $H, C \subseteq Y^X$ be families of binary classifiers. Let $D$ be a distribution over a finite or countably infinite\footnote{Measure theory sucks.} set $X$. The target function to be learned is $f: X \rightarrow [-1,1]$. It is sometimes assumed that $f: X \rightarrow Y$ is binary, and moreover for (realizable) PAC it is further assumed that $f \in H$. But for general agnostic learning $f: X \rightarrow [-1,1]$ can be interpreted as: an example $x \sim D$ is drawn and the label $y \in Y$ is chosen so that $\E[y|x] = f(x)$. Define correlation $cor_D(h, f) = E_{x \sim D}[h(x)f(x)]$. This is just $1-2Pr[h(x)\neq y]$ so $cor>0$ means error is less than 1/2, and correlation 1 means error is 0. Let $L$ be a learning algorithm that outputs binary classifiers in $C$. As background, in standard (noiseless)boosting one says that $L$ $\gamma$-weak-learns $H$ if for every classifier $f \in H$ and every distribution $D$ over $X$, with probability $\geq 3/4$, $L$ outputs $c \in C$ with correlation $cor_D(c, f)\geq \gamma$. It is known that $H \subseteq maj(C)$ the majority of sums of classifiers in $C$. Moreover the algorithm that finds $c \in C$ with maximum correlation (if it could be done efficiently) would $\gamma$ weak-learn the class $H=maj_k(C)$ of the majority of the sum of up to $k$ classifiers in $C$ with $\gamma = \poly(1/k)$. In agnostic learning, we consider a target function $f:X \rightarrow [-1,1]$. Again suppose we have an algorithm $L$ that outputs binary classifiers in $C$. One says that $L$ $(\gamma, \alpha, D)$-weak-agnostic learns $C$ if for every classifier $f:X \rightarrow [-1,1]$ with $\max_{h \in H} cor_D(h, f) \geq \alpha$, with probability $\geq 3/4$ $L$ outputs $c \in C$ with $cor_D(c, f) \geq \gamma$. This is stronger than standard boosting in that it has to work for any $f$ that has $\geq \alpha$ correlation with some $h \in H$, as opposed to standard learning where it only has to work for those $f$ where OPT$=0$) and moreover it only has to hold for some $D$. It is known that $L$ efficiently $(\gamma, \alpha, D)$-weak-agnostic learns $H$ then one can efficiently find a classifier with correlation $> OPT-\alpha - \epsilon$ (OPT$=max_{h \in H} cor(h, f)$), with high probability, in time $\poly(1/\epsilon, 1/\gamma, 1/\alpha)$. Ideally, for agnostic boosting to show that one can agnostically learn $H$, one would like $L$ that agnostically $(\gamma(\alpha), \alpha, D)$-weak learns $H$ where $\gamma : (0,1] \rightarrow (0,1]$, so we can achieve correlation $>OPT - 2\epsilon$ by setting $\alpha =\epsilon$. In the TODOs, we ask whether a version of this might be provable for specific $(\gamma, \alpha)$ pairs. \begin{proposition} Fix distribution $D$ with full support\footnote{This full-support assumption can probably be removed with care} over $X$, and $H, C \subseteq Y^X$. Suppose there is some function $\gamma : (0,1] \rightarrow (0,1]$ such that for all $f: X \rightarrow [-1,1]$, $$\sup_{c \in C} cor_D(c, f) \geq \gamma(\sup_H cor(h, f)).$$ Then $H \subseteq span(C)$. \end{proposition} \begin{proof} Suppose not. Then there is some $h \in H$ such that $h \not\in span(C)$. Take $h' \in span(C)$ that is closest in L2 norm to $h$, i.e., that minimizes squared error $E_D[(h(x)-h'(x))^2]$. TODO: argue that $cor(h', h)<1$ otherwise a scaled-down version of $h'$ would have lower squared error. Now, take $f=\frac{h-h'}{Z}$ where $Z$ is a normalization constant large enough to guarantee that $f(x)\in [-1,1]$. Clearly no $c \in C$ has positive correlation with $f$ and yet there $$cor(h, f) = \frac{1}{Z}(cor(h, h)-cor(h', h)) \frac{1}{Z}(1-cor(h', h)) > 0.$$ \end{proof} \subsection{TODOs: would be nice to do} \begin{enumerate} \item Check that this is right? \item Add analysis for approximate case, i.e., some version of the above that only holds for specific ($\gamma, \alpha$) where it would have to be shown that everything in $H$ is close to the span of $C$ (with bounded weights) or something like that. \item Show that gradient boosting or some very simple boosting algorithm works in this setting? \end{enumerate} \section{Multicalibration\xspace} \label{sec:mcab} In this section, we present our definitions of multicalibration. We first consider the case of binary labels, and then extend it to the multi-class and real-valued settings. To streamline the presentation, routine proofs are deferred to Appendix \ref{app:mcab}. Given real-valued random variables $\mathbf{z}_1, \mathbf{z}_2$ from a joint distribution $\mathcal{D}$, we define \begin{align*} \CoVar_\mathcal{D}[\mathbf{z}_1, \mathbf{z}_2] &= \E_\mathcal{D}[\mathbf{z}_1\mathbf{z}_2] - \E_\mathcal{D}[\mathbf{z}_1]\E_\mathcal{D}[\mathbf{z}_2] = \E_\mathcal{D}\left[\mathbf{z}_1(\mathbf{z}_2 - \E_\mathcal{D}[\mathbf{z}_2])\right]. \end{align*} We will use the fact that covariance is bilinear. \eat{linear in each argument, hence \begin{align*} \CoVar_\mathcal{D}[\lambda\mathbf{z}_1 + \lambda'\mathbf{z}_1', \mathbf{z}_2] &= \lambda \CoVar_\mathcal{D}[\mathbf{z}_1, \mathbf{z}_2] + \lambda'\CoVar_\mathcal{D}[\mathbf{z}_1', \mathbf{z}_2] \end{align*} } The following identity will be useful for Boolean $\mathbf{y}$. \begin{corollary} \label{cor:covar} For random variables $(\mathbf{z}, \mathbf{y}) \sim \mathcal{D}$ where $\mathbf{y} \in \ensuremath{\{0,1\}}$, \begin{align} \label{eq:covar-1} \CoVar_\mathcal{D}[\mathbf{z}, \mathbf{y}] = \Pr_{\mathcal{D}}[\mathbf{y} = 1]\left(\E_{\mathcal{D}|\mathbf{y} = 1}[\mathbf{z}] - \E_{\mathcal{D}}[\mathbf{z}] \right) = \Pr_{\mathcal{D}}[\mathbf{y} = 0]\left(\E_{\mathcal{D}}[\mathbf{z}] - \E_{\mathcal{D}|\mathbf{y} = 0}[\mathbf{z}]\right). \end{align} \end{corollary} \subsection{Multicalibration\xspace via covariance} In this section, we define multicalibration\xspace for the binary labels setting where $\mathcal{Y} = \ensuremath{\{0,1\}}$. We build on a recent line of work \cite{hkrr2018, Jung20, kgz, gopalan2021multicalibrated}. A detailed discussion of how our definitions compare to previous definitions is presented in Appendix \ref{app:def-mcab}. The following definition is a generalization of the notion of $\alpha$-multicalibration\xspace to real-valued $c$, and in the setting of partitions. \begin{definition} \label{def:m-cal} Let $\mathcal{D}$ be a distribution on $\mathcal{X} \times \ensuremath{\{0,1\}}$. The partition $\mathcal{S}$ of $\mathcal{X}$ is $\alpha$-multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$ if for every $i \in [m]$ and $c \in \mathcal{C}$, the conditional distribution $\mathcal{D}_i = \mathcal{D}|\mathbf{x} \in S_i$ satisfies \begin{align} \label{eq:m-cal} \abs{\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}]} \leq \alpha. \end{align} \end{definition} A consequence of this definition is that for each $\mathcal{D}_i$, conditioning on $\mathbf{y}$ does not change the expectation of $c(\mathbf{x})$ by much. Formally, by Equation \eqref{eq:covar-1}, for $i \in [m]$ and $b \in \ensuremath{\{0,1\}}$, \begin{align} \Pr_{\mathcal{D}_i}[\mathbf{y} = b]\left|\E_{\mathcal{D}_i|\mathbf{y} = b}[c(\mathbf{x})] - \E_{\mathcal{D}_i}[c(\mathbf{x})]\right| \leq \alpha. \label{eq:multicalibration_corollary} \end{align} \eat{In contrast, \cite{hkrr2018} consider $c: \mathcal{X} \rightarrow \ensuremath{\{0,1\}}$ which can be thought of as the indicator of a set, and require that for each $\mathcal{D}_i$, conditioning on being in the set does not change the expectation of $\mathbf{y}$. } Definition \ref{def:m-cal} requires a bound on the covariance for every distribution $\mathcal{D}_i$. This might be hard to achieve if $\mathcal{D}(S_i)$ is tiny, and hence we hardly see samples from $\mathcal{D}_i$ when sampling from $\mathcal{D}$. This motivated a relaxed definition called $(\alpha, \beta)$-multicalibration\xspace in \cite{hkrr2018, gopalan2021multicalibrated}. We propose a different definition for which it is also easy to achieve sample efficiency. Rather than requiring the covariance be small for every $i$, we only require it to be small on average. Let $\i \sim \mathcal{D}$ denote sampling (the index of) a set from the partition $\mathcal{S}$ according to $\mathcal{D}$ so that $\Pr[\i = i] = \mathcal{D}(S_i)$. \begin{definition} \label{def:m-cal-1} The partition $\mathcal{S}$ of $\mathcal{X}$ is $\alpha$-approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$ if for every $c \in \mathcal{C}$, \begin{align} \label{eq:m-cal-new} \E_{\i \sim \mathcal{D}}\abs{\CoVar_{\mathcal{D}_\i}[c(\mathbf{x}), \mathbf{y}]} \leq \alpha. \end{align} \end{definition} The next lemma shows that approximate multicalibration\xspace\ implies closeness to (strict) multicalibration\xspace\ under the distribution $\mathcal{D}$. The proof is by applying Markov's inequality to Definition \ref{def:m-cal-1}. \begin{lemma} If $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$, then for every $c \in \mathcal{C}$ and $\beta \in [0,1]$ \begin{align} \Pr_{\i \sim \mathcal{D}}\left[\abs{\CoVar_{\mathcal{D}_{\i}}[c(\mathbf{x}), \mathbf{y}} \geq \frac{\alpha}{\beta}\right] \leq \beta. \end{align} \end{lemma} This lemma shows that being $\alpha\beta$-approximately multicalibrated\xspace\ is closely related to the notion of $(\alpha, \beta)$-multicalibration\xspace\ in \cite{hkrr2018, gopalan2021multicalibrated}, which roughly says that the $\alpha$-multicalibration\xspace\ condition holds for all but a $\beta$ fraction of the space $\mathcal{X}$. Conversely, one can show that $(\alpha, \beta)$-multicalibration\xspace\ gives $(\alpha + \beta \infnorm{\mathcal{C}})$-approximate multicalibration\xspace. We find the single parameter notion of $\alpha$-approximate multicalibration\xspace\ more elegant. It is also easy to achieve sample efficiency, since as the next lemma shows, it only requires strong conditional guarantees for large states. \begin{lemma} \label{lem:small} Let the partition $\mathcal{S}$ be such that for all $i \in [m]$ where \begin{align} \label{eq:small} \mathcal{D}(S_i) \geq \frac{\alpha}{2m\infnorm{\mathcal{C}}} \end{align} it holds that for every $c \in \mathcal{C}$, \begin{align} \label{eq:small-cov} \abs{\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}]} \leq \frac{\alpha}{2}. \end{align} Then $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$. \end{lemma} Approximate multicalibration\xspace implies that for an {\em average} state in the partition, conditioning on the label does not change the expectation of $c(x)$ much. The proof follows by plugging Equation \eqref{eq:covar-1} in the definition of approximate multicalibration\xspace. \begin{corollary} \label{cor:bin} If $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$, then for $c \in \mathcal{C}$ and $b \in \ensuremath{\{0,1\}}$, \begin{align} \E_{\i \sim \mathcal{D}}\left[\Pr_{\mathcal{D}_i}[\mathbf{y} = b]\left|\E_{\mathcal{D}_i|\mathbf{y} = b}[c(\mathbf{x})] - \E_{\mathcal{D}_i}[c(\mathbf{x})]\right|\right] \leq \alpha. \end{align} \end{corollary} \paragraph{Extension to the multi-class setting} In the multi-class setting $\mathcal{Y} =[l]$, so that $l =2$ is exactly the Boolean case considered above. We use $\ind{\mathbf{y} =j}$ to denote the indicator of the event that the label is $j$. The following definition generalizes Definition \ref{def:m-cal-1}: \begin{definition} \label{def:m-cal-k} Let $\mathcal{D}$ be a distribution on $\mathcal{X} \times [l]$ where $l \geq 2$. The partition $\mathcal{S}$ of $\mathcal{X}$ is $\alpha$-approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$ if for every $c \in \mathcal{C}$ and $j \in [l]$, it holds that \begin{align} \label{eq:m-cal-k} \E_{\i \sim \mathcal{D}}\left[\abs{\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \ind{\mathbf{y} = j}]}\right] \leq \alpha. \end{align} \end{definition} \paragraph{Extension to the bounded real-valued case.} We now consider the setting where $\mathcal{Y}$ is a bounded interval, by scaling we may consider $\mathcal{Y} = [0,1]$. For interval $J = [v,w] \subset \mathcal{Y}$, let $\ind{\mathbf{y} \in J}$ be the indicator of the event that $\mathbf{y} \in J$. \begin{definition} \label{def:m-cal-real} Let $\mathcal{D}$ be a distribution on $\mathcal{X} \times [0,1]$. The partition $\mathcal{S}$ of $\mathcal{X}$ is $\alpha$-approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$ if for every $c \in \mathcal{C}$ and interval $J \subseteq [0,1]$, it holds that \begin{align} \label{eq:m-cal-real} \E_{\i \sim \mathcal{D}}\left[\abs{\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \ind{\mathbf{y} \in J}]}\right] \leq \alpha. \end{align} \end{definition} \paragraph{Computational efficiency} Given these new definitions, a natural question is about the computational complexity of computing multicalibrated partitions. Following \cite{hkrr2018}, this task can be accomplished efficiently given a weak agnostic learner for the class $\mathcal{C}$. We present a formal statement of this result for the multi-class setting in Theorem \ref{thm:alg-multi}. The multi-class setting includes the Boolean labels setting as a special case. For the purposes of omniprediction, we show in Section \ref{sec:real} that the bounded real-valued setting reduces to the multi-class setting. We defer these results to Section \ref{sec:algo} since we do not consider them to be the main contribution of this work, several of the ideas used in the algorithm and its analysis are present in previous work, they are presented here for completeness. \eat{ For computing such a partition, we show in Section \ref{sec:real} that it can be reduced to the multi-class case for $l = B/\alpha$. } \subsection{Some closure properties of multicalibration\xspace } \label{sec:closure} In this section, we prove that approximate multicalibration\xspace\ is closed under two natural operations on the class $\mathcal{C}$ and the distribution $\mathcal{D}$: \begin{enumerate} \item {\bf Linear combinations of $\mathcal{C}$: } We take sparse linear combinations of the functions $c \in \mathcal{C}$. \item {\bf Conditioning $\mathcal{D}$ on a subset: } We condition the distribution $\mathcal{D}$ on a subset $\mathcal{X}' \subseteq \mathcal{X}$ whose indicator lies in the set $\mathcal{C}$. \end{enumerate} Again we prove these for the case $\mathcal{Y} = \ensuremath{\{0,1\}}$, but the extension to arbitrary $\mathcal{Y}$ is routine. \paragraph{Multi-calibration under linear combinations.} We will typically start with an approximately multicalibrated\xspace partition for a {\em base} class of bounded or even Boolean functions, such as decision trees or coordinate functions. Since our definition allows the functions $c$ to be real-valued and possibly unbounded, we can consider functions arising from linear combinations over this base class. The motivation for this comes from boosting algorithms like AdaBoost or Logistic Regression, where we take a base class of weak learners, and then construct a strong learner which is a linear combination of the weak learners \cite{freund1997decision, boostingBook}. We will denote by $\mathrm{Lin}_\mathcal{C}$ the set of all linear functions over $\mathcal{C}$. We associate the vector $w = (w_0, w_1, \ldots)$ with the function $g_w \in \mathrm{Lin}_\mathcal{C}$ defined by $g_w(x) = w_0 + \sum_{j}w_j c_j(x)$ where $c_j \in \mathcal{C}$ and denote $\|w\|_1 = \sum_{j \geq 1} w_j$ (note we have excluded $w_0$). Let \begin{equation}\label{eq:mLC} \mathrm{Lin}_\mathcal{C}(W) = \{ g_w \in \mathrm{Lin}_\mathcal{C}: \|w\|_1 \leq W \} \end{equation} be the set of all {\em $W$-sparse} linear combinations. The following simple claim shows that multicalibration\xspace\ is {\em closed} under taking sparse linear combinations. The parameter $\alpha$ degrades with the sparsity. The proof follows from linearity of covariance, and is given in Appendix \ref{app:mcab}. \begin{lemma} \label{lem:linear} For any $W > 0$, if $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$, then it is $\alpha W$-approximately multicalibrated\xspace for $\mathrm{Lin}_\mathcal{C}(W), \mathcal{D}$. \end{lemma} \paragraph{Multi-calibration for sub-populations.} Let $T \subseteq \mathcal{X}$ be a sub-population such that its indicator function belongs to $\mathcal{C}$. Let $\mathcal{D}'$ denote the distribution $\mathcal{D}|\mathbf{x} \in T$, where $\mathcal{D}'(x) = \mathcal{D}(x)/\mathcal{D}(T)\; \forall x \in T$. Let $\mathcal{S}' = \{S_i \cap T\}$ be the partition of $T$ induced by $\mathcal{S}$. We will use $\mathcal{D}'_i$ for the distribution $\mathcal{D}'|\mathbf{x} \in S'_i$ (which is the same as $\mathcal{D}|\mathbf{x} \in S'_i$ since $S'_i \subseteq T$), and will denote $p'_i = \E_{\mathcal{D}'_i}[\mathbf{y}]$. Let $\mathcal{C}' \subseteq \mathcal{C}$ denote the subset of functions from $\mathcal{C}$ that are supported on $T$ (functions that are 0 outside of $T$). Note that $\mathcal{C}'$ is nonempty, since the indicator of $T$ lies in it. The proof of the following result for the sub-population $T$ in Appendix \ref{app:sub-pop}. \begin{theorem} \label{thm:sub-pop} If $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$, then $\mathcal{S}'$ is $\alpha(1 + \infnorm{\mathcal{C}'})/\mathcal{D}(\mathcal{X}')$-approximately multicalibrated\xspace for $\mathcal{C}', \mathcal{D}'$. \end{theorem} \section{Notation and Preliminaries} \label{sec:notation} Let $\mathcal{D}$ denote a distribution on $\mathcal{X} \times \mathcal{Y}$. The set $\mathcal{X}$ represents points in our space, it could be continuous or discrete. The set $\mathcal{Y}$ represents the labels, we will typically consider $\mathcal{Y} = \ensuremath{\{0,1\}}$, $\mathcal{Y} = [k]$ or $\mathcal{Y} = \ensuremath{[0,1]}$. We use $(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}$ where $\mathbf{x} \in \mathcal{X}, \mathbf{y} \in \mathcal{Y}$ to denote a sample from $\mathcal{D}$. We use boldface for random variables. For any $S \subset \mathcal{X}$, let $\mathcal{D}(S) = \Pr_{\mathbf{x} \sim \mathcal{D}}[ \mathbf{x} \in S]$. We will use $\mathbf{y} \sim \B{p}$ to denote sampling from the Bernoulli distribution with parameter $p$. Let $\mathcal{C} = \{c: \mathcal{X} \rightarrow \mathbb{R}\}$ be a collection of real-valued hypotheses on a domain $\mathcal{X}$, which could be continuous or discrete. The hypotheses in $\mathcal{C}$ should be efficiently computable, and the reader can think of them as monomials, decision trees or neural nets. We will denote \[ \infnorm{\mathcal{C}} = \max_{c \in \mathcal{C}, x \in \mathcal{X}}|c(x)|. \] A loss function $\ell$ takes a label $y \in \mathcal{Y}$, an action $t \in \mathbb{R}$ and returns a loss value $\ell(y,t)$. Common examples are the $\ell_p$ losses $\ell_p(y, t) = |y -t|^p$ and logistic loss $\ell(y, t) = \log(1 + \exp(-yt))$. The problem of minimizing a loss function $\ell$ is to learn a hypotheses $h: \mathcal{X} \rightarrow \mathbb{R}$ such that the expected loss $\ell_\mathcal{D}(h) {:=} \E_\mathcal{D}[\ell(\mathbf{y}, h(\mathbf{x}))]$ is small. Let $\mathcal{L} = \{\ell: \mathcal{Y} \times \mathbb{R} \rightarrow \mathbb{R}\}$ denote a collection of loss functions. A partition $\mathcal{S} = \{S_1, \ldots, S_m \}$ of the domain $\mathcal{X}$, is a collection of disjoint subsets whose union equals $\mathcal{X}$, we refer to $m$ as its size. We refer to each $S_i$ as a state in the partition. Given a partition $\mathcal{S} = \{S_1, \ldots, S_m \}$ of the domain $\mathcal{X}$, define the conditional distribution $\mathcal{D}_i$ over $S_i \times \mathcal{Y}$ as $\mathcal{D}_i = \mathcal{D}|\mathbf{x} \in S_i$. A (binary) predictor is a function $f:\mathcal{X} \rightarrow \ensuremath{[0,1]}$, where $f(x)$ is interpreted as the probability conditioned on $x$ that $\mathbf{y}=1$. We define the ground truth predictor as $f^*(x) := {\E_\mathcal{D}[\mathbf{y}|\mathbf{x} =x]}$. For general label sets $\mathcal{Y}$, let $\mathcal{P}(\mathcal{Y})$ denote the space of probability distributions on $\mathcal{Y}$. Define the ground truth predictor $f^*: \mathcal{X} \rightarrow \mathcal{P}(\mathcal{Y})$ where $f^*(x)$ is the distribution of $\mathbf{y}|x$. A predictor is a function $f:\mathcal{X} \rightarrow \mathcal{P}(\mathcal{Y})$ which is intended to be an approximation of $f^*$. We denote by $g \circ h$ the composition of functions. \subsection{Nice loss functions} We say $\ell:\mathcal{Y} \times \mathbb{R} \rightarrow \mathbb{R}$ is a convex loss function, if $\ell(y, t)$ is a convex function of $t$ for every $y \in \mathcal{Y}$. Note that in the binary setting, our formulation allows for binary classification with different false-positive/negative costs, e.g., $\ell(y, t) = c_y |t-y|$ where $c_{0}$ and $c_1$ are the different costs. A function $f:\mathbb{R}\rightarrow \mathbb{R}$ is said to be $B$-Lipschitz over interval $I$ if $|f(t)-f(t')|\leq B|t-t'|$ for all $t, t' \in I$. We say the function is $B$-Lipschitz if the condition holds for $I =\mathbb{R}$. While assuming the loss is $B$-Lipschitz is sufficient for us, we can work with a weaker notion that only requires the Lipschitz property on a sufficiently large interval. This weaker notion covers most commonly used loss functions such as the exponential loss that are not Lipschitz everywhere. Also, we will define loss functions in the setting of labels that come from $\mathcal{Y}$. In this section though, we will focus on the case $\mathcal{Y} = \ensuremath{\{0,1\}}$. \begin{definition} \label{def:nice-loss} For $B, \epsilon >0$, a convex loss function $\ell: \mathcal{Y} \times \mathbb{R} \rightarrow \mathbb{R}$ is $(B, \epsilon)$-nice if there is a closed interval $I = I_\ell \subseteq \mathbb{R}$ satisfying: \begin{enumerate} \item {\bf ($B$-Lipschitzness)} For all $y$, $\ell(y, t)$ is $B$-Lipschitz in $t$ over $I_{\ell}$: \[ \forall y \in \mathcal{Y}, \ t, t' \in I_{\ell}, |\ell(y, t) - \ell(y, t')| \leq B |t - t'|.\] \item {\bf ($\epsilon$-optimality)} For $y \in \mathcal{Y}$, $I_{\ell}$ contains an $\epsilon$-optimal minimizer of $\ell(y,t)$: \[ \inf_{t \in I_{\ell}}\ell(y, t) \leq \inf_{t \in \mathbb{R}} \ell(y, t)+\epsilon.\] \end{enumerate} Let $\mathcal{L}(B, \epsilon)$ be the set of all $(B, \epsilon)$-nice functions. \end{definition} Observe that if a function is $B$-Lipschitz on $\mathbb{R}$, then it is $(B, 0)$-nice with $I_\ell =\mathbb{R}$. For a closed interval $I = [c,d]$ define the function \begin{align*} \clip(t, I) = \begin{cases} c \ \text{if} \ t \leq c\\ t \ \text{if} \ c \leq t \leq d\\ d \ \text{if} \ d \leq t. \end{cases} \end{align*} We use some simple facts about this function without proof, the first is a simple consequence of $\epsilon$-optimality and convexity. \begin{lemma} \label{lem:tech} If $\ell$ is $(B, \epsilon)$-nice, then $\ell(y,\clip(t, I_\ell)) \leq \ell(y,t) + \epsilon$. The function $\clip(t,I_\ell)$ is $1$-Lipschitz as a function of $t$. \end{lemma} Here are a few examples of nice loss functions: \begin{itemize} \item Binary classification with different false-positive/negative costs, e.g., $\ell(y, t) = \kappa_y |y-t|$ where $\kappa_0 \neq \kappa_1$ are the different costs. Here $I_\ell =[0,1], B =\max(\kappa_0, \kappa_1), \epsilon=0$. \item The $\ell_p$ losses for $p \geq 1$: \[ \ell_p(y, t) {:=} |y-t|^p \] take $I_\ell=[0,1], B=p, \epsilon=0$. \item The exponential loss $\ell(y, t) = e^{(1 - 2y) t}$. Here, for any $\epsilon > 0$, we can take $I_\ell=[-\ln (1/\epsilon), \ln (1/\epsilon)]$ and $B = 1/\epsilon$. \item The logistic loss $\ell(y, t) = \log(1 + \exp((1 -2y)t))$. Here we take $I_\ell = \mathbb{R}$, $B =1$ and $\epsilon = 0$. \item The hinge loss $\ell(y, t)=\max(0,1+(1-2y)t)$. Here we take $I_\ell = \mathbb{R}$, $B =1$ and $\epsilon = 0$. \end{itemize} It is worth noting that only for exponential loss did we need $\epsilon > 0$. \section{Omnipredictors\xspace} \label{sec:omni} In this section, we define our notion of Omnipredictors\xspace. Our definitions are simpler for the case of binary labels where $\mathcal{Y} = \ensuremath{\{0,1\}}$, hence we present that case first. Recall that for a predictor $h$, $\ell_\mathcal{D}(h)$ is the expected loss of $h$ under $\mathcal{D}$. \begin{definition}[Omnipredictor\xspace] \label{def:omni} Let $\mathcal{C}$ be family of functions on $\mathcal{X}$, and let $\mathcal{L}$ be a family of loss functions. The predictor $f:\mathcal{X} \rightarrow \ensuremath{[0,1]}$ is an $(\mathcal{L}, \mathcal{C}, \delta)$-omnipredictor\xspace if for every $\ell \in \mathcal{L}$ there exists a function $k:\ensuremath{[0,1]} \rightarrow \mathbb{R}$ so that \[ \ell_\mathcal{D}(k \circ f) \leq \min_{c \in \mathcal{C}} \ell_\mathcal{D}(c) + \delta. \] \end{definition} The definition states that for every loss $\ell$, there is a simple (univariate) transformation $k$ of the predictions $f$, such that the composition $k \circ f$ has loss comparable to the best hypothesis $c \in \mathcal{C}$, which is chosen tailored to the loss $\ell$. Setting aside efficiency considerations, it is easy to show that $f^*$ is an omnipredictor\xspace for every $\mathcal{C}, \mathcal{L}$. \begin{lemma} For every $\mathcal{C}, \mathcal{L}$, the ground-truth predictor $f^*$ is an $(\mathcal{L}, \mathcal{C}, 0)$-omnipredictor\xspace. \end{lemma} \begin{proof} By the definition of omnipredictors\xspace, given an arbitrary loss function $\ell: \ensuremath{\{0,1\}} \times \mathbb{R} \rightarrow \mathbb{R}$, our goal is to find $k^*_\ell:\ensuremath{\{0,1\}} \rightarrow \mathbb{R}$ so that \begin{align} \label{eq:f*} \ell_\mathcal{D}(k^*_\ell \circ f) \leq \min_{c:\mathcal{X} \rightarrow \mathbb{R}} \ell_\mathcal{D}(c). \end{align} Define the function $k^*_\ell: \ensuremath{[0,1]} \rightarrow \mathbb{R}$ which minimizes expected loss under the Bernoulli distribution: \begin{align} \label{eq:def-k*} k_\ell^*(p) = \argmin_{t \in \mathbb{R}} \E_{\mathbf{y} \sim \B{p}}[\ell(\mathbf{y},t)] = \argmin_{t \in \mathbb{R}} p\ell(1, t) + (1 - p)\ell(0, t). \end{align} If there are multiple minima we break ties arbitrarily. Conditioned on $\mathbf{x} =x$, $\mathbf{y} \sim \B{f^*(x)}$, so $k_\ell^*(f^*(x)) \in \mathbb{R}$ is the value that minimizes the expected loss. Hence for every $x \in \mathcal{X}$, \[ \E_{\mathcal{D}|\mathbf{x} =x}[\ell(\mathbf{y}, k_\ell^*(f^*(x))] \leq \E_{\mathcal{D}|\mathbf{x} =x}[\ell(\mathbf{y}, c(x))].\] Equation \eqref{eq:f*} follows by averaging over all values of $x$. \end{proof} Note that the function $k^*_\ell$ depends on $\ell$ but is independent of the distribution $\mathcal{D}$. For instance, for the $\ell_1$ loss, $\ell_1(y, t) = |y -t|$, we have $k_{\ell_1}^*(p) = \ind{p \geq 1/2}$. For the $\ell_2$ loss $\ell_2(y,t) = (y -t)^2$, we have $k_{\ell_2}^*(p) = p$. While Definition \ref{def:omni} does not place any restrictions on the post-processing function $k$, in our upper bounds, we will choose $k$ which is very close to the function $k^*$ above. Our upper bounds will be efficient for (convex) functions $\ell$ such that a good approximation to $k^*$ can be be approximated efficiently. Our lower bounds will hold for arbitrary $k$. Finally, a natural family of predictors arising from partitions plays a key role in our results. \begin{definition} \label{def:canonical} Given a partition $\mathcal{S}$ of $\mathcal{X}$ of size $m$, let $\E_{\mathcal{D}_i}[\mathbf{y}] = p_i \in [0,1]$ for $i \in [m]$. The canonical predictor for $\mathcal{S}$ is $f^\mathcal{S}(x) = p_i$ for all $x \in S_i$. \end{definition} The canonical predictor simply predicts the expected label in each state of the partition. Since $f^\mathcal{S}$ is constant within each state of the partition, it can be viewed as a function $f^\mathcal{S}: \mathcal{S} \rightarrow \mathbb{R}$. This view will be useful in our results. \paragraph{Omnipredictors\xspace for general $\mathcal{Y}$.} Consider the setting where we are given a distribution $\mathcal{D}$ on $\mathcal{X} \times \mathcal{Y}$ for $\mathcal{Y} \subseteq \mathbb{R}$, hence the labels can take on real values. We are primarily interested in the real-valued setting of $\mathcal{Y} = \ensuremath{[0,1]}$, and the multi-class setting where $\mathcal{Y} =[l]$. Given a state $S_i$ in a partition $\mathcal{S}$, let $P_i \in \mathcal{P}(\mathcal{Y})$ denote the distribution of $\mathbf{y}$ under $\mathcal{D}_i$. The canonical predictor $f^\mathcal{S}: \mathcal{X} \rightarrow \mathcal{P}(\mathcal{Y})$ is given by $f^\mathcal{S}(x) = P_i$ for all $x \in S_i$. We now define the notion of an omnipredictor\xspace. The main difference from the binary case is that the predictor now predicts a distribution in $\mathcal{P}(\mathcal{Y})$, so the post-processing function $k$ maps {\em distributions} to real values. \begin{definition} \label{def:omni-real} Let $\mathcal{C}$ be family of functions on $\mathcal{X}$, and let $\mathcal{L}$ be a family of loss functions $\ell: \mathcal{Y} \times \mathbb{R} \rightarrow \mathbb{R}$. The predictor $f:\mathcal{X} \rightarrow \mathcal{P}(\mathcal{Y})$ is an $(\mathcal{L}, \mathcal{C}, \delta)$-omnipredictor\xspace if for every $\ell \in \mathcal{L}$ there exists a function $k:\mathcal{P}(\mathcal{Y}) \rightarrow \mathbb{R}$ so that \[ \ell_\mathcal{D}(k \circ f) \leq \min_{c \in \mathcal{C}} \ell_\mathcal{D}(c) + \delta. \] \end{definition} \eat{ An equivalent definition can be given in terms of the conditional expectations. \begin{definition} \label{def:m-cal-01} The partition $\mathcal{S}$ of $\mathcal{X}$ is $\alpha$-multicalibrated\xspace for $\mathcal{C}, \mathcal{D}$ if for every $i \in [m]$ such that $\Var_{ \mathcal{D}_i}[y] > 0$ and for every $c \in \mathcal{C}$, \begin{align} \label{eq:m-cal-01} \abs{\E_{\mathcal{D}_i|\mathbf{y} =1}[c(\mathbf{x})] - \E_{\mathcal{D}_i|\mathbf{y} = 0}[c(\mathbf{x})]}\leq \frac{\alpha}{\Var_{\mathcal{D}_i}[y]} . \end{align} \end{definition} Having $\Var_{\mathcal{D}_i}[\mathbf{y}] > 0$ ensures that both the conditional distributions $\mathcal{D}_i|\mathbf{y} =1$ and $\mathcal{D}_i|\mathbf{y} = 0$ are well defined. For states where $\mathbf{y}$ is constant and $\Var_{\mathcal{D}_i}[\mathbf{y}] =0$, we say that the multicalibration\xspace\ condition holds trivially. \begin{lemma} Definitions \ref{def:m-cal} and \ref{def:m-cal-01} are equivalent. \end{lemma} \begin{proof} First consider states where $\mathbf{y} \sim \mathcal{D}_i$ is constant, hence $\Var_{\mathcal{D}_i}[\mathbf{y}] = 0$. Such states are trivially approximately multicalibrated\xspace by Definition \ref{def:m-cal-01}. They also satisfy Equation \eqref{eq:m-cal} since \[ \CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}] = \E_{\mathcal{D}_i}[c(\mathbf{x})(\mathbf{y} - \E_{\mathcal{D}_i}[\mathbf{y}])] = 0.\] Now consider states where $\mathbf{y}$ is not constant. We can simplify Equation \eqref{eq:m-cal} by putting $p_i = \E_{\mathcal{D}_i}[\mathbf{y}]$, and rewriting it as \begin{align} \label{eq:m-cal2} \abs{\CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}]} = \abs{\E_{\mathcal{D}_i}[c(\mathbf{x})(\mathbf{y} - p_i)]} \leq \alpha . \end{align} We can sample $(\mathbf{x}, \mathbf{y})$ from $\mathcal{D}_i$ in two steps, we first sample $\mathbf{y} \in \ensuremath{\{0,1\}}$ where $\Pr[\mathbf{y} =1] = p_i$, and then sample $\mathbf{x} \sim D_i|\mathbf{y}$. Hence we can write \begin{align*} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[c(\mathbf{x}) (\mathbf{y} - p_i)] &= p_i\E_{\mathbf{x} \sim D_i|\mathbf{y} = 1}[c(\mathbf{x}) (1 - p_i)] + (1 -p_i) \E_{\mathbf{x} \sim D_i|\mathbf{y} = 0}[c(\mathbf{x}) ( -p_i)]\\ &= p_i(1 -p _i) \left(\E_{\mathcal{D}_i|\mathbf{y} =1}[c(\mathbf{x})] - \E_{\mathcal{D}_i|\mathbf{y} = 0}[c(\mathbf{x})]\right)\\ &= \Var_{\mathcal{D}_i}[\mathbf{y}] \left(\E_{\mathcal{D}_i|\mathbf{y} =1}[c(\mathbf{x})] - \E_{\mathcal{D}_i|\mathbf{y} = 0}[c(\mathbf{x})]\right) \end{align*} Hence Equation \eqref{eq:m-cal2} and \eqref{eq:m-cal-01} are equivalent assuming $\Var_{\mathcal{D}_i}[\mathbf{y}] \neq 0$. \end{proof} \subsection{A relaxed definition} } \section{Omnipredictors\xspace in the real valued setting} \label{sec:real} In this section we will consider two settings: \begin{enumerate} \item {\bf The multi-class setting}. Here the labels take values in $[l]$. For each $j \in [l]$, the label $j$ is associated with the loss function $\ell(j, t)$ which is $(B, \epsilon)$-nice. This means that there is an interval $I_\ell$ for which the $B$-Lipshcitz and $\epsilon$-optimality property hold for the functions $\ell(j, t)$ for every $j \in [k]$. The loss functions for different labels could be very different, in analogy to different false positive and negative scores for the Boolean case. \item {\bf The real-valued setting}. Here the labels take values in $\ensuremath{[0,1]}$. We will assume that the loss function $\ell(y, t)$ is $B$-Lipschitz in $y$ for all $t$, and that $\ell(y, t)$ is $(B, \epsilon)$-nice as a function of $t$.\footnote{One can relax the Lipschitz requirement in the first argument and only require it for $t \in I$ rather than all $t$. We work with the stronger assumption for simplicity} \end{enumerate} We show that for nice loss functions, omniprediction in the real-valued setting reduces to the multi-class setting. We take $l = \lceil B/\epsilon \rceil$ and partition $[0,1]$ into $l$ disjoint buckets $\{b_j\}_{j=1}^l$ of width $\epsilon/B$ each. For $y \in b_j$, we use the loss function $\ell(j/l, t)$ in place of $\ell(y,t)$. This amounts to discretizing $y$ to $\hat{y}$ where $|y -\hat{y}| \leq \epsilon/B$. By the $B$-Lipschitz property, it follows that for any predictor $f:\mathcal{X} \rightarrow \mathbb{R}$, \begin{align} \abs{\E_{\mathcal{D}}[\ell(\mathbf{y}, f(\mathbf{x}))] - \E_{\mathcal{D}}[\ell(\hat{\mathbf{y}}, f(\mathbf{x}))]} \leq \E_{\mathcal{D}}\left[ \abs{\ell(\mathbf{y}, f(\mathbf{x}) - \ell(\hat{\mathbf{y}}, f(\mathbf{x})} \right] \leq \epsilon.\label{eq:real_reduction} \end{align} Since $\hat{y}$ takes on $l$ discrete values, we have reduced to the multi-class setting. Hence we now focus on generalizing our results to the multi-class setting where $\mathcal{Y} =[l]$ for $l \geq 2$. Recall that the definition of multicalibration\xspace in the multi-class requires that for all $c \in \mathcal{C}$ and $j \in [l]$, we have \begin{align} \label{eq:multi-class} \E_{\i \sim \mathcal{D}}\left[\abs{\CoVar_{\mathcal{D}_\i}[c(x)\ind{\mathbf{y} = j}]}\right] \leq \alpha. \end{align} Let $\mathcal{P}(l)$ denote the space of probability distributions on $l$. Given a partition $\mathcal{S}$, we associate to each state $S_i$ a probability distribution over labels $P_i \in \mathcal{P}(l)$. The canonical predictor $f^\mathcal{S}: \mathcal{X} \rightarrow \mathcal{P}(l)$ predicts a in $\mathcal{P}$ for every $x \in \mathcal{X}$ and is given by \[ f^\mathcal{S}(x) = P_i \ \forall x \in S_i. \] In analogy with the corresponding definitions for the binary classification setting, for every $P \in \mathcal{P}(l)$ we define $k_\ell(P) \in I$ to be the action that minimizes expected loss under $P$: \begin{align*} k_\ell(P) = \arg\min_{t \in I}\E_{\j \sim P}[\ell(\j, t)] \end{align*} and the $\ell$-optimized hypothesis $h^\mathcal{S}_\ell:\mathcal{X} \rightarrow I$ by \begin{align*} f^\mathcal{S}_\ell(x) = k_\ell(P_i) \ \forall x \in S_i. \end{align*} Our main theorem is a direct generalization of Theorem \ref{thm:key}. \begin{theorem} \label{thm:key-k} Let $\mathcal{D}$ be a distribution on $\mathcal{X} \times [l]$ and $\ell :[l] \times \mathbb{R} \rightarrow \mathbb{R}$ be a $(B, \epsilon)$-nice loss function. If the partition $\mathcal{S}$ is $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$, then the canonical predictor $f^\mathcal{S}$ is an $(\mathcal{L}, \mathcal{C}, k\alpha B + \epsilon)$-omnipredictor\xspace. \end{theorem} The theorem follows from the next Lemma which generalizes Lemma \ref{lem:better} to $l \geq 2$. Since the proof follows along similar lines till the last step, we only describe the difference. \begin{lemma} \label{lem:better-k} Let $\ell: [l] \times \mathbb{R} \rightarrow \mathbb{R}$ be an $(B, \epsilon)$ nice function. Given $c \in \mathcal{C}$, if we define the predictor $\hat{c}: \mathcal{S} \rightarrow I_\ell$ by \[ \hat{c}(x) = \clip\left(\E_{\mathcal{D}_i}[c(x)], I_\ell\right) \ \text{for} \ x \in S_i. \] then \begin{align} \ell_\mathcal{D}(\hat{c}) \leq \ell_\mathcal{D}(c) + l\alpha B + \epsilon. \end{align} \end{lemma} \begin{proof} We follow the proof of Lemma \ref{lem:better} till Equation \eqref{eq:use-this}, this portion does not assume $\mathbf{y} \in \ensuremath{\{0,1\}}$. At this point we have established that \begin{align} \label{eq:used-that} \ell_\mathcal{D}(\hat{c}) - \ell_\mathcal{D}(c) -\epsilon &\leq B\E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i} \left| \E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]\right| \end{align} The following analog of Corollary \ref{cor:bin} follows from Equation \eqref{eq:covar-1} about covariance with binary random variables. For every $j \in [l]$ \begin{align*} \E_{\i \sim \mathcal{D}} \left[ \Pr_{\mathcal{D}_i}[\mathbf{y} = j]\left|\E_{\mathcal{D}_\i|\mathbf{y} = j}[c(\mathbf{x})] - \E_{\mathcal{D}_\i}[c(\mathbf{x})]\right| \right] = \E_{\i \sim \mathcal{D}}\left[\left|\CoVar_{\mathcal{D}_\i}[c(\mathbf{x}), \ind{\mathbf{y} =j}\right|\right] \leq \alpha. \end{align*} We use this to bound the RHS of Equation \eqref{eq:used-that} as \begin{align*} \E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i} \left| \E_{\mathbf{x} \sim \mathcal{D}_i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]\right| &= \E_{\i \sim \mathcal{D}}\sum_{j \in [l]}\Pr_{\mathcal{D}_\i}[\mathbf{y} =j] \left| \E_{\mathbf{x} \sim \mathcal{D}_\i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim \mathcal{D}_\i|\mathbf{y} = j}[c(\mathbf{x})]\right|\\ &= \sum_{j \in [l]} \E_{\i \sim \mathcal{D}}\left[\Pr_{\mathcal{D}_\i}[\mathbf{y} =j] \left| \E_{\mathbf{x} \sim \mathcal{D}_\i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim \mathcal{D}_\i|\mathbf{y} = j}[c(\mathbf{x})]\right|\right]\\ & \leq \sum_{j \in [l]}\alpha = l\alpha. \end{align*} Plugging this into the RHS of Equation \eqref{eq:used-that} gives the desired bound. \end{proof} We now derive the proof of Theorem \ref{thm:key-k}. From the definition of $h^\mathcal{S}_\ell$ it follows that \[ h^\mathcal{S}_\ell = \argmin_{h:\mathcal{S} \rightarrow I_\ell} \ell_\mathcal{D}(h). \] Since $\hat{c}: \mathcal{S} \rightarrow I_\ell$ this implies $ \ell_\mathcal{D}(h^\mathcal{S}_\ell) \leq \ell_\mathcal{D}(\hat{c})$. The claim now follows from Lemma \ref{lem:better-k}. \subsection{Improved bounds for squared loss} One of the most commonly used losses for the real-valued case is the squared loss $\ell_2(y, t) = (t -y)^2$. For this loss, we can show a stronger bound. Since $\ell_2$ is a {\em proper} scoring rule, the post-processing function $k^*_{\ell_2}$ is just the identity function, hence $h^\mathcal{S}_{\ell_2}(x) = f^\mathcal{S}(x) =\E_{ \mathbf{y} \sim \mathcal{D}_i}[\mathbf{y}] = p_i$. We will show the following guarantee comparing it to any linear function. \begin{theorem} \label{thm:ell_2} Consider the real-valued prediction problem with $y\in [0,1]$, let $\hat{y}$ be a discretization of $y$ into $\lceil 1/\epsilon \rceil$ buckets (as in Equation \ref{eq:real_reduction}). Let $\mathcal{S}$ be $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$, and $f^\mathcal{S}(x)$ be the predictor defined above. Let $\ell(\mathbf{y}, t) = (t- y)^2$ denoted the $\ell_2$ loss. For any function $g_w \in \mathrm{Lin}_\mathcal{C}$ and $y \in [0,1]$, we have \begin{align} \label{eq:ell_2} \ell_{\mathcal{D}}(f^\mathcal{S}) + \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} [(g_w(\mathbf{x}) - f^\mathcal{S}(\mathbf{x}))^2] \leq \ell_\mathcal{D}(g_w) + \lceil 1/\epsilon \rceil \alpha \|w\|_1 + \epsilon. \end{align} \end{theorem} Let us compare this bound with the one implied by Corollary \ref{cor:lipschitz}, which applies since $\ell_2$ loss is $([0,1], 1,0)$-nice. The main difference is the addition of the term $\E[(g_w(\mathbf{x}) - f^\mathcal{S}(\mathbf{x}))^2]$ to the LHS. This tells us that when $\lceil 1/\epsilon \rceil \alpha\|w\|_1$ is small (say $O(\epsilon)$), any linear function that is far (in squared distance) from $f^\mathcal{S}$ incurs large $\ell_2$ loss. This theorem follows from the following {\em Pythagorean bound} which holds for the squared error, proved in Appendix \ref{sec:l2_proof}. \begin{lemma}\label{lem:l2} In the setting of Theorem \ref{thm:ell_2}, \begin{align*} \abs{\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[ \ell_2(\mathbf{y}, g_w(\mathbf{x}))] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} [\ell_2(\mathbf{y}, f_\mathcal{S}(\mathbf{x}))] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} [(g_w(\mathbf{x}) - f_\mathcal{S}(\mathbf{x}))^2] } \leq \lceil 1/\epsilon \rceil\alpha \|w\|_1 + \epsilon. \end{align*} \end{lemma} \eat{ \begin{lemma} For any $c \in \mathcal{C}$, we have \begin{align*} \E_{\mathcal{D}}\ell(\mathbf{y}, c(\mathbf{x})) + \alpha k B \geq \E_{\i \sim \mathcal{D}} \left[\ell\left(\mathbf{y}, \E_{\mathcal{D}_i}[c(\mathbf{x})]\right) \right] . \end{align*} \end{lemma} \begin{proof} By the convexity of $\ell(\mathbf{y}, t)$ as a function of $t$, we have \begin{align*} \E_{\mathcal{D}}[\ell(\mathbf{y}, c(\mathbf{x}))] = \E_{i \sim \mathcal{D}}\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_\i}[\ell(\mathbf{y}, c(\mathbf{x}))] = \E_{i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i}\E_{\mathbf{x} \sim \mathcal{D}_i|\mathbf{y}}[\ell(\mathbf{y}, c(\mathbf{x}))]\geq \E_{i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_\i}\left[\ell\left(\mathbf{y}, \E_{\mathbf{x} \sim\mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]\right)\right] \end{align*} So we can write \begin{align*} \E_{\i \sim \mathcal{D}} \E_{\mathcal{D}_i}\left[\ell\left(\mathbf{y}, \E_{\mathcal{D}_i}[c(\mathbf{x})]\right)\right] - \E_{\mathcal{D}}\ell(\mathbf{y}, c(\mathbf{x})) &\leq \E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_i} \left[ \ell\left(\mathbf{y}, \E_{\mathbf{x} \sim\mathcal{D}_i}[c(\mathbf{x})]\right) - \ell\left(\mathbf{y}, \E_{\mathbf{x} \sim\mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]\right)\right]\\ &\leq \E_{\i \sim \mathcal{D}}\E_{\mathbf{y} \sim \mathcal{D}_i}\left[ B\abs{\E_{\mathbf{x} \sim\mathcal{D}_i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim\mathcal{D}_i|\mathbf{y}}[c(\mathbf{x})]}\right]\\ &= \E_{\i \sim \mathcal{D}}\left[\sum_{j \in [k]} B \Pr[\mathbf{y} = j]\abs{\E_{\mathbf{x} \sim\mathcal{D}_i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim\mathcal{D}_i|\mathbf{y} = j}[c(\mathbf{x})]}\right] \\ & = B\sum_{j \in [k]}\E_{\i \sim \mathcal{D}} \left[\Pr[\mathbf{y} = j]\abs{\E_{\mathbf{x} \sim\mathcal{D}_i}[c(\mathbf{x})] - \E_{\mathbf{x} \sim\mathcal{D}_i|\mathbf{y} = j}[c(\mathbf{x})]}\right] \\ &\leq \alpha k B \end{align*} where the last line uses Lemma \ref{lem:tech}. \end{proof} } \eat{ One of the most commonly used losses for the real-valued case is the squared loss $\ell_2(y, t) = (t -y)^2$. For this loss, we can show a stronger bound. Since $\ell_2$ is a {\em proper} scoring rule, no adjustment is needed to the canonical predictor, $f^\mathcal{S}_{\ell_2}(x) = f^\mathcal{S}(x) = p_i$. We will show the following guarantee comparing it to any linear function. \begin{theorem} \label{thm:ell_2} Let $\mathcal{S}$ be $\alpha$-approximately multicalibrated\xspace\ for $\mathcal{C}, \mathcal{D}$, and $f^\mathcal{S}(x)$ be the predictor defined above. For any function $g_w \in \mathrm{Lin}_\mathcal{C}$ and $y \in [0,1]$, we have \begin{align} \label{eq:ell_2} \bar{\ell}_2(f^\mathcal{S}, \mathcal{D}) + \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} [(g_w(\mathbf{x}) - f^\mathcal{S}(\mathbf{x}))^2] \leq \bar{\ell_2}(g_w, \mathcal{D}) +\alpha \|w\|_1 + \epsilon. \end{align} \end{theorem} Let us compare this bound with the one implied by Corollary \ref{cor:lipschitz}, which applies since $\ell_2$ loss is $([0,1], 1,0)$-nice. The main difference is the addition of the term $\E[(g_w(\mathbf{x}) - f^\mathcal{S}(\mathbf{x}))^2]$ to the LHS. This tells us that when $\alpha\|w\|_1$ is small, any linear function that is far (in squared distance) from $f^\mathcal{S}$ incurs large $\ell_2$ loss. This theorem follows from the following {\em Pythagorean bound} which holds for the squared error. \begin{lemma} In the setting of Theorem \ref{thm:ell_2}, \begin{align*} \abs{\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[ \ell_2(\mathbf{y}, g_w(\mathbf{x}))] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} [\ell_2(\mathbf{y}, f_\mathcal{S}(\mathbf{x}))] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}} [(g_w(\mathbf{x}) - f_\mathcal{S}(\mathbf{x}))^2] } \leq \alpha \|w\|_1 + \epsilon. \end{align*} \end{lemma} \begin{proof} Since the squared loss is $1$-Lipschitz, by the argument in Equation \eqref{eq:real_reduction}, we can work with an $\epsilon$-discretization of the interval $[0,1]$ with at most $\epsilon$ loss. Therefore, for $k=\lceil 1/\epsilon \rceil$, let $y=j\epsilon$, for $j \in \{0,\dots,k\}$. For any $(x,y)$ we have \begin{align*} (g_w(x) - y)^2 = (g_w(x) - p_i)^2 + (p_i -y)^2 + 2(g_w(x) - p_i)(p_i - y). \end{align*} As in the proof of Theorem \ref{thm:key}, let use denote $\alpha_i = \CoVar_{\mathcal{D}_i}[c(\mathbf{x}), \mathbf{y}]$. Fixing $i \in [m]$ and taking expectations over $(\mathbf{x},\mathbf{y}) \sim \mathcal{D}_i$ \begin{align} \label{eq:sq-error} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[ (g_w(\mathbf{x}) - \mathbf{y})^2] &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(g_w(\mathbf{x}) - p_i)^2] + \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(p_i - \mathbf{y})^2]\notag\\ & + 2p_i\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [p_i - \mathbf{y}] + 2\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [g_w(\mathbf{x})(p_i - \mathbf{y} )] . \end{align} We can simplify all except the last term as \begin{align*} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[ (g_w(\mathbf{x}) - \mathbf{y})^2] &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}}[\ell_2(\mathbf{y}, g_w(\mathbf{x})]\\ \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(g_w(\mathbf{x}) - p_i)^2] &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(g_w(\mathbf{x}) - f^\mathcal{S}(\mathbf{x}))^2]\\ \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(p_i - \mathbf{y})^2] &= \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(f^\mathcal{S}(\mathbf{x}) - \mathbf{y})^2] = \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[\ell_2(\mathbf{y}, f^\mathcal{S}(\mathbf{x}))] \\ \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [p_i - \mathbf{y}] &= 0. \end{align*} For the last term in Equation \eqref{eq:sq-error} we can write, \begin{align*} \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [g_w(\mathbf{x})(\mathbf{y} - p_i)] &= \sum_{j \geq 1}w_j \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [c_j(\mathbf{x})(\mathbf{y} - p_i)]\\ &= \end{align*} Plugging back into Equation \eqref{eq:sq-error} and rearranging gives \begin{align*} \abs{\E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i}[ \ell_2(\mathbf{y}, g_w(\mathbf{x}))] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [\ell_2(\mathbf{y}, f^\mathcal{S}(\mathbf{x}))] - \E_{(\mathbf{x}, \mathbf{y}) \sim \mathcal{D}_i} [(g_w(\mathbf{x}) - p_i)^2] } \leq \alpha_i \|w\|_1 \end{align*} Now averaging over $i \in [m]$ with probability $\mathcal{D}(S_i)$ gives the desired inequality. \end{proof} } \section{Related work} \label{sec:related} While the notion of an omnipredictor\xspace is introduced in this work, our definitions draw on two previous lines of work. The first is the notion of multicalibration\xspace\ for predictors that was defined in the work of Herbert-Johnson {\it et al.}\ \cite{hkrr2018}.\footnote{See also \cite{kearns2018}, who in parallel with \cite{hkrr2018} introduced notions of multi-group fairness.} A detailed discussion of how our definitions of multicalibration\xspace compare to previous definitions appears in Appendix \ref{app:def-mcab}. The other is work on boosting by branching programs of Mansour-McAllester \cite{MansourM2002}, which built on Kearns-Mansour \cite{KearnsM99} and the notion of correlation boosting \cite{Kalai04, kalai2005boosting}. \paragraph{Group fairness and multicalibration\xspace.} While multicalibration\xspace was introduced with the motivation of algorithmic fairness, it has been shown to be quite useful from the context of accuracy when learning in an heterogeneous environment. This was done both experimentally \cite{kgz,BardaYRGLBBD21} and in real-life implementations~\cite{BardaEtal20}. From a theoretical perspective, it has been shown in \cite{hkrr2018} that post-processing a predictor to make it multicalibrated cannot increase the $\ell_2$ loss. This was extended to showing some optimality results of multicalibrated predictors with respect to $\ell_2$ and even log-loss \cite{GargKR19,KimThesis}. Multicalibrated predictors are also connected to loss minimization through the notion of outcome-indistinguishability \cite{OI} in the work of \cite{RothblumYon21}. Outcome indistinguishability shows that a multicalibrated predictor is indistinguishable from the true probabilities predictor in a particular technical sense. In~\cite{RothblumYon21} this is used to create a predictor that can be used to minimize a rather general and potentially global notion of loss even when restricted to sub-groups. The proof constructs a family of distinguishers, for a fixed loss function, such that if there exists a subset on which the a predictor doesn't minimize the loss function then one of the predictors can distinguish the predictor from the true-probabilities predictor in the sense of outcome indistinguishability. The main way in which all of these results are different from what we show is that they do not seek to simultaneously allow for the minimization of such a rich family of loss functions. In the case of~\cite{RothblumYon21}, since the result goes through outcome indistinguishability, to minimize a loss with respect to a class $\mathcal{C}$, a predictor needs to be multicalibrated with respect to a different class that relies on the loss function and incorporates the reduction from multicalibration and outcome indistinguishability. In contrast, our result addresses minimization of a family of losses that may not be known at the time of learning, and we assume the learnability of $\mathcal{C}$ alone. Convexity of the losses plays a key role in our upper bounds. \paragraph{Agnostic boosting.} Our work is closely related to work on boosting via branching programs \cite{KearnsM99, MansourM2002, kalai2005boosting, Kalai04}. Indeed, the splitting criterion used in the work of Kalai \cite{Kalai04} is precisely that $\CoVar[c(\mathbf{x}), \mathbf{y}] \geq \alpha$ for some $c \in \mathcal{C}$, for the task of learning generalized linear models. The {\em okay learners} in the work of \cite{kalai2005boosting} are also based on having non-trivial Covariance with the target. Our results show that upon termination, these algorithms yields an approximately multicalibrated\xspace\ partition; hence we can view multicalibration\xspace\ as a solution concept for the output of Boosting by Branching Program family of algorithms. It was known that these algorithms have stronger noise tolerance properties than potential based algorithms such as AdaBoost, see \cite{kalai2005boosting, KalaiMV08}. Our results significantly strengthen our understanding of the power of these algorithms, showing that they give guarantees for a broad family of convex loss functions, and not just $0$-$1$ loss. \paragraph{Naive instantiations of the composition approach.} The obvious attempt to building omnipredictors\xspace would be to learn a model $f$ for $f^*$ using a model family $\mathcal{F}$ such as logistic regression, and then compose it with the right post-processing function $k_{\ell}^*$ for a given loss $\ell$. In the context of binary classification, for certain families of non-decomposable accuracy metrics (including $F$-scores and AUC), it is shown in \cite{NatarajanKRD15, DKKN17} that this approach gives the best predictor for the hypothesis class $\mathcal{C}$ of binary classifiers derived by thresholding models from $\mathcal{F}$. These results can be seen as a form of omnipredictors\xspace, but with strong restrictions on $\mathcal{L}$ and $\mathcal{C}$. Their results do not apply to the decomposable convex losses we consider; indeed it seems unlikely that the output of logistic regression can give reasonable guarantees for say the exponential loss or squared loss, even with post-processing. More importantly, our results hold for arbitrary classes $\mathcal{C}$ that are weakly agnostically learnable. For any such class, we show how to construct a model $f$ which is an omnipredictor\xspace. In contrast, their results prove optimality for a rather limited hypothesis class $\mathcal{C}$ derived from the model family $\mathcal{F}$. \paragraph{Condtional density estimation} For real-valued $y \in \mathbb{R}$, an omnipredictor\xspace solves the problem of \textit{Conditional Density Estimation} (CDE) \cite{hansen1994autoregressive}. While CDE is recognized as an important problem in practice and a number of CDE algorithms have been proposed, it has received little attention in the computational learning theory literature. The notion of omnipredictor\xspace is related to the statistical notion of a \textit{sufficient statistic}, which is a statistic that captures all relevant information about a distribution. \paragraph{Surrogate loss functions for classification} There is a large literature in statistics which shows that a convex surrogate loss function (with certain properties) can be used instead of the hard to optimize 0-1 loss, and any hypothesis $c \in \mathcal{C}$ which minimizes the surrogate loss will also minimize the original 0-1 loss with respect to $\mathcal{C}$ \cite{lugosi2004bayes,steinwart2005consistency,bartlett2006convexity}. There are also similar results for the multi-class 0-1 loss \cite{tewari2007consistency}, and in the asymmetric setting when the false positive and false negative costs are known \cite{scott2012calibrated}. However, this line of work is quite different from ours, crucially an $(\mathcal{L}, \mathcal{C})$-omnipredictor\xspace optimizes not just for a single loss but for any loss in the family $\mathcal{L}$ (such as different false positive and false negative costs, we recall that as Fig. \ref{fig:1} shows this cannot be achieved with a single hypothesis from $\mathcal{C}$).
{'timestamp': '2021-09-14T02:17:50', 'yymm': '2109', 'arxiv_id': '2109.05389', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05389'}
arxiv
\section{Introduction} With the rapid advancement of Internet of Things (IoT) and social networking applications, there is an exponential increase of data generated at network edge devices, such as smartphones, IoT devices, and sensors \cite{chiang2016fog}. These valuable data provide highly useful information for the prediction, classification, and other intelligent applications, which can improve our daily lives \cite{shalev2014understanding}. To analyze and exploit the large amount of data, standard machine learning (ML) techniques normally require collecting the training data {in a central server}. However, such centralized data collection and training can be quite challenging to perform due to limited communication bandwidth and data privacy concerns \cite{mao2017survey,park2019wireless}. To tackle this challenge, \emph{Federated learning (FL)} has emerged as an attractive distributed learning paradigm, which enables many clients\footnote{Depending on the type of clients, FL can be categorized into cross-device FL and cross-silo FL (clients are companies or organizations, etc.) \cite{kairouz2019advances}. This paper focuses on the former and we use ``device'' and ``client'' interchangeably.} to collaboratively train a model under the coordination of a central server, while keeping the training data decentralized and private\cite{mcmahan2017communication,kairouz2019advances}. In FL settings, the training data are in general massively distributed over a large number of clients, and the communications between the server and clients are typically operated at lower rates compared to datacenter settings. These unique features necessitate FL algorithms to perform \emph{multiple local iterations} in parallel on \emph{a fraction of randomly sampled clients} and then aggregate the resulting model update via the central server periodically \cite{mcmahan2017communication}.\footnote{{Model compression is also an effective approach for improving FL communication efficiency. While orthogonal to the focus of this work, standard compression approaches such as sketched or random masking and model pruning \cite{jiang2020pruning,kairouz2019advances} can be used together to further reduce the cost.}} {FL has demonstrated its effectiveness in various \emph{statistically heterogeneous} settings, e.g., unbalanced and {non-independent and identically distributed (non-i.i.d.)} data \cite{bonawitz2019towards, li2019convergence,9099064,9165960}. Nevertheless, an efficient deployment of FL in mobile edge networks also needs to consider \emph{system heterogeneity}. {This is because in mobile edge environment, the system bandwidth is limited and shared by all connected mobile devices with potential mutual interference. Moreover, the selected devices may have different computational capabilities and dynamic wireless channel conditions due to mobility and channel fading, thus an efficient scheduling strategy in FL should adapt to system heterogeneity.}} Because model training and information transmission for on-device FL can be both time and energy consuming, it is necessary and important to analyze the \emph{cost} that is incurred for completing a given FL task. In general, the cost of FL includes multiple components such as learning time and energy consumption \cite{tran2019federated}. The importance of different cost components depends on the characteristics of FL systems and applications. For example, in a solar-based sensor network, energy consumption is the major concern for the sensors to participate in FL tasks, whereas in a multi-agent search-and-rescue task where the goal is to collaboratively learn an unknown map, achieving timely result would be the first priority. Therefore, a cost-effective FL design needs to \emph{jointly optimize various cost components} (e.g., learning time and energy consumption) \emph{for different preferences}. A way of optimizing the cost is to adapt control variables in the FL process to achieve a properly defined objective. For example, some existing works have considered the adaptation of communication interval (i.e., the number of local iterations between two global aggregation rounds) for communication-efficient FL with convergence guarantees \cite{wang2019adaptive,wang2018adaptive}. However, a limitation in these works is that they only adapt a single control variable (i.e., communication interval) in the FL process and ignore other essential aspects, such as the number of participating clients in each round, which can have a significant impact on the energy consumption. \begin{figure}[!t] \centering \includegraphics[width=9cm,height=6.2cm]{wireless_cost.pdf} \caption{A heterogeneous federated learning training round in mobile network, where $K$ sampled clients performs $E$ steps of local iteration and communicates with the BS with time-sharing. \label{fig:intro} \end{figure} In this paper, we consider a \emph{multivariate} control problem for wireless FL with convergence guarantees. To minimize the expected cost, we develop an algorithm that adapts these control variables in the FL process to achieve our goal. Compared to the univariate setting in existing works, our \emph{multivariate} control problem is much more challenging due to the following reasons: \emph{1)}~The choices of control variables are tightly coupled due to system and statistical heterogeneity. \emph{2)}~The relationship between the control variables and the learning convergence rate has only been captured by an upper bound with unknown coefficients in the literature. \emph{3)} Our cost objective includes multiple components (e.g., time and energy) which can have different importance depending on the application scenario, whereas existing works often consider a single optimization objective, e.g., minimizing the communication overhead. In light of the above discussion, we state the key contributions of this work as follows: \begin{itemize} \item \emph{Cost-effective Wireless FL Design:} This work, for the first time, analyzes how to design adaptive FL that optimally chooses the number of participating clients (${K}$) and the number of local iterations (${E}$) to minimize the \emph{total} cost in mobile edge networks. Considering the wireless bandwidth limitation and interference, we propose a new scheduling scheme, as illustrated in Fig.~1, which characterizes both computation and communication heterogeneity. \item \emph{Optimization Algorithm:} We establish the analytical relationship between the total cost, control variables, heterogeneous system parameters, and convergence upper bound, based on which we formulate and analyze the optimization problem for total cost minimization. When facing the challenging issue of estimating the unknown coefficients in the convergence bound, we develop an effective sampling-based algorithm to learn these parameters with a small estimation overhead. \item {\emph{Theoretical Propertie :} We obtain important analytical properties that effectively identify the design principles of $K$ and $E$ for different optimization metrics and heterogeneous system parameters. Notably, the choice of $K$ leads to an interesting trade-off between learning time reduction and energy saving, with a relatively large $K$ favoring the former while $K=1$ always benefiting the latter. {In contrast, the total cost, no matter emphasizing learning time or energy consumption, always first decreases and then increases in $E$.} We also show how heterogeneous system parameters in terms of computation and communication affect the optimal $K$ and $E$.} \item \emph{Simulation and Experimentation:} We evaluate our theoretical results with real and synthetic heterogeneous datasets, both in a simulated wireless cellular network and on a WiFi-based hardware prototype. Experimental results demonstrate that our proposed optimization algorithm {provides near-optimal solution for different optimization metrics, and verify our theoretical findings for design principles and solution properties. } \end{itemize} The rest of the paper is organized as follows. We first present the related work in Section~\ref{sec:related}. Then, we present the system model and problem formulation in Section~\ref{sec:systemModel}. In Section~\ref{sec:optimizationProblem}, we analyze the cost minimization problem and present an algorithm to solve it. We provide theoretical analysis on the solution properties in Section~\ref{sec:property}. Experimentation results are given in Section~\ref{sec:experimentation} and the conclusion is presented in Section~\ref{sec:conclusion}. \begin{table*}[!tbp] \label{relate_work} \caption{{Summary of related work for FL cost minimization with control parameters}} \resizebox{\textwidth}{35mm}{\begin{tabular}{c||c|c||c|c|c|c} \toprule[1.2pt] \multicolumn{1}{c||}{\multirow{2}{*}{{reference}}} & \multicolumn{2}{c||}{{optimization goal}} & \multicolumn{4}{c}{{control parameters}} \\ \cline{2-7} \multicolumn{1}{c||}{} & {training time} & {energy consumption} & {local iteration number} & {sampled client number} & {mobile clients scheduling} & {resource allocation (CPU/power/bandwidth)} \\ \hline [13] & \checkmark & \checkmark & & & \checkmark & \checkmark \\ \hline [14] & \checkmark & \checkmark & \checkmark & & & \\ \hline [15] & \checkmark & & \checkmark & & & \\ \hline[27] & \checkmark & & & & \checkmark & \checkmark \\ \hline [28] & \checkmark & & & \checkmark & & \\ \hline [29] & \checkmark & & & \checkmark & \checkmark & \\ \hline [30] & \checkmark & & & & \checkmark & \checkmark \\\hline [31] & \checkmark & & & & \checkmark & \checkmark \\\hline [33] & \checkmark & & & & \checkmark & \\\hline [34] & & \checkmark & & & \checkmark & \checkmark \\\hline [35] & & \checkmark & & & \checkmark & \checkmark \\\hline [36] & & \checkmark & & & \checkmark & \checkmark \\\hline [37] & & \checkmark & & & \checkmark & \checkmark \\ \hline [38]& \checkmark & & \checkmark & & & \\ \hline [39] & \checkmark & & \checkmark & & & \\ \hline [41] & \checkmark & & \checkmark & \checkmark & & \\ \hline \textbf{this work} & \textbf{\checkmark} & \textbf{\checkmark} & \textbf{\checkmark} & \textbf{\checkmark} & \textbf{\checkmark} & \\ \midrule[1.2pt] \end{tabular}} \end{table*} \section{Related Work} \label{sec:related} FL was first proposed in \cite{mcmahan2017communication}, which demonstrated FL's effectiveness of collaboratively learning a model without collecting users' data. The de facto FL algorithm is federated averaging (FedAvg), which performs multiple local iterations in parallel on a subset of devices in each round. A system-level FL framework \cite{bonawitz2019towards} demonstrates the empirical success of FedAvg in mobile devices. Recently, a convergence bound of FedAvg was established in \cite{li2019convergence}. {Other related distributed optimization algorithms are mostly analyzed for homogeneous and i.i.d. datasets (e.g., \cite{yu2018parallel,stich2018local,wang2018cooperative}) and full client participation (e.g., \cite{khaled2019first,smith2017federated}), which do not capture the essence of on-device FL.} {{Some extensions of FedAvg considered aspects such as adding a proximal term~\cite{li2018federated}, using gradient descent acceleration~\cite{liu2020accelerating}, variance reduction (e.g., \cite{karimireddy2020scaffold,liang2019variance}), {or fine tuning hyper-parameters~\cite{8814558,reddi2020adaptive}}}. While novel insights are provided in these works, they did not consider optimization for cost/resource efficiency.} {Literature in FL cost optimization mainly focused on learning time and on-device energy consumption in mobile edge networks. The optimization of learning time was studied in \cite{ chen2020convergence,nguyen2020fast,nishio2019client,shi2020device, wadu2020federated,wang2020optimizing, yang2019scheduling,jiang2020pruning}, and joint optimization for learning time and energy consumption was considered in \cite{mo2020energy,zeng2020energy,yang2019energy,luo2020hfel}. These works considered resource (e.g., transmission power, communication bandwidth, and CPU frequency) allocation (e.g., \cite{ chen2020convergence,nguyen2020fast,mo2020energy,zeng2020energy,yang2019energy,luo2020hfel}), cost-aware client selection (e.g., \cite{nishio2019client, shi2020device}), client scheduling (e.g., \cite{wadu2020federated, wang2020optimizing,yang2019scheduling}), and model pruning\cite{jiang2020pruning} for \emph{pre-specified} (i.e., non-optimized) design parameters ($K$ and $E$ in our case) of the FL algorithm.} The optimization of a single design parameter $E$ was studied in~\cite{wang2019adaptive,wang2018adaptive,han2020adaptive,luping2019cmfl,hsieh2017gaia}, most of which assume full client participation and can be infeasible for large-scale on-device FL. A very recent work in \cite{jin2020resource} considered the optimization of both $E$ and client selection for additive per-client costs. {However, the cost of learning time in our problem is non-additive on a per-client basis, since different clients perform local model updates in parallel. In addition, the convergence bound used in~\cite{jin2020resource} (also~\cite{tran2019federated}) is for a primal-dual optimization algorithm, which is different from the commonly used FedAvg algorithm. The challenge in optimizing both $K$ and $E$ for cost minimization of FedAvg, which also distinguishes our work from the above, is the need \emph{to analytically connect the total cost with the control variables as well as with the convergence rate}.} {The comparison of our work with the above related works is illustrated in Table~\ref{relate_work}, where we note that our optimization design is orthogonal to most works on resource allocation in the last column in Table~\ref{relate_work} and can be used together with those techniques to further reduce the cost.} In addition, most existing work on FL are based on simulations, whereas we implement our algorithm in an actual hardware prototype with resource-constrained devices. \section System Model and Problem Formulation} \label{sec:systemModel} We start by summarizing the basics of FL and its de facto algorithm FedAvg. Then, we introduce the scheduling strategy when applying FL in mobile edge networks with system heterogeneity. Finally, we present the cost optimization problem for FL tasks. We summarize all key notations in this paper in Table~II. \subsection{Federated Learning Consider a scenario with a large number of mobile clients that have data for training a machine learning model. Due to data privacy concern, it is not desirable for clients to disclose and send their raw data to a high-performance data center. FL is a decentralized learning framework that aims to resolve this problem. Mathematically, FL is the following distributed optimization problem: \begin{equation} \label{gl_ob} \min_{\mathbf{w}} F\left( \mathbf{w} \right) :=\sum\nolimits_{k = 1}^N{p_k}{F_k}\left( \mathbf{w} \right) \end{equation} where the objective $F\left( \mathbf{w} \right)$ is also known as the global loss function, $\mathbf{w}$ is the model parameter vector, $N$ is the total number of devices, and $p_k>0$ is the weight of the $k$-th device such that $\sum\nolimits_{k = 1}^N p_k=1$. Suppose the $k$-th device has $n_k$ training data samples ($\mathbf{x}_{k, 1}, \cdots, \mathbf{x}_{k, n_{k}}$), and the total number of training data samples across $N$ devices is $n :=\sum\nolimits_{k \!=\! 1}^N n_k$, then we have $p_k=\frac{n_k}{n}$. The local loss function of client $k$ is \begin{equation} \label{lo_ob} {F_k}\left( \mathbf{w} \right) := \frac{1}{{{n_k}}}\sum\limits_{j =1}^{n_k} {{f}\left( \mathbf{w}; \mathbf{x}_{k,j} \right)}, \end{equation} where $f(\cdot)$ represents a per-sample loss function, e.g., mean square error or cross entropy applied to the output of a model with parameter $\mathbf{w}$ and input data sample $\mathbf{x}_{k,j}$ \cite{wang2019adaptive}. FedAvg (Algorithm~1) was proposed in \cite{mcmahan2017communication} to solve \eqref{gl_ob}. In each \emph{round}~$r$, a subset of randomly selected clients $\mathcal{K}^{r}$ run $E$ steps\footnote{$E$ is originally defined as epochs of SGD in \cite{mcmahan2017communication}. In this paper we denote $E$ as the number of local iterations for theoretical analysis.} of stochastic gradient decent (SGD) on~\eqref{lo_ob} in parallel, {where $\mathcal{K}^{r} \subseteq \{1,2,...,N\}$}. Then, the updated model parameters of these $\left|\mathcal{K}^{r}\right|$ clients are sent to and aggregated by the server. This process repeats for many rounds until the global loss converges. FL has demonstrated its effectiveness in tackling with statistical heterogeneity, e.g., unbalanced and non-i.i.d. data distribution. Meanwhile, applying it in practical mobile edge networks also needs to address clients' computational and communication heterogeneity. Therefore, an efficient FL design requires \emph{joint consideration of statistical and system heterogeneity}. \begin{table}[!t] \label{keynotation} \centering \caption{Summary of all key notations} \begin{tabular}{l|l} \toprule[1pt] $F\left( \mathbf{w} \right)$ & Global loss function \\ ${F_k}\left( \mathbf{w} \right)$ & Local loss function \\ $\mathbf{w}^*$ & Optimal model parameter that minimizes $F\left( \mathbf{w} \right)$\\ $\mathbf{w}_R$ & Final model parameter after $R$ rounds\\ $\epsilon$ & Desired precision with $\mathbb{E}[F(\mathbf{w}_R)]-F^{*} \le \epsilon$\\ $R$ & Final round number for achieving $\epsilon$ \\ $r$ & Round number index \\ $\mathcal{K}^{r}$ & Randomly selected clients in round $r$ \\ $K$ & Number of selected clients with $K\!:=\! \left| \mathcal{K}^{r}\!\right|\!$ \\ $E$ & Number of local iteration steps\\ $T^{r}$ & Round time in round $r$ \\ $e^{r}$ & Energy consumption in round $r$ \\ $t_{k,p}$ & Com\underline{p}utation time of client $k$ for one iteration \\ $e_{k,p}$ & Com\underline{p}utation energy of client $k$ for one iteration\\ $t_{k,m}^{r}$ & Co\underline{m}munication time of client $k$ in round $r$ \\ $e_{k,m}^{r}$ & Co\underline{m}munication energy of client $k$ in round $r$\\ $\overline{t}_{k,m}$ & Expected $t_{k,m}^{r}$ in $R$ round \\ $\overline{e}_{k,m}$ & Expected $e_{k,m}^{r}$ in $R$ round \\ $t_p$ & Expected per-device per-iteration computation time \\ $e_p$ & Expected per-device per-iteration computation energy\\ $t_m$ & Expected per-device per-round communication time \\ $e_m$ & Expected per-device per-round communication energy\\ $T_\textnormal{tot}$ & Total learning time after $R$ rounds \\ $e_\textnormal{tot}$ & Total energy consumption after $R$ rounds\\ $T_k^{r}$ & Time after scheduling client $k$ in round $r$ \\ $C_\textnormal{tot}$ & Balanced total cost \\ $\gamma$ & {Normalized price factor} \\% (one unit time for one unit energy)}\\ $A_0$, $B_0$ & Unknown constants in convergence bound\\ $F_a$, $F_b$ & Pre-defined global loss for estimation $A_0$, $B_0$ \\ $R_a$, $R_b$ & Pre-defined round number for estimation $A_0$, $B_0$ \\ \bottomrule[1pt] \end{tabular}% \label{tabl}% \end{table}% \begin{algorithm}[t] \small \caption{Federated Learning Algorithm} \label{alg:fedavg} \KwIn{$K$, $E$, precision $\epsilon$, initial model $\mathbf{w_0}$, initial round index $r=0$} \KwOut{Final model parameter $\mathbf{w}_R$} \While{$r \le R }{ Server randomly selects a subset of clients $\mathcal{K}^{r}$ and broadcast the current global model parameter $\mathbf{w}_r$ to the selected clients\label{alg:fedavgStep1}\tcp*{Communication} Each selected client $k \in \mathcal{K}^{r} $ in parallel updates $\mathbf{w}_r$ by running $E$ steps of SGD on \eqref{lo_ob} to compute a new model $\mathbf{w}_r^{(k)}$\label{alg:fedavgStep2}\tcp*{Computation} Each selected client $k \in \mathcal{K}^{r}$ sends back the updated model $\mathbf{w}_r^{(k)}$ to the server\label{alg:fedavgStep3}\tcp*{Communication} Server computes the new global model parameter $\mathbf{w}_{r+1} \leftarrow \frac{\sum_{k \in \mathcal{K}^{r}} p_k \mathbf{w}_r^{(k)}}{\sum_{k \in \mathcal{K}^{r}} p_k} $\label{alg:fedavgStep4}\tcp*{Aggregation} $r \leftarrow r+1$; } \end{algorithm} \subsection{Deploying Federated Learning in Mobile Edge Networks} In mobile edge networks, due to system bandwidth limitation and wireless interference, participating clients are usually scheduled in a time-sharing (TS) \cite{tran2019federated,mo2020energy} or frequency-sharing (FS) \cite{shi2020device, chen2020convergence,yang2019energy} protocols.\footnote{{We consider cellular network based one-hop communication between the server and the clients, since its topology is well-aligned with that in mainstream FL community. For FL in a decentralized topology, e.g., in wireless ad-hoc networks, the communications could be multi-hop, which is beyond our focus in this work.} Although leveraging analog aggregation techniques in wireless communications \cite{zhu2019broadband, yang2020federated, amiri2020machine} can increase the communication efficiency, it may require stringent synchronization and additional superposition code design.} {However, the selected heterogeneous clients may have diverse communication and computation capabilities, which results in different per-round training time under different scheduling strategies, especially for clients with dynamic wireless channels.} This is because the per-round time depends on the slowest client (known as straggler), as the server needs to collect all updates from the sampled clients before performing global aggregation. {In this paper, as shown in Fig. 1, we propose a new TS based FL model which works efficiently with heterogeneous computation and communication time. We note that the empirical results in Section~\ref{sec:experimentation} demonstrate that our proposed TS is superior to existing FS schemes in \cite{zhu2019broadband, yang2020federated, amiri2020machine}. {The main reason is that, in those FS schemes, the frequency allocation for the sampled clients in each round is \emph{static}, which causes a waste in bandwidth resources. This is because, due to computational heterogeneity, clients who complete computation early can be allocated with more bandwidth for transmission before the next client completing computation, instead of always sharing the entire bandwidth static with other slower clients.}} In the following, we first describe our system model and then present the proposed TS protocol. \subsubsection{\textbf{System Model}} Similar to existing works \cite{mcmahan2017communication, li2019convergence, li2018federated}, we sample $K$ clients in each round $r$ (i.e., $K := \left| \mathcal{K}^{r} \right|,{ 1\le K \le N}$), where the sampling is uniform at random (without replacement) out of all $N$ clients. Similar to existing studies on wireless FL (e.g., \cite{ shi2020device, chen2020convergence,yang2019energy}), we assume that a particular device has the same com{p}utation cost (time and energy) over multiple rounds, whereas the communication cost varies between rounds due to wireless dynamics. We do not consider the server's downlink cost for model broadcasting and model aggregation, as we mainly focus on the performance bottleneck of the battery-constrained edge devices \subsubsection{\textbf{Proposed Time-sharing Protocol}} Consider a general round $r$, where the server (co-located with the base station) first broadcasts the current global model to the randomly selected $\mathcal{K}^{r}$ clients. Then, each of the selected clients performs $E$ steps of local iterations \emph{in parallel}, where we denote $t_{k,p}$ as the com\underline{p}utation time for client $k$ to perform one local iteration. In the communication phase, however, the selected clients \emph{sequentially} upload their model to the server in different time slots, where we denote $t_{k,m}^{r}$ as the co\underline{m}munication time for client $k$ to upload the model parameter in round $r$.\footnote{We note that $t_{k,m}^{r}$ can be calculated by $t_{k,m}^{r}=\left.{\Omega} \middle/ {B\log \left( {1 + \frac{p_k\bar{h}_k^{r}}{N_0}}\right)}\right.$, where $\Omega$ is the size of model parameter, $B$ is the bandwidth, $p_k$ is the transmission power (we do not consider power control in this work, though it can be incorporated in future work), $\bar{h}_k^{r}$ is the average channel gain of the client $k$ during the FL training time in round $r$ and $N_0$ is the white noise power.} Due to the difference between $t_{k,p}$ and $t_{k,m}^{r}$ among the selected $K$ clients in $\mathcal{K}^{r}$, the time of round $r$ depends on the \emph{scheduling order} of the $K$ clients. We present the optimal TS scheduling with the following theorem, which achieves the minimum time for a particular round $r$ with the selected clients $\mathcal{K}^{r}$. {We note that the proposed scheduling scheme mainly considers the total learning time for the sampled clients rather than their energy consumption. This is because the total energy consumption is the sum of all sampled clients' energy cost, which is independent of the scheduling order of the $K$ clients.} \newtheorem{theorem}{\textbf{Theorem}} \begin{theorem} \label{theorem1} \textbf{(Optimal time-sharing scheduling)} For any sampled clients set $\mathcal{K}^{r}$ in round $r$, without loss of generality, we assume that $\mathcal{K}^{r}$ is ordered based on $\{t_{k,p}: \forall k \in \mathcal{K}^{r}\}$, such that $t_{1,p}\le \ldots \le t_{k,p}\le \ldots \le t_{K,p}$. Then, sequentially scheduling the ordered $K$ clients yields the minimum time of round $r$, compared to any other scheduling sequence. Under this scheduling sequence, denoting $T_k^{r}$ as the time after scheduling client $k$, we have \begin{equation} \label{tdd} T_k^{r}=\max \left\{ {{t_{k,p}E}, {T_{k-1}^{r}}} \right\} + {t_{k,m}^{r}},\ k\in \left\{ {1, \ldots K} \right\}, \end{equation} where $T_K^{r}$ is the entire time of round $r$ after scheduling all $K$ clients, and we define $T_0^{r}:=0$ and $T^{r} := T_K^{r}$ for convenience. \end{theorem} We give the proof in Appendix \ref{theorem1app}. Compared to existing TS scheduling strategy in \cite{tran2019federated} where communication from the clients to the server will not begin until all sampled clients complete local iterations, the scheduling policy specified in Theorem~\ref{theorem1} enables each client to upload its result to the server as soon as it finishes the computation when the wireless channel is available, which potentially reduces system waiting time and thus the round time $T^{r}$. The \emph{max} function in \eqref{tdd} characterizes whether the channel is vacant when a certain client completes its local iteration, e.g., the red shadow time slots in Fig.~1. \subsection{Cost Analysis of Federated Learning in Mobile Edge Networks} Despite the effectiveness and efficiency of FL, practitioners need to take into account the cost of completing FL tasks. The total cost of FL, according to Fig.~1, involves \emph{learning time} and \emph{energy consumption}, both of which are consumed during local computation and global communication in each round. \subsubsection{\textbf{Time Cost}} Based on the optimal TS scheduling in Theorem \ref{theorem1}, the per-round time after scheduling the selected $K$ clients is $T^{r}$, which depends on the number of sampled clients $K$ and the number of location computation steps $E$. The total learning time $T_\textnormal{tot}$ after $R$ rounds is \begin{equation} \label{Ttot} T_\textnormal{tot}(K,E,R)=\sum\nolimits_{r=1}^{R}T^{r} \end{equation} \subsubsection{\textbf{Energy Cost}} Similar to the notation for time cost, by denoting $e_k$ as the per-round energy consumption for client $k$ to complete the computation and communication, we have \begin{equation} \label{energyk} e_{k}^{r}=e_{k,p} E+ e_{k,m}^{r}, \end{equation} where $e_{k,p}$ is the com\underline{p}utation energy for client $k$ to perform one step local iteration in each round, and $e_{k,m}^{r}$ is client $k$'s com\underline{m}unication energy in round $r$ due to wireless dynamics. Unlike the per-round time cost, the energy cost $e^{r}$ in each round $r$ depends on the \emph{sum} energy consumption of the selected $K$ clients. Therefore, the total energy cost $e_\textnormal{tot}$ after $R$ rounds can be expressed as \begin{equation} \label{etot} e_\textnormal{tot}(K,E,R)=\sum\nolimits_{r=1}^{R}\sum\nolimits_{k \in \mathcal{K}^{r}}e_{k}^{r} \end{equation} \subsection{Problem Formulation} Considering the difference of the two cost metrics, the optimal solutions of $K$, $E$ and $R$ generally do not achieve the common goal for minimizing both $T_\textnormal{tot}$ and $e_\textnormal{tot}$. To strike the balance between learning time and energy consumption, we introduce a weight $\gamma \in \left[0, 1\right]$ and optimize the balanced cost function in the following form: \begin{equation} \label{homocost} C_\textnormal{tot}(K,E,R)= \gamma e_\textnormal{tot}(K,E,R)+\left(1-\gamma\right) T_\textnormal{tot}(K,E,R), \end{equation} {where $1-\gamma$ and $\gamma$ can be interpreted as the \emph{normalized price} of the two costs, i.e., how much monetary cost for one unit of time and one unit of energy, respectively. The value of $\gamma$ can be adjusted for different preferences.} For example, we can set $\gamma=0$ when all clients are plugged in and energy consumption is not a major concern, whereas $\gamma=1$ when devices are solar-based sensors where saving the devices' energy is the priority. Our goal is to minimize the {expected} total cost while ensuring convergence, which translates into this problem: \begin{equation}\begin{array}{cl} \label{ob1} \!\!\!\!\!\!\!\!\textbf{P1:}\quad\quad \min_{E, K, R} & \mathbb{E}[C_\textnormal{tot}(E,K,R)] \\ \quad\quad \text { s.t. } & \mathbb{E}[F(\mathbf{w}_R)]-F^{*} \le \epsilon,\\ & K,E,R \in \mathbb{Z}^{+}, \ \text{and}\ \ 1 \le K \le N. \end{array}\end{equation} {where $\mathbb{E}[F(\mathbf{w}_R)]$ is the expected loss after $R$ rounds, $F^*$ is the (true and unknown) minimum value of $F$, and $\epsilon$ is the desired precision. {We note that the expectation in Problem \textbf{P1} takes over three source of randomness, where the first two randomness come from the client sampling and data sampling in SGD in each round, and the third randomness comes from the varying communication cost in each round due to dynamic wireless channel conditions.} {Solving Problem \textbf{P1} is challenging in two aspects. First, it is difficult to find an \emph{exact analytical expression} to relate $K$, $E$ and $R$ with $C_\textnormal{tot}$, especially due to the \emph maximum} function in $T_\textnormal{tot}$. Second, it is generally impossible to obtain an exact analytical relationship to connect $K$, $E$ and $R$ with the convergence constraint. In the following section, we propose an algorithm that approximately solves Problem \textbf{P1}, which we later show with extensive experiments that the proposed solution can achieve a near-optimal performance of Problem \textbf{P1}.} \section{Cost-Effective Optimization Algorithm} \label{sec:optimizationProblem} This section shows how to approximately solve Problem \textbf{P1}. {We first formulate an alternative problem that includes an approximate analytical relationship between the expected cost $\mathbb{E}[C_\textnormal{tot}]$, the convergence constraint, and the control variables $E$, $K$ and $R$. Then, we show that this new optimization problem can be efficiently solved after estimating unknown parameters associated with the convergence bound, and we propose a sampling-based algorithm to learn these unknown parameters. \subsection{Approximate Solution to Problem \textbf{P1}} \subsubsection{\textbf{Analytical Expression of} $\mathbb{E}[e_\textnormal{tot}]$} We first analytically establish the expected energy cost $\mathbb{E}[e_\textnormal{tot}]$ with $K$ and $E$. \newtheorem{lemma}{{Lemma}} \begin{lemma} \label{lemma:expect_e_tot} The expectation of $e_\textnormal{tot}$ in \eqref{etot} can be expressed as \begin{equation} \label{het_energy} \mathbb{E}[e_\textnormal{tot}(K,E,R)]= K\left(e_{p}E+ e_{m}\right)R, \end{equation} where $e_p\!:=\!\frac{\sum_{k=1}^{N} e_{k,p}}{N}$ and $e_m\!:=\!\frac{\sum_{k=1}^{N}\sum_{r=1}^{R}{e}_{k,m}^{r}}{NR}$ denote the average per-device energy consumption for one local iteration and one round of communication, respectively \end{lemma} \begin{proof} Given that all devices are sampled uniformly at random in each round and each round $K$ out of $N$ clients are sampled, thus for $R$ rounds, each device will be sampled in $\frac{KR}{N}$ rounds in expectation. Based on the result in \eqref{energyk} that each device $k$ consumes $e_{k,p} E+ {e}_{k,m}^{r}$ energy in each round, summing up $e_{k,p} E+ {e}_{k,m}^{r}$ over all $N$ clients and over $\frac{KR}{N}$ rounds lead to \eqref{het_energy}. \end{proof} \subsubsection{\textbf{Analytical Expression of} $\mathbb{E}[T_\textnormal{tot}]$} {Next, we give an approximate expression of the expected time cost $\mathbb{E}[T_\textnormal{tot}]$ with $K$ and $E$. {In the following, we first show how to approximate the per-round time $T^r$ in \eqref{tdd}, based on which we formulate a combinatorial expression of expected $T_\textnormal{tot}$ in \eqref{Ttot}. Then, we further approximate the expectation of $T_\textnormal{tot}$ for analytical tractability.}} {Considering that the communication time is usually the bottleneck in wireless FL settings, it is most likely that the maximum in \eqref{tdd} is equal to $T_{k-1}^{r}$ for any $k \in \{2, \ldots, K\} $, e.g., the red shadow time slot in Fig.~\ref{fig:intro} rarely happens. In other words, the communication channel will be usually occupied after the fastest client (e.g., $k=1$ in the $K$ clients reordered as in Theorem~\ref{theorem1}) finishes computation. Therefore, $T^{r}$ in \eqref{tdd} can be approximated by \begin{equation} \label{app_tr_wireless} T^{r}\appro {t_{1,p}}E+\sum_{k=1}^K{t_{k,m}^{r}}. \end{equation}} Note that the ordering of $\{t_{k,p}: \forall k \in \mathcal{K}^{r}\}$ varies across different rounds due to random sampling, i.e., the client with index $k=1$ may be different in different rounds. With a slight abuse of notation, we use $t_{i,p}$ to denote the $i$-th fastest client (in terms of computation) out of all $N$ clients (i.e., before sampling), such that \begin{equation} \label{reorder}t_{1,p} \leq t_{2,p} \leq \ldots \leq t_{i,p} \leq \ldots \leq t_{N,p}. \end{equation} \begin{lemma} \label{lemma:expect_t_tot} With the reordered clients as in \eqref{reorder} and the approximate $T^{r}$ as in \eqref{app_tr_wireless}, the expectation of $T_\textnormal{tot}$ in \eqref{Ttot} can be expressed as\footnote{The notation of $C_{N}^{K}$ is also noted as $\binom{N}{K}$ which represents the combination number of choosing $K$ out of $N$ without replacement.} \begin{equation} \label{avgtime} \mathbb{E}[T_\textnormal{tot}(K,E,R)]\approx\left(\frac{\sum\nolimits_{i=1}^{N-i+1}{C_{N-i}^{i-1}}t_{i,p} }{C_{N}^{K}} +t_mK\right)R, \end{equation} where $t_m:=\frac{\sum_{i=1}^{N}\sum_{r=1}^{R}{t}_{i,m}^r}{NR}$ is the average per-device time cost for one round of communication. \end{lemma} We give the full proof in Appendix \ref{lemma2app}. The basic idea is to show the expectation of $T^{r}$ in \eqref{app_tr_wireless} is $\mathbb{E}[T^{r}] \approx \frac{\sum\nolimits_{i=1}^{N-K+1}{C_{N-i}^{K-1}}t_{i,p} }{C_{N}^{K}}E+t_mK,$ where $\frac{\sum\nolimits_{i=1}^{N-K+1}{C_{N-i}^{K-1}}t_{i,p} }{C_{N}^{K}}E$ represents that the probability of client $i$ being the first scheduling client is $\frac{{C_{N-i}^{K-1}}}{C_{N}^{K}}$, and the second term $t_mK$ is derived similar to $e_m$ in \emph{Lemma} 1. In particular, the multiplication of $K$ in $t_mK$ characterizes the scheduling property of wireless communications with limited bandwidth. However, $\mathbb{E}[T_\textnormal{tot}]$ in \eqref{avgtime} is still hard to analyze due to the various combinatorial terms with respect to control variable $K$. For analytical tractability, similar to how we derive \eqref{het_energy}, we define an approximation of $\mathbb{E}[T_\textnormal{tot}]$ as \begin{equation} \label{appro_t_tot} \tilde{\mathbb{E}}[T_\textnormal{tot}(K,E,R)] :=\left(t_pE+t_mK\right)R \end{equation} where $t_p:=\frac{\sum_{i=1}^{N} t_{i,p}}{N}$ is the average per-device time cost for one local iteration. The approximation $\tilde{\mathbb{E}}[T_\textnormal{tot}]$ in \eqref{appro_t_tot} is equivalent to $\mathbb{E}[T_\textnormal{tot}]$ in \eqref{avgtime} in the following two cases. \noindent\emph{Case 1}: For clients with homogeneous computation capabilities, e.g., $t_{p}=t_{i,p}$, $\forall i \in \{1, \ldots, N\}$, along with the recursive property of $C_{m}^{n}\!+C_{m}^{n-1}\!=\!C_{m+1}^{n}$, we have \begin{equation} \notag \label{avgtimehomo} \begin{array}{cl} \mathbb{E}[{T_\textnormal{tot}}(K,E,R)]&=\left(t_pE\frac{\sum\nolimits_{i=1}^{N-K+1}{C_{N-i}^{K-1}}}{C_{N}^{K}}+t_mK\right R\\ &=\left(t_p E+t_mK\right)R\\ &=\tilde{\mathbb{E}}[T_\textnormal{tot}(K,E,R)]. \end{array} \end{equation} \noindent\emph{Case 2}: For clients with heterogeneous computation capabilities with $K=1$, we have \begin{equation} \notag \label{avgtimek=1} \begin{array}{cl} \mathbb{E}[{T_\textnormal{tot}}(K=1,E,R)]&=\left(\frac{\sum\nolimits_{i=1}^{N}{t_{i,p}E}}{N}+t_mK\right)R\\ &=\left(t_p E+t_mK\right) R\\ &=\tilde{\mathbb{E}}[T_\textnormal{tot}(K=1,E,R)]. \end{array} \end{equation} {In the following cost analysis, we use $\tilde{\mathbb{E}}[T_\textnormal{tot}(K,E,R)]$ in \eqref{appro_t_tot} as the approximate expected value of the original total learning time in \eqref{Ttot}.} \subsubsection{\textbf{Analytical Relationship Between $\mathbb{E}[C_\textnormal{tot}]$ and Convergence}} Based on $\mathbb{E}[e_\textnormal{tot}]$ in \eqref{het_energy} and the approximation $\tilde{\mathbb{E}}[T_\textnormal{tot}(K,E,R)]$ in \eqref{appro_t_tot}, we formulate an approximate objective function of Problem \textbf{P1} as \begin{equation} \label{obj_fun} \tilde{\mathbb{E}}[C_\textnormal{tot}]= \left(\gamma K\left( e_pE+ e_m\right)+\left(1-\gamma\right)\left(t_pE+t_mK\right)\right)R \end{equation} {To connect $\tilde{\mathbb{E}}[C_\textnormal{tot}]$ with the $\epsilon$-convergence constraint in \eqref{ob1} as well as to characterize the heterogeneous data, we utilize the convergence result \cite{li2019convergence}}\footnote{{We use the convergence result in \cite{li2019convergence} because both \cite{li2019convergence} and our work analyze the FedAvg algorithm, and the convergence result in \cite{li2019convergence} includes both control variables $E$ and $K$ for cost minimization. We also note that the convergence result in \cite{li2019convergence} requires clients to decay the learning rate throughout the training process, which we show later in Section VI.}}: \begin{equation} \label{upperbound1} \mathbb{E}[F(\mathbf{w}_R)]\!-\!F^{*}\le \frac{1}{ER}\left(A_0+B_0\left(1+ \frac{N-K}{K(N\!-\!1)}\right) E^2\right), \end{equation} where $A_0$ and $B_0$ are loss function related constants characterizing the statistical heterogeneity of non-i.i.d. data. By letting the upper bound satisfy the convergence constraint,\footnote{We note that optimization using upper bound as an approximation has also been adopted in \cite{wang2019adaptive} and resource allocation based literature \cite{tran2019federated, chen2020convergence,yang2019energy}.} we approximate Problem \textbf{P1} as \begin{equation}\begin{array}{cl} \label{ob2} \!\!\!\!\!\!\textbf{P2:} \ \min_{E, K, R} & \!\!\! \left(\gamma K\left( e_pE+ e_m\right)+\left(1\!-\!\gamma\right)\left(t_pE+t_mK\right)\right)R \\ \quad \text { s.t. } &\!\!\! \frac{1}{ER}\left(A_0+B_0\left(1+ \frac{N-K}{K(N-1)}\right) E^2\right) \le \epsilon\\%,\\ & K,E,R \in \mathbb{Z}^{+}, \ \text{and}\ \ 1 \le K \le N. \end{array}\end{equation} Combining with \eqref{upperbound1}, we can see that Problem \textbf{P2} is more constrained than Problem \textbf{P1}, as any feasible solution of \textbf{P2} is also feasible for \textbf{P1}, but not vice versa. Problem \textbf{P2}, however, is a non-linear constrained \emph{integer} optimization problem, which is still difficult to solve in general. Therefore, we relax $K$, $E$ and $R$ as continuous variables for theoretical analysis, which are rounded back to integer variables\footnote{{For two integer variables we have four rounding combinations of $\left(\left \lceil{K}\right \rceil, \left \lceil{E}\right \rceil \right)$, $\left(\left \lceil{K}\right \rceil, \left \lfloor{E}\right \rfloor \right)$, $\left(\left \lfloor{K}\right \rfloor, \left \lceil{E}\right \rceil \right)$, and $\left(\left \lfloor{K}\right \rfloor, \left \lfloor{E}\right \rfloor \right)$.}} later. For the relaxed problem, if any feasible solution $E^\prime, K^\prime$, and $R^\prime$ satisfies the $\epsilon$-constraint in Problem \textbf{P2} with inequality, we can always decrease this $R^\prime$ to some $R^{\prime\prime}$ ($R^{\prime\prime} < R^\prime$), which satisfies the constraint with equality but reduces the objective function value. Hence, for optimal $R$, the $\epsilon$-constraint is always satisfied with equality, and we can obtain $R$ from this equality as \begin{equation} R = \frac{1}{\epsilon E}\left(A_0+B_0\left(1+ \frac{N-K}{K(N-1)}\right) E^2\right). \label{eq:R_solution} \end{equation} By substituting \eqref{eq:R_solution} into problem \textbf{P2}, we obtain \begin{equation} \label{ob3} \begin{array}{cl} \!\!\!\textbf{P3:} \ \min_{E, K} & \!\!\!\!\!\left(\left(1\!-\!\gamma\right)\left(t_pE+\!t_mK\right)\!+\!\gamma K \left(e_p E\!+\!e_m\right)\right) \\&\cdot \frac{\left(\!A_0+B_0\left(\! 1+ \frac{N-K}{K(N-1)}\!\right) E^2\right)}{\epsilon E} \\ \!\!\!\!\!\quad\text {s.t.} & \!\!\! {E}\ge 1, \ \text{and}\ \ 1 \le K \le N, \end{array} \end{equation} In the following, we solve Problem \textbf{P3} as an approximation of the original problem \textbf{P1}. Our empirical results in Section~\ref{sec:experimentation} demonstrate that the solution obtained from solving \textbf{P3} achieves \emph{near-optimal performance} of the original problem \textbf{P1}. For ease of analysis, we incorporate $\epsilon$ in the constants $A_0$ and $B_0$. \subsection{Solving the Approximate Optimization Problem \textbf{P3}} In this subsection, we first characterize some properties of the optimization problem \textbf{P3}. Then, we propose a sampling-based algorithm to learn the problem-related unknown parameters $A_0$ and $B_0$, based on which the solution $K^*$ and $E^*$ (of Problem \textbf{P3}) can be efficiently computed. The overall algorithm for obtaining $K^*$ and $E^*$ is given in Algorithm~\ref{alg:optimalSolution}. \begin{algorithm}[t] \small \caption{Cost-effective design of $K$ and $E$} \label{alg:optimalSolution} \KwIn{{$N$, $\gamma$, $t_p$, $t_m$, $e_p$, $e_m$, {loss $F_a$ and $F_b$, $\mathbf{w}_0$, number of sampled pairs $M$}}, stopping condition $\epsilon_0$} \KwOut{{$K^*$ and $E^*$}} \For{$i=1,2, \ldots, M$ \label{alg:optimalSolution:startEstimation}}{ Empirically choose $(K_i$, $E_i)$ and run Algorithm~1; Record $R_{i,a}$ and $R_{i,b}$ when $F_a$ and $F_b$ are reached; } Calculate average $\frac{A_0}{B_0}$ using \eqref{A0B05}; \label{alg:optimalSolution:endEstimation} Choose a feasible $z_0 \leftarrow \left(K_0, E_0\right)$ and set $j \leftarrow 0$; \label{alg:optimalSolution:startOptimization} \While{$\Vert z_{j} - z_{j-1}\Vert > \epsilon_0$}{ Substitute $E_{j}$, $\frac{A_0}{B_0}$, $N$, $\gamma$, $t_p$, $t_m$, $e_p$, $e_m$ into \eqref{ob3} and derive $K^\prime$; $K_{j+1} \leftarrow \arg\min_{K \in [1, N]} |K - K'|$; \label{alg:optimalSolution:projectionK} Substitute $K_{j+1}$, $\frac{A_0}{B_0}$, $N$, $\gamma$, $t_p$, $t_m$, $e_p$, $e_m$ into \eqref{ob3} and derive $E^\prime$; $E_{j+1} \leftarrow \arg\min_{E \geq 1} |E - E'|$; \label{alg:optimalSolution:projectionE} $z_{j+1} \leftarrow \left(K_{j+1}, E_{j+1}\right)$ and $j \leftarrow j+1$; } Substitute four rounding combinations of $\left(\left \lceil{K_j}\right \rceil, \left \lceil{E_j}\right \rceil \right)$, $\left(\left \lceil{K_j}\right \rceil, \left \lfloor{E_j}\right \rfloor \right)$, $\left(\left \lfloor{K_j}\right \rfloor, \left \lceil{E_j}\right \rceil \right)$, and $\left(\left \lfloor{K_j}\right \rfloor, \left \lfloor{E_j}\right \rfloor \right)$ into the objective function of problem \textbf{P3}, and set the pair with the minimum value as $\left(K^*, E^*\right)$ \label{alg:optimalSolution:rounding} \Return $\left(K^*, E^*\right) \label{alg:optimalSolution:endOptimization} \end{algorithm} \subsubsection{\textbf{Characterizing Problem \textbf{P3}}} \begin{theorem} \label{theorem:biconvex} Problem \textbf{P3} is strictly biconvex \cite{gorski2007biconvex}. \end{theorem} \begin{proof} For any $E \ge 1$, we have {\small \begin{equation*} \dfrac{\partial^2 \tilde{\mathbb{E}}[C_\textnormal{tot}]}{\partial^2 K}=\dfrac{2(1-\gamma)B_{0} Nt_{p} E^{2}}{(N-1) K^{3}}>0.\end{equation*} } Similarly, for any $1\le K \le N$, we have {\small \begin{equation} \begin{array}{cl} \dfrac{\partial^2 \tilde{\mathbb{E}}[C_\textnormal{tot}]}{\partial^2 E}=2 \left( \left(1-\gamma\right)t_p+\gamma K e_p\right) B_{0}\left(1+\frac{N-K}{K(N-1)}\right) \\\qquad + \dfrac{2A_{0}\left( (1-\gamma)Kt_m+\gamma Ke_m\right) }{E^{3}}>0 \end{array} \end{equation}}% Since the domain of $K$ and $E$ is convex, we conclude that Problem \textbf{P3} is strictly biconvex. \end{proof} The biconvex property allows many efficient algorithms, such as \emph{Alternate Convex Search} (ACS) approach, to a achieve a guaranteed local optima\cite{gorski2007biconvex}. E.g., we could iteratively solve $K$ and $E$ in the objective function \eqref{ob3} until we achieve the converged $K^\ast$ and $E^\ast$. This optimization process corresponds to Lines~\ref{alg:optimalSolution:startOptimization}--\ref{alg:optimalSolution:endOptimization} of Algorithm~\ref{alg:optimalSolution}, where Lines~\ref{alg:optimalSolution:projectionK} and \ref{alg:optimalSolution:projectionE} ensure that the solution is taken within the feasibility region, and Line~\ref{alg:optimalSolution:rounding} rounds the continuous values of $K$ and $E$ to integer values. \subsubsection{\textbf{Estimation of Parameters $\frac{A_0}{B_0}$}} Solving the objective function \eqref{ob3} is still nontrivial because it includes unknown parameters $A_0$ and $B_0$, which can only be determined during the learning process.\footnote{We assume that $t_p$, $t_m$, $t_m$ and $e_m$ can be measured offline.} In fact, the optimal $K$ and $E$ in \eqref{ob3} only depend on the value of $\frac{A_0}{B_0}$ as we could divide $B_0$ and incorporate it in $\epsilon$. In the following, we propose a sampling-based algorithm to estimate $\frac{A_0}{B_0}$, and show that the overhead for estimation is marginal. The basic idea is to sample different combinations of $\left(K, E\right)$ and use the upper bound in \eqref{upperbound1} to approximate $F(\mathbf{w}_R)\!-\!F^{*}$. {Specifically, we empirically sample\footnote{{Our sampling criteria is to cover diverse combinations of $\left(K,E\right)$.}}} a pair $\left(K_i, E_i\right)$ and run Algorithm~1 with an initial model $\mathbf{w}_0\!=\!\mathbf{0}$ until it reaches two pre-defined global losses $F_a := F(\mathbf{w}_{R_{i,a}})$ and $F_b := F(\mathbf{w}_{R_{i,b}})$ ($F_b<F_a$), where $R_{i,a}$ and ${R_{i,b}}$ are the executed round numbers for reaching losses $F_a$ and $F_b$. The pre-defined losses $F_a$ and $F_b$ can be set to a relatively high value, to keep a small estimation overhead, but they cannot be too high either as it would cause low estimation accuracy. Then, we hav \begin{equation} \begin{cases} \label{A0B01} R_{i,a} \approx d + \dfrac{A_0 + B_0\left(1+ \frac{N-K_i}{K_i(N-1)}\right) E_i^2}{E_i\left(F_a-F^{*}\right)},\\ {R_{i,b}} \approx d + \dfrac{A_0 + B_0\left(1+ \frac{N-K_i}{K_i(N-1)}\right) E_i^2}{E_i\left(F_b-F^{*}\right)}. \end{cases} \end{equation} from \eqref{upperbound1}, where $d$ captures a constant error of using the upper bound to approximate $F(\mathbf{w}_R)\!-\!F^{*}$. Based on \eqref{A0B01}, we have \begin{equation} \label{A0B03} {R_{i,b}}-R_{i,a} \approx \frac{\Delta}{E_i} \left( {A_0\! +\! B_0\left(1\!+\! \frac{N-K_i}{K_i(N\!-\!1)}\right)\! E_i^2}\right), \end{equation} where $\Delta :=\frac{1}{F_b\!-\!F^{*}}\!-\!\frac{1}{F_a\!-\!F^{*}}$. Similarly, sampling another pair of ($K_j$, $E_j$) and performing the above process gives us another executed round numbers $R_{j,a}$ and $R_{j,b}$. Thus, we have \begin{equation} \label{A0B05} \frac{E_i\left(R_{i,b} -R_{i,a}\right)}{E_j\left(R_{j,b}-R_{j,a}\right)} \approx \frac{ {A_0 + B_0\left(1+ \frac{N-K_i}{K_i(N-1)}\right) E_i^2}}{{A_0 + B_0\left(1+ \frac{N-K_j}{K_j(N-1)}\right) E_j^2}}. \end{equation} We can obtain $\frac{A_0}{B_0}$ from \eqref{A0B05} (note that the variables except for $\frac{A_0}{B_0}$ are known). In practice, we may sample several different pairs of $\left(K_i, E_i\right)$ to obtain an averaged estimation of $\frac{A_0}{B_0}$. This estimation process is given in Lines~\ref{alg:optimalSolution:startEstimation}--\ref{alg:optimalSolution:endEstimation} of Algorithm~\ref{alg:optimalSolution}. \textbf{Estimation overhead}: {The main overhead used for estimation $\frac{A_0}{B_0}$ comes from the additional iterations with different sampling pairs ($K_i$, $E_i$). For each pair, $K_i$ clients conduct $R_{i,b}$ rounds of $E_i$ step local iterations for reaching the lower pre-defined loss $F_b$. Hence, for $M$ sampling pairs, the number of iteration $I_{est}$ used for estimation is \begin{equation} I_{est}=\sum_{i=1}^MK_iE_iR_{i,b}. \end{equation} For training with obtained ($K^*$, $E^*$), then according to (15), the total iteration number $I_{tot}$ that used for reaching for reaching $\epsilon=F_R-F^{*}$ precision is \begin{equation} I_{tot}=K^*E^*R\approx \frac{K^*\left[{A_0 + B_0\left(1+\frac{N-K^\ast}{K^\ast(N-1)}\right) ({E^\ast})^2}\right]}{\epsilon}. \end{equation} Therefore, the estimation overhead ratio can be expressed as \begin{equation} \label{overhead}\frac{I_{est}}{I_{tot}}\approx \epsilon \cdot \frac{ \sum_{i=1}^MK_iE_iR_{i,b}}{K^*\left[{A_0 + B_0\left(1+\frac{N-K^\ast}{K^\ast(N-1)}\right) ({E^\ast})^2}\right]}, \end{equation} where the right hand side of \eqref{overhead} except for $\epsilon$ is bounded by some constant value, and thus the overhead ratio will be marginal for a high error precision with $\epsilon$ being small.} \section{Design Principles and Solution Properties for Cost Minimization} \label{sec:property} We theoretically analyze the solution properties for different optimization metrics and heterogeneous system parameters. The analysis not only provides insightful design principles but also gives alternative ways of solving Problem \textbf{P3} more efficiently. Our empirical results in Section~\ref{sec:experimentation} show that these properties derived for Problem \textbf{P3} \emph{are still valid for the original} problem \textbf{P1}. For the ease of presentation, we consider continuous $K$ and $E$ (i.e., before rounding) in this section. \subsection{Solution Property of $K$ for Minimizing $\tilde{\mathbb{E}}[C_\textnormal{tot}]$} We first show how the normalized price factor $\gamma$ affects the optimal solution of $K$. This provides useful design principles for choosing the number of participants for different optimization metrics, e.g., learning time or energy minimization. \begin{theorem} \label{theorem:t_tot} For any fixed value of $E$, $K^{\ast}$ decreases in $\gamma$. In particular, when $\gamma=1$, $\tilde{\mathbb{E}}[C_\textnormal{tot}]$ is a strictly increasing function in $K$, thus $K^\ast=1$. \end{theorem} The proof is given in Appendix~\ref{theorem3app}. Theorem \ref{theorem:t_tot} shows that sampling fewer devices can reduce the total energy consumption for reaching the target loss (which would be the main objective as $\gamma$ becomes large). {While this may seem contradictory at the first glance, since a smaller $K$ would result in more rounds to achieve the desired precision $\epsilon$. The key intuition is that the total energy is the sum energy consumption of all selected clients. Although more rounds may cost longer learning time, there are also less number of clients participating in each round, so the total energy consumption can be smaller.} {Particularly, for pure energy minimization task ($\gamma=1$) with $K^*=1$, our proposed sequential ordering scheduling in Theorem~1 reduces to uniformly at random sample one client for transmission in each round, which is a bit different compared to the Round-Robin scheme, because the sequence of our selected clients over several rounds is random not always following the same order.} Based on Theorem \ref{theorem:t_tot}, we derive a trade-off design principle for $K$, generally, with a relatively larger\footnote{We note that the main difference for reducing time cost between this work and wired FL in \cite{luo2020cost} is that the optimal $K^\ast$ (for $\gamma=0$) in \cite{luo2020cost} is always $N$, where it is usually some value between $[1,N]$ in this paper. } $K$ favoring learning time reduction (small $\gamma$) and a smaller $K$ favoring energy saving (large $\gamma$). For a given $\gamma$, the optimal $K^{\ast}$ achieves the best balance between learning time minimization and energy consumption minimization. Next, we show how heterogeneous system parameters in terms of computation and communication affect the optimal solution of $K$. This shows which directions $K$ and $E$ should change to, when the system environment changes. \begin{theorem} \label{corollary:t_tot_K} For any fixed value of $E$, when $0<\gamma<1$, $K^\ast$ increases in $t_p$ and decreases in $t_m$, $e_p$ and $e_m$. When $\gamma=0$, $K^\ast$ increases with $\frac{t_p}{t_m}$; whereas when $\gamma=1$, $K^{\ast}$ is independent of $e_m$ and $e_p$. \end{theorem} We give the proof in Appendix~\ref{theorem4app}. Intuitively, for general $0\le\gamma<1$, Theorem~\ref{corollary:t_tot_K} says that when $t_m$ increases (e.g., more clients suffering poor channel conditions or less system bandwidth is available), or $e_m$ and $e_p$ increases (higher average energy costs in communication or computation), the optimal strategy to reduce the total cost is to sample fewer clients. Interestingly, when the average computation time $t_p$ increases, we should sample more clients. This is because, unlike the per-round communication time accumulated with more clients being sampled, the computation is performed in parallel among the sampled clients, which only slightly increases the per-round time. Sampling more clients can possibly reduce the required total number of rounds, thus bringing down the total learning time. When we only focus on energy minimization ($\gamma=1$), the optimal $K$ is independent of $e_m$ and $e_p$, because Theorem \ref{theorem:t_tot} shows that $K^\ast=1$ in this case. \subsection{Solution Property of $E$ for Minimizing $\tilde{\mathbb{E}}[C_\textnormal{tot}]$} We first identify how the normalized price factor $\gamma$ affects the choice of $E$ for different optimization goals, e.g., learning time or energy minimization. \begin{theorem} \label{corollary:t_tot_E1} For any $0\le\gamma \le1$ and any fixed value of $K$, as $E$ increases, $\tilde{\mathbb{E}}[C_\textnormal{tot}]$ first decreases and then increases. \end{theorem} The proof is given in Appendix~\ref{theorem5app}. Theorem~\ref{corollary:t_tot_E1} shows that, unlike the strategy for minimizing energy consumption where $K^\ast$ lies at the boundary, the optimal $E$ should not be set too small nor too large no matter for saving energy consumption or learning time. Then, the following theorem characterizes how heterogeneous system parameters in computation and communication affect the design principle of optimal $E$. \begin{theorem} \label{corollary:t_tot_E2} For any fixed value of $E$, when $0<\gamma<1$, $E^\ast$ increases as $t_p$ or $e_p$ decreases. $E^*$ increases in $\frac{t_m}{t_p}$ when $\gamma=0$, and $E^*$ increases in $\frac{e_m}{e_p}$ when $\gamma=1$. \end{theorem} We give the proof in Appendix~\ref{theorem6app}. Theorem~\ref{corollary:t_tot_E2} says that for any given $K$, when or $t_p$ or $e_p$ decreases, the optimal strategy for learning time minimization ($\gamma=0$) or energy consumption minimization ($\gamma=1$) is to perform more steps of iterations (i.e., increase $E$) before aggregation. {This is because when computation is cheaper or when communication is more expensive, it is beneficial to perform more computation in each round, as intuition suggests. This theorem provides theoretical evidence for the empirical observations in \cite{mcmahan2017communication, yu2018parallel, stich2018local,wang2018adaptive}.} \begin{figure}[!t] \centering \includegraphics[width=8.5cm,height=5.2cm]{hd_new.jpg} \caption{Hardware prototype with the laptop being central server, 20 Raspberry Pi and 10 Jetson Nano being devices. During the FL experiments, the wireless router is placed 2 meters away from all the devices.} \end{figure} \section{Experimental Evaluation} \label{sec:experimentation} In this section, we evaluate the performance of our proposed scheduling scheme, cost-effective FL algorithm and derived solution properties. We start by presenting the evaluation setup, and then show the experimental results. \subsection{Experimental Setup} \subsubsection{Platforms} {We conducted experiments both on a networked hardware prototype system and in a simulated environment. Our prototype system, as illustrated in Fig.~2, consists of 30 edge devices with $20$ Raspberry Pis (version 4) and $10$ Jetson Nanos as well as a laptop computer serving as the central server. All devices are interconnected via an enterprise Wi-Fi router, and we developed a TCP-based socket interface for the peer-to-peer connection.\footnote{{To characterize LTE-based wireless networks as in Fig.~1, we manually change the original communication protocol in our TS-based WiFi system, so that all devices start their local training at the same time and without calculating the downlink time.}} In the simulation system, we simulated a cellular network of an urban microcell consisting of a central BS serving as the server and $N=100$ clients. The BS and server were co-located at the center of the cell with a radius of $2$ km, and the clients were uniformly distributed in the cell. } \subsubsection{Datasets and Models} We evaluate our results both on a real dataset and a synthetic dataset. {For the real dataset, following a same setup of \cite{li2020federated}, we adopted the widely used MNIST dataset and EMNIST dataset, which contains gray-scale images of handwritten digits and characters.} For the synthetic dataset, we follow a similar setup to that in \cite{li2018federated}, which generates $60$-dimensional random vectors as input data. The synthetic data is denoted by $Synthetic \ (\alpha, \beta)$ with $\alpha$ and $\beta$ representing the statistical heterogeneity (i.e., how non-i.i.d. the data are). We adopt the \emph{convex} {multinomial logistic regression} model for both datasets with model size around $0.03$ MB \cite{li2019convergence}. \subsubsection{Implementation} {Based on the above, we consider the following three experimental setups with heterogeneous data distribution}. \emph{Prototype Setup}: We conduct the first experiment on the prototype system using MNIST dataset, where we divide $9,000$ data samples among the $N\!=\!30$ edge devices (20 Raspberry Pis and 10 Jetson Nanos) in a non-i.i.d. fashion, with each device containing a balanced number of $300$ samples of only $2$ digit labels. {\emph{Simulation Setup 1}: We conduct the second experiment in the simulated system using EMNIST dataset, where we divide 48,000 image samples among $N=100$ clients in a non-i.i.d. fashion, with each client containing a balanced number of 480 samples of only 2 classes. } \emph{Simulation Setup 2}: We conduct the third experiment in the simulated system using $Synthetic \ (1, 1)$ dataset for statistical heterogeneity. We generate $24,517$ data samples and distribute them among $N\!=\!100$ mobile devices in an unbalanced power law distribution, where the number of samples in each device has a mean of $245$ and standard deviation of $362$. \subsubsection{Training Parameters} For all experiments, we initialize our model with $\mathbf{w}_0=\mathbf{0}$ and SGD batch size $b=64$. In each round, we uniformly sample $K$ devices at random, which run $E$ steps of SGD in parallel. For all experiments, we use an initial learning rate $\eta_0=0.1$ with decay rate $\frac{{\eta}_0}{1+r}$, where $r$ is communication round index. We evaluate the aggregated model in each round on the global loss function. Each result is averaged over 50 experiments. \subsubsection{Heterogeneous System Parameters} The prototype system allows us to capture real system heterogeneity in terms of communication and computation time, which we measured the average $t_p = 4.9 \times 10^{-3}$ s with standard deviation $1.43 \times 10^{-3}$ s and $t_m = 0.16$~s with standard deviation $0.03$ s. We do not consider the energy cost in the prototype system because it is difficult to measure. For the simulated mobile edge system, we assume the system bandwidth is 1.8 MHz and adopt the standard LTE communications model based on a well-known urban channel model with the mean per-client throughput $1.4$~Mbit/s (thus $t_m\approx 0.2$~s) as in \cite{nishio2019client}. We generate the computation time and energy consumption for each client using a truncated normal distribution with mean value of $t_p\!=\!0.5$~s (emulating slow devices), $e_p=0.01$~J, and $e_m = 0.02$~J . {According to the definition of $\gamma$, we unify the time and energy costs such that one second is equivalent to $1-\gamma$ dollars~(\$) and one Joule is equivalent to $\gamma$ dollars~(\$).} \subsection{{Performance Results}} In this subsection, we first evaluate the performance of our proposed TS scheduling strategy with two existing benchmarks. Then, we compare the performance of the proposed solution ($K^*$, $E^*$) obtained from Algorithm~2 for solving Problem \textbf{P3}, with that of the empirical optimal solution ($K_\textnormal{OPT}$, $E_\textnormal{OPT}$) achieved by an exhaustive search on the optimal solution of the original problem \textbf{P1}. Finally, we validate our derived design principles and solution properties. \begin{figure*}[!t] \centering \subfigure[Loss with scheduling scheme ]{\label{schedul_lossa}\includegraphics[width=5.4cm,height=4.5cm]{loss_scheduling_K10E70_new.pdf}} \subfigure[$T_\textnormal{tot}$ with scheduling schemes and $E$]{\label{schedule_lossc}\includegraphics[width=5.4cm,height=4.5cm]{scheding_E_new3.pdf}} \subfigure[$T_\textnormal{tot}$ with scheduling schemes and $K$]{\label{schedule_t_tot}\includegraphics[width=5.4cm,height=4.5cm]{scheding_K_new3.pdf}} \caption Total learning time performance of \textbf{Prototype Setup} for different scheduling strategies with logistic regression and MNIST dataset. (a): For a given pair $\left(K=10, E=70\right)$, our proposed scheduling strategy achieves the target loss 0.4 faster than the two benchmark schemes. (b): For fixed $K=10$, our proposed scheme achieve the target loss using shorter time for different $E$. (c): For fixed $E=70$, our proposed scheme achieve the target loss using shorter time for different $K$.} \label{scheduling} \end{figure*} \subsubsection{Scheduling Performance} Fig.~\ref{scheduling} compares the total learning time \textbf{performance of our proposed TS scheduling with the following two benchmarks} in Prototype Setup: \begin{itemize} \item Benchmark 1: existing TS scheduling strategy in \cite{tran2019federated}, where communication does not begin until all sampled clients complete their local computations. \item Benchmark 2: existing FS scheduling strategy in \cite{shi2020device, chen2020convergence,yang2019energy}, where the algorithm allocates the bandwidth at the start of each round for the sampled clients, then the bandwidth allocation remains unchanged throughout the round and every selected client starts its communication using its allocated bandwidth whenever its computation has finished. \end{itemize} The main observations are as follows \begin{itemize} \item Fig.~\ref{scheduling} demonstrates that \emph{our proposed scheduling strategy in Theorem \ref{theorem1} achieves the target loss faster than the two benchmarks}, since our method can better utilize system resources and adapt to both computation and communication heterogeneity. \item \emph{The performance gaps between our scheme and the two benchmarks increase in $E$ at first and then remain stable in Fig.~\ref{scheduling}(b)}. The reason for this observation is that, as $E$ increases, the computation times between different sampled clients are more different, allowing our scheme to {better utilize the full bandwidth} and thus save per-round time. When $E$ is large enough, the per-round time is only {dominated by computation} time, hence the impact of different scheduling is insignificant as scheduling mainly affects the communication time. \item We also observe that \emph{the performance gaps between our scheme and the two benchmarks increase in $K$ at first and then remain stable in Fig.~\ref{scheduling}(c)}. The explanation for this observation is that as $K$ increases, the difference between the maximum and minimum computation time among the selected $K$ clients can be larger, allowing our scheme to {better utilize the computational heterogeneity}, e.g., communication could begin at an early stage instead of waiting for the rest clients. When $K$ is large enough, the per-round time is mainly {dominated by communication} time, and the gain from computational heterogeneity tends to be stable between different scheduling schemes. \end{itemize} \begin{table*}[!t] \caption{Number of rounds for reaching estimation loss $F_a$ and $F_b$ for estimation of $\frac{A_0}{B_0}$ for three Setups} \label{sample3} \centering { \begin{tabular}{c||c||c|c|c|c|c|c||c} \toprule[1.2pt] \multirow{3}{*}{\makecell[c]{Prototype Setup\\MNIST} & \multirow{3}{*}{\makecell[c]{Estimation loss\\$F_a=0.65$\\\!$F_b=0.55$}} & \scriptsize{Samples of $\left(K,E\right)$} & $\left(1, 30\right)$ & $\left(5, 80\right)$ & $\left(10, 40\right)$ & $\left(15, 100\right)$ &$\left(20, 50\right)$ & \multirow{3}{*}{{\makecell[c]{\textbf{Estimated}\\$\frac{A_0}{B_0}$=36,500}} } \\ \cline{3-8} & & \scriptsize{Rounds to achieve $F_a$} & 50 & 17 & 17 & 13 & 14 & \\ \cline{3-8} & & \scriptsize{Rounds to achieve $F_b$} & 75 & 32 & 30 & 21 & 25 & \\ \midrule[1.2pt] \multirow{3}{*}{\makecell[c]{Simulation Setup 1\\EMNIST }} & \multirow{3}{*}{\makecell[c]{Estimation loss\\$F_a=1.2$\\$F_b=1.0$}} & Samples of $\left(K,E\right)$& $\left(5, 7\right)$& $\left(10, 10\right)$ & $\left(20, 20\right)$ & $\left(30, 30\right)$ & $\left(40, 40\right)$ & \multirow{3}{*}{{\makecell[c]{\textbf{Estimated}\\$\frac{A_0}{B_0}$=960}} } \\ \cline{3-8} & & Rounds to achieve $F_a$ & 17&13&10& 11 &14 & \\ \cline{3-8} & & Rounds to achieve $F_b$ & 29& 20 & 17 & 18& 28 & \\ \bottomrule[1.2pt] \multirow{3}{*}{\makecell[c]{Simulation Setup 2\\Synthetic (1,1) }} & \multirow{3}{*}{\makecell[c]{Estimation loss\\$F_a=1.7$\\$F_b=1.5$}} & Samples of $\left(K,E\right)$& $\left(5, 7\right)$& $\left(10, 10\right)$ & $\left(20, 20\right)$ & $\left(30, 30\right)$ & $\left(40, 40\right)$ & \multirow{3}{*}{{\makecell[c]{\textbf{Estimated}\\$\frac{A_0}{B_0}$=1850}} } \\ \cline{3-8} & & Rounds to achieve $F_a$ & 41&28&22& 19 &18 & \\ \cline{3-8} & & Rounds to achieve $F_b$ & 78& 52 & 39 & 34& 31 & \\ \bottomrule[1.2pt] \end{tabular}} \end{table*} \begin{figure*}[!t] \centering \subfigure[Loss with different $K$]{\label{hd_lossa}\includegraphics[width=5.4cm,height=4.5cm]{loss_E_time.pdf}} \subfigure[Loss with different $E$]{\label{hd_lossc}\includegraphics[width=5.4cm,height=4.5cm]{loss_K_time.pdf}} \subfigure[$T_\textnormal{tot}$ with different $\left(K, E\right)$ ]{\label{hd_t_tot}\includegraphics[width=5.4cm,height=4.5cm]{HDt_total_KE.pdf}} \subfigure[Accuracy with different $E$ ]{\label{hd_lossb}\includegraphics[width=5.4cm,height=4.5cm]{acc_E_time.pdf}} \subfigure[Accuracy with different $K$ ]{\label{hd_acc_t}\includegraphics[width=5.4cm,height=4.5cm]{acc_K_time.pdf}} \caption Training performance of $T_\textnormal{tot}$ for \textbf{Prototype Setup} with logistic regression and MNIST dataset for $\gamma\!=\!0$. (a)-(c): Our solution achieves the target loss using $66.2$~s compared to the empirical optimum $61.7$~s, but faster than those with $E$ being too small or too large and those with $K$ being large. (d)-(e): Our solution achieves target test accuracy $91\%$ slightly longer than the optimal solution, but faster than the non-optimal values of $\left(K,E\right)$ in (a) and (b).} \label{hd} \end{figure*} \subsubsection{Optimality Performance} We first present the estimation process and results of $\frac{A_0}{B_0}$ for the three experiment setups in Table~\ref{sample3}. Figs.~\ref{hd}--\ref{c_tot} compare the \textbf{performance of our {proposed solution of ($K^*,\ E^*$) with empirical optimal solution} ($K_\textnormal{OPT},\ E_\textnormal{OPT}$)} {and other} ($K$, $E$) {pairs}\footnote{The benchmark $E$ and $K$ are chosen to be either lager or smaller than the empirical optimal ones for comparison.} for Prototype and Simulation Setups, respectively.\footnote{We note that ($K^*$, $E^*$) are obtained by estimating the average value of $\frac{A_0}{B_0}$, whose estimation process is summarized in Table~\ref{sample3}. Specifically, we empirically set two relatively high target losses $F_a$ and $F_b$ with a few sampling pairs of $\left(K,E\right)$. Note that due to different learning tasks and statistical heterogeneity, the sampling range of $E$ in Prototype Setup is larger than that in Simulation Setup. Then, we record the corresponding number of rounds for reaching $F_a$ and $F_b$, based on which we calculate the averaged estimation value of $\frac{A_0}{B_0}$ using \eqref{A0B05}.} The key observations are as follows. \begin{figure*}[!t] \centering \subfigure[Loss with different $K$]{\label{setup_femnist0}\includegraphics[width=5.4cm,height=4.5cm]{loss_energy_K_fem.pdf}} \subfigure[Loss with different $E$]{\label{setup_femnist1}\includegraphics[width=5.4cm,height=4.5cm]{loss_energy_E_fem.pdf}} \subfigure[$e_\textnormal{tot}$ with different $\left(K, E\right)$ ]{\label{setup_femnist2}\includegraphics[width=5.4cm,height=4.5cm]{Etot_K_E_fem.pdf}} \subfigure[Accuracy with different $E$ ]{\label{setup_femnist3}\includegraphics[width=5.4cm,height=4.5cm]{acc_energy_E_fem.pdf}} \subfigure[Accuracy with different $K$ ]{\label{setup_femnist4}\includegraphics[width=5.4cm,height=4.5cm]{acc_energy_K_fem.pdf}} \caption {Training performance of $e_\textnormal{tot}$ for \textbf{Simulation Setup 1} with logistic regression and EMNIST dataset for $\gamma\!=\!1$. (a)-(c): Our solution achieves the target loss using $42.4$~J, which slightly larger than the empirical optimum $33.7$~J, but saves several folds of energy compared to those ($E$,$K$) pairs without optimization. (d-e): Our solution achieves the target test accuracy $77.5\%$ using slightly more energy than the optimal solution, but saves several folds of energy than the non-optimal values of $\left(K,E\right)$ in (a) and (b).}} \label{emnist} \end{figure*} \begin{itemize} \item Fig.~\ref{hd} shows the {learning time cost} $T_\textnormal{tot}$ for reaching the target loss under different $\left(K, E\right)$ for Prototype Setup \footnote{For hardware prototype, we only show the convergence performance with $T_\textnormal{tot}$ for $\gamma = 0$.} {In particular, \emph{our solution achieves the target loss using $66.2$ s compared to the empirical optimum $61.7$ s}, whereas other ($K$, $E$) pairs {without optimization may consume a learning time that is several folds more}, as shown in Fig.~\ref{hd}(c).\footnote{The intersections in Fig. 4(c) and Fig. 5(d) show that, for a given $E$, different numbers of $K$ may result in the same total learning time. This is because the trade-off between the total number of rounds for reaching the target loss and the per-round time, as a large $K$ reduces the number of rounds but yields a longer per-round time, whereas a small $K$ reduces the per-round time but requires more rounds.}} \item {Fig.~\ref{emnist} depicts the energy cost $e_\textnormal{tot}$ for reaching the target loss under different $\left(K, E\right)$ for Simulation Setup 1. \emph{Our solution achieves the target loss and accuracy with the similar energy cost compared to the empirical optimal solution,} and saves several folds of energy compared to those ($K$, $E$) pairs without optimization.} \item Figs.~\ref{c_tot} shows the {total cost $C_\textnormal{tot}$} for reaching the target loss for {different $\gamma$} under different $\left(K,\ E\right)$ for Simulation Setup 2. Comparing to other ($K$, $E$) pairs without optimization in Fig.~\ref{c_tot}(c)-(f), {our proposed solutions incur a similar total cost as the corresponding empirical optimal ones through the entire range of $\gamma$}. \end{itemize} \begin{figure*}[t] \centering \subfigure[Loss with $E$ for $\gamma=0.5$]{ \includegraphics[width=5.34cm,height=4.4cm]{loss_gamma05_E15_new.pdf}} \subfigure[Loss with $K$ for $\gamma=0.5$]{\includegraphics[width=5.27cm,height=4.4cm]{loss_gamma05_K4_new.pdf}} \subfigure[\label{ctot_gamma05}$C_\textnormal{tot}$ with $\left(K, E\right)$ for $\gamma=0.5$]{ \includegraphics[width=5.27cm,height=4.4cm]{C_tot_gamma_0.5_new.pdf}} \subfigure[\label{ctot_gamma0}$C_\textnormal{tot}$ with $\left(K, E\right)$ for $\gamma=0$]{ \includegraphics[width=5.27cm,height=4.4cm]{C_tot_gamma_0.pdf}} \subfigure[\label{ctot_gamma1}$C_\textnormal{tot}$ with $\left(K, E\right)$ for $\gamma=1$]{ \includegraphics[width=5.27cm,height=4.4cm]{C_tot_gamma_1_new.pdf}} \subfigure[\label{tradeoffctot}$C_\textnormal{tot}$ with $\gamma$]{\includegraphics[width=5.3cm,height=4.41cm]{C_tot_gamma_new2.pdf}} \caption{Performance of $C_\textnormal{tot}$ for reaching the target loss 1.05 for different $\gamma$ for \textbf{Simulation Setup 2} with logistic regression and Synthetic (1,1). (a)-(b): When $\gamma=0.5$ our solution reaches the target loss $1.05$ using \$1221 compared to the empirical optimal \$1104. (c)-(f): When $\gamma$ increases from 0 to 1, our proposed solutions reach the target loss using the similar total cost as the corresponding empirical optimal ones. } \label{c_tot} \end{figure*} \subsubsection{Property Validation} \label{sec:propertyValidation} We highlight that \textbf{our derived theoretical properties of $K$ and $E$ can be validated empirically} in both prototype and simulation experiments. Particularly, we manually decrease $t_p$ and $e_p$ in Simulation Setup 2, and shows how system parameters affect the design principles in Fig.~\ref{property}. We summarize the key results as follows \begin{itemize} \item We observe from Figs.~\ref{ctot_gamma0}-\ref{ctot_gamma1} that the optimal $K$ decreases from 10 to 1 as $\gamma$ increases from 0 to 1. Particularly, we see from Figs.~\ref{setup_femnist2} and \ref{ctot_gamma1} that, when $\gamma=1$, the energy cost strictly increases in $K$, with $K_\textnormal{OPT}=1$. % These observations confirm our claim in Theorem~\ref{theorem:t_tot} \item Figs.~\ref{hd_t_tot}, \ref{setup_femnist2}, \ref{ctot_gamma05}--\ref{ctot_gamma1} demonstrate that for any fixed value of $K$, the corresponding total cost first decreases and then increases as $E$ increases, which confirms our Theorem~\ref{corollary:t_tot_E1} \item Comparing Fig.~\ref{change_tp} with Fig.~\ref{ctot_gamma0}, we observe that for a fixed value of $E$, the optimal $K$ decreases as $t_p$ decreases. For example, for $E=26$, the optimal $K$ decreases from $10$ to $2$ as $t_p$ decreases, which confirms Theorem~\ref{corollary:t_tot_K}. \item Comparing Fig.~\ref{change_ep} with Fig.~\ref{ctot_gamma1}, for fixed value of $K$, the optimal $E$ increases as $e_p$ decreases, e.g., for $K\!=\!1$, the optimal $E$ increases from 14 to 20, which confirms Theorem~\ref{corollary:t_tot_E2}. \end{itemize} \section{Conclusion} \label{sec:conclusion} In this work, we have studied the cost-effective design for federated learning in mobile edge networks. We proposed a new time-sharing scheduling scheme which captures system heterogeneity in terms of computation and wireless communication, and analyzed how to optimally choose the number of participating clients ($K$) and the number of local iterations ($E$), which are two essential control variables in FL, to minimize the total cost while ensuring convergence. We proposed a sampling-based control algorithm which efficiently solves the optimization problem with marginal overhead. We also derived insightful solution properties which helps identify the design principles for different optimization goals, e.g., reducing learning time or saving energy. Extensive experimentation results validated our theoretical analysis and demonstrated the effectiveness and efficiency of our control algorithm. Our optimization design is orthogonal to most works on resource allocation for FL systems, e.g, transmission power or CPU frequency, and can be used together with those techniques to further reduce the cost. \begin{figure*}[t] \centering \subfigure[\label{change_tp} $C_\textnormal{tot}$ with $\left(K, E\right)$ for $\gamma=0$ ]{\includegraphics[width=5.4cm,height=4.47cm]{C_tot_gamma_0tp0.12_new.pdf}} \subfigure[\label{change_ep} $C_\textnormal{tot}$ with $\left(K, E\right)$ for $\gamma=1$ ]{\includegraphics[width=5.4cm,height=4.47cm]{C_tot_gamma_1ep0.02_new.pdf}} \caption{Performance of $C_\textnormal{tot}$ for reaching the target loss 1.05 for (a) $\gamma=0$ and (b) $\gamma=1$ for \textbf{revised Simulation Setup 2}, where we manually decrease $t_p$ from $0.5$~s to $0.1$~s and $e_p$ from $0.01$~J to $0.002$~J. } \label{property} \end{figure*} \appendices \section {Proof of Theorem 1} \label{theorem1app} We prove by contradiction. For any reordered clients sequence $i\!-\!2$, $i\!-\!1$ and $i$ with $t_{i-2,p}>t_{i-1,p}>t_{i,p}$, then the time after scheduling the three clients is: \begin{equation} \label{app_theo1} \begin{aligned} T_i=&\max \left\{ {{t_{i,p}}, {T_{i - 1}}} \right\} + {t_{i,m}}\\ =&\max \left\{ {{t_{i,p}}, {\max \left\{ {{t_{i-1,p}},{T_{i - 2}}} \right\} + {t_{i-1,m}}}} \right\} + {t_{i,m}}. \end{aligned} \end{equation} Now, suppose we switch the scheduling order of $i\!-\!1$ and $i$, then the time after scheduling the three clients is: \begin{equation} \label{app_theo2} \begin{aligned} T_{i-1}^\prim =\max \left\{ {{t _{i-1,p}}, {\max \left\{ {{t _{i,p}},{T_{i-2}}} \right\} + {t_{i,m}}}} \right\} + {t_{i-1,m}}. \end{aligned} \end{equation} Case 1: if $t_{i,p}>t_{i-1,p}>T_{i-2}$, then $T_i$ in \eqref{app_theo1} reduces to \begin{equation} \begin{aligned} T_ =&\max \left\{ {{t _{i,p}}, \ {{t _{i-1,p}} \! +\! {t_{i-1,m}}}} \right\} + {t_{i,m}}, \end{aligned} \end{equation} and $T_{i-1}^\prime$ in \eqref{app_theo2} reduces to \begin{equation} \begin{aligned} T_{i-1}^\prim =&\max \left\{ {{t _{i-1,p}}, {{t _{i,p}} + {t_{i,m}}}} \right\} + {t_{i-1,m}}\\ =& {{t_{i,p}} + {t_{i,m}}} + {t_{i-1,m}}\\ >& \max \left\{ {{t _{i,p}}, \ {{t _{i-1,p}} \! +\! {t_{i-1,m}}}} \right\} + {t_{i,m}}=T_i. \end{aligned} \end{equation} Case 2: if $T_{i-2}>t_{i,p}>t_{i-1,p}$, then $T_i$ in \eqref{app_theo1} reduces to \begin{equation} \begin{aligned} T_ =&\max \left\{ {{t _{i,p}}, \ T_{i - 2} \! +\! {t_{i-1,m}}} \right\} + {t_{i,m}}\\ =&T_{i - 2} \! +\! {t_{i-1,m}} + {t_{i,m}}, \end{aligned} \end{equation} and $T_{i-1}^\prime$ in \eqref{app_theo2} reduces to \begin{equation} \begin{aligned} T_{i-1}^\prim =&\max \left\{ {{t _{i-1,p}}, {{T_{i - 2}} + {t_{i,m}}}} \right\} + {t_{i-1,m}}\\ =&T_{i - 2} \! +\! {t_{i-1,m}} + {t_{i,m}}=T_i. \end{aligned} \end{equation} Case 3: if $t_{i,p}>T_{i-2}>t_{i-1,p}$, then $T_i$ in \eqref{app_theo1} reduces to \begin{equation} \begin{aligned} T_ =\max \left\{ {{t _{i,p}}, \ {{T _{i-2}} + {t_{i-1,m}}}} \right\} + {t_{i,m}}, \end{aligned} \end{equation} and $T_{i-1}^\prime$ in \eqref{app_theo2} reduces to \begin{equation} \begin{aligned} T_{i-1 =&\max \left\{ {{t _{i-1,p}}, {{t _{i,p}} + {t_{i,m}}}} \right\} + {t_{i-1,m}}\\ =& {{t _{i,p}} + {t_{i,m}}} + {t_{i-1,m}}\\ >& \max \left\{ {{t_{i,p}}, \ {{T_{i-2}} + {t_{i-1,m}}}} \right\} + {t_{i,m}}=T_i. \end{aligned} \end{equation} Therefore, we conclude that if any clients are not scheduled based on increasing order of $t_{k,p}$, scheduling the same sampled clients would result in a longer time. \section{Proof of Lemma 2} \label{lemma2app} Since the $K$ clients are sampled uniformly at random in each round \emph{without replacement}, the ``first" scheduling client is $\min_{k \in \mathcal{K}^{r}}\{t_{k,p}\}$. Thus, in the reordered sequence \eqref{reorder}, those who could be served as the first are the $\{1,2,\ldots,N\!-\!K\!+\!1\}$th clients. The probability of client $i\in\{1,2,\ldots,N-K+1\}$ being the ``first" client is $\frac{{C_{N-i}^{K-1}}}{C_{N}^{K}}$, where $C_{N}^{K}$ is the number of all possible $K$ clients combinations, ${C_{N-k}^{K-1}}$ is the number of $K$ clients combinations with client $i$ being the ``first" (fast) client. In other words, the rest $K-1$ clients must be taken from the behind the $N-K$ clients who placed behind client $k$. Therefore, the expected time of the ``first" client is \begin{equation} \mathbb{E}[\min_{k \in \mathcal{K}^{r}}\{t_{k,p}E\}]=\frac{\sum\nolimits_{i=1}^{N-K+1}{C_{N-i}^{K-1}}t_{i,p} }{C_{N}^{K}}E. \end{equation} Then, similar to the proof in \emph{Lemma} 1, for uniform at random sampling, the probability of each client being sampled in each round is $\frac{K}{N}$. Thus. we have \begin{equation} \begin{aligned} \mathbb{E}[\sum_{k=1}^{K}t_{k,m}^{r}]=&\frac{K}{N} \mathbb{E}[\sum_{i=1}^{N}t_{i,m}^{r}]\\ =&K\frac{\sum_{i=1}^{N}\mathbb{E}[t_{i,m}^{r}]}{N} =K\frac{\sum_{i=i}^{N}\overline{t}_{i,m}}{N} =t_mK. \end{aligned} \end{equation} Given that the computation time and communication time are independent, the approximate per-round time in \eqref{app_tr_wireless} can be expressed as \begin{equation} \begin{aligned} \mathbb{E}[T^{r}] =&\mathbb{E}[\min_{k \in \mathcal{K}^{r}}\{t_{k,p}E\}]+ \mathbb{E}[\sum_{k=1}^{K}t_{k,m}^{r}]\\ =&\frac{\sum\nolimits_{i=1}^{N-K+1}{C_{N-i}^{K-1}}t_{i,p} }{C_{N}^{K}}E+t_mK. \end{aligned} \end{equation} Therefore, \eqref{avgtime} can be obtained for $R$ round communications, which concludes this proof. \section{Proof of Theorem 3} \label{theorem3app} Taking the first order derivative of $\tilde{\mathbb{E}}[C_\textnormal{tot}]$ over $K$ for any given $E$, we have \begin{equation} \label{partialK0} \begin{aligned} \frac{\partial\tilde{\mathbb{E}}[C_\textnormal{tot}]}{\partial K}=&\left[(1\!-\!\gamma)t_m+\gamma\left(e_pE \!+\!{e_m}\right)\right]\left(\frac{A_0}{E}+\frac{B_0(N\!-\!2)E}{N\!-\!1}\right)\\ &-\frac{(1\!-\!\gamma)B_0Nt_pE^2}{(N\!-\!1)K^2}. \end{aligned} \end{equation} When $\gamma=1$, $\frac{\partial\tilde{\mathbb{E}}[C_\textnormal{tot}]}{\partial K}$ is always positive, thus, $K^\ast=1$. However, when $0\le \gamma<1$, $\frac{\partial\tilde{\mathbb{E}}[C_\textnormal{tot}]}{\partial K}$ is negative for small $K$ and positive for large $K$. Thus, as $K$ increases, $\tilde{\mathbb{E}}[C_\textnormal{tot}]$ first decreases and then increases, thus $K^\ast \in [1,N]$. By letting $\frac{\partial\tilde{\mathbb{E}}[C_\textnormal{tot}]}{\partial K}=0$, and dividing $(1-\gamma)$, we concludes that $K^{\ast}$ decreases as $\gamma$ due to the fact that $\frac{\gamma}{(1-\gamma)}$ is an increasing function in $\gamma$. \section{Proof of Theorem 4} \label{theorem4app} Following the proof in Appendix \ref{theorem3app}, we let $\frac{\partial\tilde{\mathbb{E}}[C_\textnormal{tot}]}{\partial K}=0$. Then, it is straightforward to obtain that, for any given $E$ and $0<\gamma<1$, the optimal $K$ increases in $t_p$ while decreases in $t_m$, $e_m$, and $e_p$. In particular, according to Theorem \ref{theorem:t_tot}, when $\gamma=1$, $K^\ast=1$ and thus is independent with $e_m$ and $e_p$. \section{Proof of Theorem 5} \label{theorem5app} Taking the first order derivative of $\tilde{\mathbb{E}}[C_\textnormal{tot}]$ over $E$ for any given $K$, we have \begin{equation} \begin{aligned} \label{partialE_theorem4} \frac{\partial\tilde{\mathbb{E}}[C_\textnormal{tot}]}{\partial E}&=B_{0}\left[(1\!-\!\gamma)\left( 2t_{p} E \!+\! t_{m}K \right)\!+\!\gamma K(2e_pE\!+\!e_m)\right] \\ &\cdot \left(1\!+\!\frac{N\!-\!K}{K(N\!-\!1)}\!\right)-\frac{ A_{0}K[(1\!-\!\gamma)t_m\!+\!\gamma e_m]}{E^{2}}. \end{aligned}\end{equation} For any $0\le\gamma\le1$, and any feasible $K$, \eqref{partialE_theorem4} is negative when $E$ is small and positive when $E$ is large. Thus, as $E$ increases, $\tilde{\mathbb{E}}[C_\textnormal{tot}]$ first decreases and then increases. % \section{Proof of Theorem 6} \label{theorem6app} Following the proof in Appendix \ref{theorem5app}, we let $\frac{\partial\tilde{\mathbb{E}}[C_\textnormal{tot}]}{\partial E}=0$. Then, we have \begin{equation} \begin{aligned} \label{partialE_appF} \frac{\left[(1\!-\!\gamma)\left( 2t_{p} E^3 \!+\! t_{m}KE^2 \right)\!+\!\gamma K(2e_pE^3\!+\!e_mE^2)\right]}{K[(1\!-\!\gamma)t_m\!+\!\gamma e_m]} \\ =\frac{ A_{0}}{B_0\left(1\!+\!\frac{N\!-\!K}{K(N\!-\!1)}\!\right)}. \end{aligned} \end{equation} Thus, it is straightforward to see that the solution of $E$ increases as $t_p$ or $e_p$ decreases. In particular, when $\gamma=0$, the solution of $E$ increases in $\frac{t_m}{t_p}$. Similarly, when $\gamma=1$, the solution of $E$ increases in $\frac{e_m}{e_p}$. \bibliographystyle{IEEEtran}
{'timestamp': '2021-09-14T02:18:37', 'yymm': '2109', 'arxiv_id': '2109.05411', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05411'}
arxiv
\section{Introduction} \label{sec:intro} Advancements in high-performance computing (HPC) and techniques like particle transport and agent-based modeling yield an enormous corpus of stochastic simulation data. \citet{baker2022analyzing} provides a review of state-of-the-art simulation and modeling in such contexts as well as current challenges in this field. Simulators exist with many applications, including disease/epidemics \citep{johnson2018phenomenological,hu2017sequential,fadikar2018calibrating} tumor spread \citep{ozik2019learning}, inventory/supply chain management \citep{hong:nelson:2006,xie2017heteroscedastic}, ocean circulation \citep{herbei2014estimating}, and radiation/nuclear safety \citep{werner2018mcnp6}. In many cases --- in particular those cited above --- the simulator can exhibit input-dependent-noise, or so-called heteroskedasticity. When the data is noisy, in addition to the usual nonlinear dynamics in mean structure, a large and carefully designed simulation campaign is essential for isolating signal. Modeling is another crucial component for recognizing signal in noisy data. Gaussian process (GP) regression is the canonical choice of surrogate model for simulation experiments because it provides accurate predictions and uncertainty quantification (UQ). These GP features facilitate many downstream tasks such as calibration, input sensitivity analysis, Bayesian optimization, and more. See \cite{Santer2018} or \cite{gramacy2020surrogates} for a review of GPs and for additional context. However, standard GP inference and prediction scales poorly to large data sets. GP modeling involves a multivariate normal (MVN) distribution whose dimension $N$ matches the size of the training data, i.e., $(\mathbf{X}_N, \mathbf{Y}_N)$ for regression. The quadratic cost of storage and cubic cost of decomposition of covariance matrices for determinants and inverses involved in likelihoods limits $N$ to the small thousands. For many stochastic computer experiments in modest input dimension, small simulation campaigns are insufficient for learning whilst larger $N$ cannot be handled by ordinary GPs. Numerous strategies abound in diverse literatures (machine learning, spatial/geostatistics, computer experiments) to scale up GP capabilities in $N$, with many relying on approximation. Some take a divide-and-conquer approach, constructing multiple GPs in segments of a partition of the design space \citep{Kim2005, Gramacy2008, park2018patchwork}. A local approximate GP \citep[LAGP;][]{Gramacy2015} offers a kind of infinite-partition, separately constructing $n \ll N$-sized local neighborhoods around each testing location $\mathbf{x}'$ in a transductive \citep{vapnik2013nature} fashion. Small $n$ provides thrifty processing despite $\mathcal{O}(n^3)$ complexity. Handling multiple $\mathbf{x}'$ is parallelizable \citep{gramacy2014massively}. Predictions are accurate, but a downside to local/partition modeling is that it furnishes a pathologically discontinuous predictive surface. Other approaches target matrix decomposition directly by imposing sparsity on the covariance \citep{titsias2009, aune2014parameter, Wilson2015, gardner2018product, Pleiss2018, solin2020hilbert}, the precision matrix \citep{Datta2016, katzfuss2021}, or via reduced rank. One rank reduction strategy deploys a set of $M \ll N$ latent knots, or {\em inducing points}, through which an $\mathcal{O}(M^2N)$ decomposition is derived \citep[e.g.][]{Williams2001, Snelson2006, Banerjee2008, hoffman2013stochastic}. Recently, the inducing points approach has been hybridized with LAGP \citep[LIGP;][]{cole2021locally}, improving computation times and supporting larger neighborhood sizes $n$. GP modeling technology for computer experiments is often tailored to the no-noise (i.e., deterministic simulation) or constant (iid) noise case, which also remains true when scaling up via approximation. Partition-based schemes are an important exception, as region-based statistically independent modeling imparts a degree of non-stationarity, potentially in both mean and variance. Few mechanisms exist to limit or control partitioning. Computational independence, which speeds up the analysis by allowing multiple numerical procedures to be carried out in parallel, can be tightly coupled to regional statistical independence. LAGP is an exception, in that it allows the user to control compute time directly through the neighborhood size, $n$. Although the software \citep[\texttt{laGP};][]{gramacy2016lagp} supports local inference of so-called nugget hyperparameters, its performance for noisy data is often disappointing because small $n$ may cause noise to be misinterpreted as signal, and exacerbate predictive discontinuity. Expressly accommodating input-dependent noise has been explored in the (global/ordinary) GP literature \citep[e.g.,][]{goldberg1997regression, kersting2007most}, introducing $N$ latent nugget variables which must be learned alongside the usual tunable kernel quantities. However, this strategy is in the opposite direction on the computational efficiency frontier. Stochastic kriging \citep{ankenman2010} offers thriftier computation for GP modeling under heteroskedasticity as long as the per-run degree of replication is high. This allows latent variables to be replaced with independent moment-based variance estimates. Heteroskedastic GPs \citep[HetGP;][]{hetGP1} combine these two ideas: using latent variables for each of $\bar{N}$ unique input locations and leveraging replication in design, but not requiring a minimum degree. The so-called ``Woodbury identities'' \citep{Harville2011} facilitate exact GP inference and prediction in $\mathcal{O}(\bar{N}^3)$ time, regardless of $N$. \citet{hetGP2} showed how replication, especially in high noise regions of the input space, can be essential for both statistical and computational efficiency. Yet even though $\bar{N} \ll N$, big $\bar{N}$ may be needed to map out the input space, which can be limiting. In this paper we propose that, by porting the Woodbury approach from HetGP over to the LIGP framework, one achieves the best of both worlds. Relatively few local-$m$ inducing points could support a much larger number of local unique inputs $\bar{n}$ representing a much larger neighborhood of $n$ total observations under replication. Casting a wide $n$-net is crucial for separating signal from noise, but would be prohibitive under the original LAGP regime. In addition to larger neighborhoods, incorporating a state-dependent nugget in the LIGP framework, as is already available in {\tt laGP}, is crucial in estimating noise. Local inducing points, whose number $m \ll \bar{n} \ll n \ll N$ may be far fewer than under any of the other sizes, together with a Woodbury structure for $\bar{n}$ representing the full $n$, make for a powerful cascade of local information. We derive the quantities involved for inference for this upgraded LIGP, which include the gradient for numerical optimization and prediction. Illustrations are provided along the way, followed by extended benchmarking in both constant noise and heteroskedastic settings. We show that this new LIGP capability is both faster and more accurate than alternatives. The remaining flow of the paper is as follows. An overview of GP regression and LIGP is provided in Section \ref{sec:review}. Our contribution, focused on estimating local noise and incorporating replication in LIGP via Woodbury, is detailed in Section \ref{sec:gps_with_reps}. Section \ref{sec:results} summarizes empirical work on synthetic and benchmark examples from epidemiology and biology. Section \ref{sec:bermuda} explores this new capability in the context of pricing Bermudan options in computational finance. Section \ref{sec:discussion} wraps up with a discussion and directions for future work. \section{Review} \label{sec:review} In this section, we review standard GP surrogate modeling followed by locally induced GPs. \subsection{Gaussian process regression} \label{ss:gp_basic} Consider an unknown function $f: \mathbb{R}^d \rightarrow \mathbb{R}$ for a set of $d$-dimensional design locations/inputs $\mathbf{X}_N=(\mathbf{x}_1, \ldots,\mathbf{x}_N)^\top$ and corresponding noisy observations $\mathbf{Y}_N=(y_1, ...,y_N)^\top$ of $f$. A common surrogate for such data is a Gaussian process (GP), which places an MVN prior on $f$. The prior is uniquely defined by a mean vector and covariance (kernel) function $k: \mathbb{R}^d \times \mathbb{R}^d \rightarrow \mathbb{R}$. The observation model is $y(\mathbf{x}_i)=f(\mathbf{x}_i)+\varepsilon_i$, under constant noise, $\varepsilon_i \stackrel{\mathrm{iid}}{\sim} \mathcal{N}(0, v)$. Often the iid noise is hyperparameterized by coupling a nugget $g$ with scale $\tau^2$, as in $v = \tau^2 g$, so that the full model for responses is $$Y_N\sim \mathcal{N}_N(0, \tau^2(\mathbf{K}_N + g\mathbb{I}_N)),$$ where $\mathbb{I}_N$ denotes an $N\times N$ identity matrix. A zero mean simplifies the exposition without loss of generality.\footnote{Any, even nontrivial, mean structure can be subsumed into a covariance kernel if so desired.} We further assume zero-centered observations and coded/pre-scaled inputs \citep{wycoff2021sensitivity} based on inverse distance between rows of $\mathbf{X}_N$. After pre-scaling, the entries of $\mathbf{K}_N$ can be comprised of kernels $k(\cdot, \cdot)$, e.g., the so-called isotropic Gaussian kernel: \begin{equation} \label{eq:kernel} k_{\theta}(\mathbf{x}_i,\mathbf{x}_j)=\text{exp}\left\{ -\frac{||\mathbf{x}_i-\mathbf{x}_j||^2}{\theta}\right\}. \end{equation} A scalar lengthscale hyperparameter $\theta$ governs the rate of radial decay of covariance. Other kernel families such as the Mat\'ern \citep[][Section 5.3.3]{Stein2012,gramacy2020surrogates}, and so-called separable forms with lengthscales for each input coordinate are also common. Our work here is largely agnostic to such choices, as long as $k(\cdot, \cdot)$ is differentiable in the coordinates of $\mathbf{x}$. Many of the limiting characteristics of this overly simplistic choice (e.g., infinite smoothness and isotropy) are relaxed by a local application. Working with MVNs that involve dense covariance matrices, as is furnished by $k(\cdot, \cdot)$, entails storage capacity that grows quadratically in $N$. Prediction and likelihood evaluation for hyperparameter inference, such as for $(\tau^2, \theta, g)$, involve inverses and determinants requiring decomposition (usually via Cholesky) that is cubic in $N$. For brevity, the relevant formulas are not provided here as they are not needed later. We shall provide related expressions momentarily in a more ambitious context. Special cases of the ones we provide may be found in textbooks alongside illustrations of many desirable GP properties such as excellent nonlinear predictive accuracy and UQ. \subsection{Local approximate GPs} \label{ss:lagp} Cubic computational costs are crippling in the modern context of large-$N$ simulation experiments. As a thrifty workaround, \cite{Gramacy2015} introduced the local approximate GP (LAGP) which imposes an implicitly sparse structure by fitting a separate, limited-data GP for each predictive location $\mathbf{x}'$ of interest. Each fit/prediction is based on an $n \ll N$-sized subset of data $D_n(\mathbf{x}') = (\mathbf{X}_n(\mathbf{x}'), \mathbf{Y}_n(\mathbf{x}'))$ nearby $\mathbf{x}'$. Multiple criteria have been suggested to build this local neighborhood $D_n(\mathbf{x}')$, with Euclidean nearest neighbor (NN) being the simplest. Each prediction thus requires flops in $\mathcal{O}(n^3)$, which can offer dramatic savings and is embarrassingly parallel for each $\mathbf{x}'$ \citep{gramacy2014massively}. LAGP was developed for interpolating deterministic simulations, however the {\tt laGP} software on CRAN \citep{gramacy2016lagp} includes a nugget-estimating capability for local smoothing. \begin{figure*}[ht!] \centering \includegraphics[trim=0 0 0 0 , clip,width=.98\textwidth]{sir_slice_plots.pdf} \caption{Mean (top) and (bottom) variance estimates (left) and errors (right) for SIR model along the slice $x_2=0.2$.} \label{fig:sir_slice} \end{figure*} The ``local nugget'' feature underwhelms when applied globally for many $ \mathbf{x}' \in \mathcal{X}$ comprising a dense testing set. This can be seen first-hand by trying the examples in the {\tt laGP} documentation. Figure \ref{fig:sir_slice} provides a demo in a stochastic simulation context with a susceptible--infected--recovered (SIR) disease model \citep{hu2017sequential}, implemented as {\tt sirEval} in {\tt hetGP} \citep{hetGP,binois2021hetgp}. We used a training set of $\bar{N}=10000$ unique inputs in $[0,1]^2$, each paired with a random degree of replication in $\{1,\dots,20\}$, so that the full experiment consisted of $N \approx 100000$ runs. The views in the figure arise from a grid of 200 testing locations along the slice $x_2=0.2$. Estimates of the ``true'' mean and variance (for comparison) are based on smoothed averages of 1000 replicates at each location. Comparators include: LAGP.NN with $n=50$, LIGP.NN with $\bar{n}=100$ ($n\approx 1000$) and $m$=10 inducing points, and HetGP on a random training subset of size $\bar{N}=1000$. Although each comparator incoroporates a different amount of data, which may seem unfair at face value, this was necessary to balance runtime (to within an order of magnitude, in seconds: 0.5, 6.9, and 15.9 respectively) with accuracy. Observe that LAGP's estimates (blue dashed lines) of the mean and variance are highly discontinuous. The error plots in the right column show how LAGP especially struggles to produce accurate estimates for larger $x_1$. Details on our preferred LIGP method (green dashed line), alongside further analysis of this figure, are the subject of Section \ref{sec:gps_with_reps}. The problem with applying LAGP to noisy data is both fundamental and technical. Fundamentally, one needs larger $n$ with noisy data lest the noise dominate the signal, but this severely cuts into efficiency gains. In a technical sense, many stochastic simulation experiments involve replication but the implementation does not adapt its notion of neighborhood accordingly. In the most extreme case, suppose the nearest input site to $\mathbf{x}'$ has $n$ replicates. Under that configuration LAGP will degenerate without a diversity of unique training inputs. Less pathologically, a multitude of nearby replicates would effectively result in a narrower $n$-neighborhood even though the number of sufficient statistics is fewer than $n$. This is inefficient both statistically and computationally. Addressing these two issues is the primary contribution of this paper. \subsection{Locally induced GPs} \label{ss:ligp} LIGP \citep{cole2021locally} is a recent extension of the LAGP idea that relaxes coupling between neighborhood construction and the local covariance structure. Rather than imposing a local covariance structure on $Y_n(\mathbf{x}')$ directly via pairwise distances between $\mathbf{X}_n(\mathbf{x}') \subset \mathbf{X}_N$, LIGP uses an intermediary set of $m$ knots, or so-called {\em inducing points} or {\em pseudo inputs} $\boldsymbol{\Psi}_m(\mathbf{x}')$, whose coordinates are not restricted to $\mathbf{X}_N$. This yields speedups by reducing the rank of the covariance structure. When $m \ll n$ there is a double-speedup, first through neighborhood structure ($n \ll N$) and then through low rank local approximation (cubic in $m$ rather than $n$). Conversely, it allows a much larger neighborhood $n$ without cubic-in-$n$ increase in flops. Let $\mathbf{K}_m$ denote a kernel matrix built from inducing points $\boldsymbol{\Psi}_m(\mathbf{x}')$ and $k(\cdot, \cdot)$, e.g., in Eq.~\eqref{eq:kernel}. We defer a discussion of how one may choose $\boldsymbol{\Psi}_m(\mathbf{x}')$ to Section \ref{ss:local_neighbor}. Similarly, write $\mathbf{k}_{nm}$ as cross evaluations of the kernel between $\mathbf{X}_n$ and $\boldsymbol{\Psi}_m$. Adopting the GP approximation with inducing points introduced by \citet{Snelson2006} yields \begin{equation} \label{eq:SPGP} \mathbf{\Sigma}_n^{(m)}(\mathbf{x}') = \tau^2\left(\mathbf{k}_{nm}\mathbf{K}_m^{-1}\mathbf{k}_{nm}^\top + \Delta_n^{(m)} + g\mathbb{I}_n\right), \end{equation} as the MVN covariance deployed for inference/prediction at $\mathbf{x}'$. Here, $\Delta_n^{(m)}=\text{Diag}\{\mathbf{K}_n-\mathbf{k}_{nm}\mathbf{K}_m^{-1}\mathbf{k}_{nm}^\top \}$ is a diagonal correction matrix for the covariance and $g\mathbb{I}_n$ expresses the pure noise. Our notation is suppressing some dependence on $\mathbf{x}'$ to keep the expressions tidy. Going forward we shall use $\Omega_n^{(m)} =\Delta_n^{(m)} + g\mathbb{I}_n$ to express the sum of diagonal matrices in Eq.~\eqref{eq:SPGP}, electing not to embolden $\Omega_n^{(m)}$ like we do for other matrices since it can be stored as an $n$-vector. When $\boldsymbol{\Psi}_m(\mathbf{x}')\equiv \mathbf{X}_n(\mathbf{x}')$, $\mathbf{\Sigma}_n^{(m)}$ reduces to the standard LAGP covariance $\mathbf{\Sigma}_n(\mathbf{x}') = \tau^2 (\mathbf{K}_n+g\mathbb{I}_n)$ and offers no computational benefit. The cost savings comes through the decomposition of $\mathbf{\Sigma}_n^{(m)}$ \eqref{eq:SPGP} through Woodbury matrix identities. Evaluations of $\mathbf{\Sigma}_n^{-1(m)}$ and $\log |\mathbf{\Sigma}_n^{(m)}|$ may be obtained with $\mathcal{O}(m^2n)$ flops rather than $\mathcal{O}(n^3)$. Likewise, taking $\boldsymbol{\Psi}_m = \mathbf{X}_n = \mathbf{X}_N$ with $\mathbf{Y}_n = \mathbf{Y}_N$ yields a global GP without approximation. Hyperparameter inference may be achieved by maximizing the logarithm of the MVN likelihood $\mathbf{Y}_n \sim \mathcal{N}(\mathbf{0},\mathbf{\Sigma}_n^{(m)})$, which may be expressed up to an additive constant as \begin{align} \label{eq:loglik} \ell(D_n(\mathbf{x}'),\boldsymbol{\Psi}_m;\tau^2, \theta, g) &\propto - n\log(\tau^2)-\log |\mathbf{Q}_m^{(n)}| + \log|\mathbf{K}_m| - \mathbf{1}_n^{\top}\text{log}(\Omega_n^{(m)})\mathbf{1}_n\\ & \qquad -\tau^{-2}\mathbf{Y}_n^\top\left(\Omega^{-1(m)}_n-\Omega_n^{-1(m)}\mathbf{k}_{nm}\mathbf{Q}_m^{-1(n)}\mathbf{k}_{nm}^\top\Omega_n^{-1(m)}\right)\mathbf{Y}_n. \nonumber \end{align} Above, $\mathbf{Q}_m^{(n)}= \mathbf{K}_m + \mathbf{k}_{nm}^{\top}\Omega_n^{-1(m)} \mathbf{k}_{nm}$ and $\mathbf{1}_n$ is a vector of $n$ ones. Differentiating Eq.~\eqref{eq:loglik} with respect to $\tau^2$ yields a closed-form MLE $\hat{\tau}^{2(n,m)}$, see Section \ref{sec:gps_with_reps}. A numerical solver like $\tt{optim}$ in $\sf{R}$ can then work with negative concentrated log-likelihood (i.e., plugging $\hat{\tau}^{2(n,m)}$ into Eq.~(\ref{eq:loglik})) to estimate $\hat{\theta}^{(n,m)}$ and $\hat{g}^{(n,m)}$. It is important to note that \cite{cole2021locally} did not include/estimate a local nugget $g$, which is part of our novel contribution. For fixed hyperparameters $(\hat{\tau}^2, \hat{\theta}, \hat{g})$, a predictive distribution for $Y(\mathbf{x}')$ arises as standard MVN conditioning via an $(n+1)$-dimensional MVN for $(Y(\mathbf{x}'), \mathbf{Y}_n)$. Using $\mathbf{k}_m(\mathbf{x}')=k_{\theta}(\boldsymbol{\Psi}_m,\mathbf{x}')$, the moments of that Gaussian distribution are \begin{align} \label{eq:GPpred} \mu_{m,n}(\mathbf{x}')&=\mathbf{k}_m^{\top}(\mathbf{x}')\mathbf{Q}_m^{-1(n)}\mathbf{k}_{nm}^\top\Omega_n^{-1(m)} \mathbf{Y}_m \hspace{.5cm} \text{and}\\ \sigma_{m,n}^2(\mathbf{x}') & = \hat{\tau}^{2} \left(k_\theta(\mathbf{x}', \mathbf{x}') + \hat{g} -\mathbf{k}_m^{\top}(\mathbf{x}')\left(\mathbf{K}_m^{-1}-\mathbf{Q}_m^{-1(n)}\right)\mathbf{k}_m(\mathbf{x}')\right).\nonumber \end{align} Both the log-likelihood (\ref{eq:loglik}), and predictive equations (\ref{eq:GPpred}) conditional on those values, reduce to LAGP and ordinary GP counterparts with $\boldsymbol{\Psi}_m = \mathbf{X}_n$ and $\boldsymbol{\Psi}_m = \mathbf{X}_n = \mathbf{X}_N$ with $\mathbf{Y}_n = \mathbf{Y}_N$, respectively. Choosing the locations of inducing points $\boldsymbol{\Psi}_m$, globally or locally, may also be based on the likelihood \citep{Snelson2006}, however this is fraught with issues \citep{titsias2009}. \citet{cole2021locally} observed that situating $\boldsymbol{\Psi}_m$ via classical design criteria like integrated variance, or so-called $A$-optimal design, led to superior out-of-sample predictive performance while also avoiding additional cubic calculation. Specifically for local analysis in LIGP, they introduced a weighted form of $\sigma^2_{n,m}(\mathbf{x}')$, centered around $\mathbf{x}'$, and proposed an active learning scheme that minimized weighted integrated mean-square error (wIMSE) for greedy selection of the next element $\boldsymbol{\psi}_{m+1}$. Upgraded details are provided in Section \ref{sec:gps_with_reps}. Saving on computation by stylizing the feature of the local designs for $\boldsymbol{\Psi}_m(\mathbf{x}')$, \citeauthor{cole2021locally}~developed several template schemes that allow to bypass optimization of wIMSE for each $\mathbf{x}'$. \section{Local smoothing under replication} \label{sec:gps_with_reps} LIGP provides an opportunity to reduce compute time while also increasing neighborhood size, because complexity grows cubically in $m$, not $\bar{n}$ or $n$. This is doubly important when there are replicates among $\mathbf{X}_N$. Without inducing points, LAGP neighborhoods of size $n$ could have very few unique inputs $\bar{n} \ll n$. However, LIGP's Woodbury representation may be extended from inducing points to replicates so that neighborhoods of size $\bar{n}$ may be built, regardless of how much bigger $n$ is, without additional cubic cost. \subsection{Fast GP inference under replication} \label{ss:gp_infer} Given a local neighborhood $D_n(\mathbf{x}')=(\mathbf{X}_n(\mathbf{x}'), \mathbf{Y}_n(\mathbf{x}'))$, let $\bar{\mathbf{x}}_i$, $i=1,\dots,\bar{n}$ represent the $\bar{n} \ll n$ unique input locations. Notate each unique $\bar{\mathbf{x}}_i$ in $\mathbf{X}_n(\mathbf{x}')$ as having $a_i\geq 1$ replicates, where $\sum_{i=1}^{\bar{n}}a_i=n$. Let $y_i^{(j)}$ be the response of the $j^\text{th}$ replicate of $\bar{\mathbf{x}}_i$, $j=1,\dots,a_i$. Without loss of generality, assume the $n$-neighborhood inputs are ordered so that $\mathbf{X}_n(\mathbf{x}') \equiv \mathbf{X}_n=(\bar{\mathbf{x}}_1,\dots, \bar{\mathbf{x}}_1, \dots, \bar{\mathbf{x}}_{\bar{n}})^\top$ with each unique input $\bar{\mathbf{x}}_i$ repeated $a_i$ times, and suppose $\mathbf{Y}_n$ is stacked with responses from the $a_i$ replicates in the same order. Based on this construction of $D_n$, let $\mathbf{X}_n=\mathbf{U}\bar{\mathbf{X}}_{\bar{n}}$, where $\mathbf{U}$ is a $n \times \bar{n}$ block matrix $\mathbf{U}=\text{Diag}(\mathbf{1}_{a_1},\dots,\mathbf{1}_{a_{\bar{n}}})$. Defining $\mathbf{U}$ in this way, we have $\mathbf{K}_n=\mathbf{U} \mathbf{K}_{\bar{n}}\mathbf{U}^\top$ where $\mathbf{K}_{\bar{n}} = (k_\theta(\bar{\mathbf{x}}_i,\bar{\mathbf{x}}_j))_{1\leq,i,j\leq\bar{n}}$, while $\mathbf{U}^\top\Omega_n^{(m)}\mathbf{U}=A_{\bar{n}}\Omega^{(m)}_{\bar{n}}$ where $A_{\bar{n}}=\text{Diag}(a_i,\dots,a_{\bar{n}})$ and $\Omega_{\bar{n}}^{(m)} =\text{Diag}\{\mathbf{K}_{\bar{n}}-\mathbf{k}_{\bar{n}m}\mathbf{K}_m^{-1}\mathbf{k}_{\bar{n}m}^\top \} + g\mathbb{I}_{\bar{n}}$. Using these definitions, we present a new expression for $\mathbf{\Sigma}_n^{(m)}$, extending Eq.~\eqref{eq:SPGP} based on the $\bar{n}$ unique input locations in the local neighborhood: \begin{equation} \label{eq:SigR} \mathbf{\Sigma}_n^{(m,\bar{n})} =\tau^2(\mathbf{U}\mathbf{k}_{\bar{n}m}\mathbf{K}_m^{-1}\mathbf{k}_{\bar{n}m}^\top \mathbf{U}^\top + \text{Diag}\{\mathbf{K}_n-\mathbf{U}\mathbf{k}_{\bar{n}m}\mathbf{K}_m^{-1}\mathbf{k}_{\bar{n}m}^\top \mathbf{U}^\top \}+g\mathbb{I}_n). \end{equation} While $\mathbf{\Sigma}_n^{(m,\bar{n})}$ in \eqref{eq:SigR} is $n \times n$, we do not build it in practice. It is an implicit, intermediate quantity which we notate here as a step toward efficient likelihood and predictive evaluation. When $m \ll \bar{n} \ll {n} \ll {N}$, decomposing $\mathbf{\Sigma}_n^{(m,\bar{n})}$ to obtain $\mathbf{\Sigma}_n^{-1(m,\bar{n})} $ and $\log|\mathbf{\Sigma}_n^{(m,\bar{n})} |$ is much cheaper than $\mathcal{O}(n^3)$ under the Woodbury identities. Generically, these are as follows and may be found in most matrix computation resources \citep[e.g.,][]{Harville2011}: \begin{align} \label{eq:woodbury} (\mathbf{B}+\mathbf{C}\mathbf{D}\mathbf{E})^{-1}&=\mathbf{B}^{-1}-\mathbf{B}^{-1}\mathbf{C}(\mathbf{D}^{-1}+\mathbf{E}\mathbf{B}^{-1}\mathbf{C})^{-1}\mathbf{E}\mathbf{B}^{-1}\hspace{.5cm} \text{and}\\ \log|\mathbf{B}+\mathbf{C}\mathbf{D}\mathbf{E}|&=\log|\mathbf{D}^{-1}+\mathbf{E}\mathbf{B}^{-1}\mathbf{C}|+\log|\mathbf{D}|+\log|\mathbf{B}|, \nonumber \end{align} where $\mathbf{B}$ and $\mathbf{D}$ are invertible matrices of size $n \times n$ and $m \times m$ respectively, and $\mathbf{C}^\top$ and $\mathbf{E}$ are of size $m \times n$. Efficient decomposition in our local approximation context involves combining LIGP's use of Eq.~(\ref{eq:woodbury}) with inducing points, and \citeauthor{hetGP1}'s (\citeyear{hetGP1}) separate use leveraging replicate structure. Based on \eqref{eq:SigR}, let $$\mathbf{B}=\text{Diag}\{\mathbf{K}_n-\mathbf{U}\mathbf{k}_{\bar{n}m}\mathbf{K}_m^{-1}\mathbf{k}_{\bar{n}m}^\top \mathbf{U}^\top \}+g\mathbb{I}_n, \quad\mathbf{D}=\mathbf{K}_m^{-1} \quad \text{and }\mathbf{E}=\mathbf{C}^\top=\mathbf{k}_{\bar{n}m}^\top \mathbf{U}^\top.$$ The result is as follows: \begin{align} \label{eq:SigiR} \mathbf{\Sigma}_n^{-1(m,\bar{n})} =&\tau^{-2}\Big(\Omega_n^{-1(m)}-\mathbf{U}\Omega_{\bar{n}}^{-1(m)}\mathbf{k}_{\bar{n}m}\mathbf{Q}_m^{-1(\bar{n})}\mathbf{k}_{\bar{n}m}^{\top}\Omega_{\bar{n}}^{-1(m)}\mathbf{U}^\top \Big) \hspace{.5cm} \text{and} \\ \log |\mathbf{\Sigma}_n^{(m,\bar{n})}|=&\log(\tau^2)+\log |\mathbf{Q}_m^{(\bar{n})}|- \log |\mathbf{K}_m| +\sum_{i=1}^{\bar{n}}a_i\text{log}\omega_i^{(\bar{n}, m)}, \nonumber \end{align} where $\mathbf{Q}_m^{(\bar{n})}= \mathbf{K}_m + \mathbf{k}_{\bar{n}m}^{\top}\Lambda_{\bar{n}}^{(m)} \mathbf{k}_{\bar{n}m}$, $\Lambda_{\bar{n}}^{(m)}=A_{\bar{n}}\Omega^{-1(m)}_{\bar{n}}$, and $\omega_i^{(\bar{n}, m)}$ is the $i^{\text{th}}$ diagonal term in $\Omega^{(m)}_{\bar{n}}$. Eq.~\eqref{eq:SigiR} is key to reducing computational cost from $\mathcal{O}(nm^2)$ in Eqs.~(\ref{eq:loglik}--\ref{eq:GPpred}) to $\mathcal{O}(\bar{n}m^2)$. The representations in \eqref{eq:SigiR} allow the log-likelihood \eqref{eq:loglik} to be expressed as follows \begin{align} \label{eq:loglikR} \ell(D_n,\boldsymbol{\Psi}_m;\tau^2, \theta, g) \propto & - n\log(\tau^2)-\log |\mathbf{Q}_m^{(\bar{n})}| + \log|\mathbf{K}_m| - \sum_{i=1}^{\bar{n}}a_i\text{log}\omega_i^{(\bar{n}, m)} \\ &-\tau^{-2}\left(\mathbf{Y}_n^\top \Omega^{-1(m)}_n\mathbf{Y}_n-\bar{\mathbf{Y}}_{\bar{n}}^\top \Lambda_{\bar{n}}^{(m)}\mathbf{k}_{\bar{n}m}\mathbf{Q}_m^{-1(\bar{n})}\mathbf{k}_{\bar{n}m}^\top \Lambda_{\bar{n}}^{(m)}\bar{\mathbf{Y}}_{\bar{n}}\right), \nonumber \end{align} up to an additive constant. Above, $\bar{\mathbf{Y}}_{\bar{n}}$ stores the averaged responses for each unique row $\mathbf{X}_{\bar{n}}$. Notice that when Eq.~\eqref{eq:SigiR} is applied to the log-likelihood, the $\mathbf{U}$ terms vanish. In fact, we do not need this quantity or $\mathbf{\Sigma}_n^{-1(m,\bar{n})}$ except as notational devices. Instead, all matrices in Eq.~\eqref{eq:loglikR} have dimension in $m$ and/or $\bar{n}$. Although $\mathbf{Y}_n^\top \Omega^{-1(m)}_n\mathbf{Y}_n$ must still be calculated, this is a product of vectors, so the entries in $\Omega^{-1(m)}_n$ may be stored and accessed through $\Omega_{\bar{n}}^{-1(m)}$ and $A_{\bar{n}}$. Their storage and manipulation are thus linear in $n$. Differentiating \eqref{eq:loglikR} with respect to $\tau^2$ and solving, gives the MLE: \begin{equation}\label{eq:nuhatR} \hat{\tau}^{2(\bar{n},m)} = n^{-1}\left(\mathbf{Y}_n^\top\Omega^{-1(m)}_n\mathbf{Y}_n-\bar{\mathbf{Y}}_{\bar{n}}^\top \Lambda_{\bar{n}}^{(m)}\mathbf{k}_{\bar{n}m}\mathbf{Q}_m^{-1(\bar{n})}\mathbf{k}_{\bar{n}m}^\top \Lambda_{\bar{n}}^{(m)}\bar{\mathbf{Y}}_{\bar{n}}\right). \end{equation} The equation for $\hat{\tau}^{2(\bar{n},m)}$ in \eqref{eq:nuhatR} still relies on all replicates through the full $\mathbf{Y}_n$ and is equivalent to $\hat{\tau}^{2(n,m)}$ as provided by \citeauthor{cole2021locally} (\citeyear{cole2021locally}), Eq. 6. This part of the calculation is linear in $n$. However when replicates are present, evaluation in \eqref{eq:nuhatR} may be much faster owing to the second term being sized in $\bar{n}$ and $m$. Plugging $\hat{\tau}^{2(\bar{n},m)}$ into Eq.~\eqref{eq:loglikR} yields the following concentrated negative log likelihood: \begin{align} \label{eq:concentrate_ll} -\ell \; (D_n,\boldsymbol{\Psi}_m; \theta, g) &\propto n\log\left(\mathbf{Y}_n^\top\Omega^{-1(m)}_n\mathbf{Y}_n-\bar{\mathbf{Y}}_{\bar{n}}^\top \Lambda_{\bar{n}}^{(m)}\mathbf{k}_{\bar{n}m}\mathbf{Q}_m^{-1(\bar{n})}\mathbf{k}_{\bar{n}m}^\top \Lambda_{\bar{n}}^{(m)}\bar{\mathbf{Y}}_{\bar{n}}\right)\\ &\;\; +\log |\mathbf{Q}_m^{(\bar{n})}| - \log|\mathbf{K}_m| + \sum_{i=1}^{\bar{n}}a_i\text{log}\omega_i^{(\bar{n}, m)}. \nonumber \end{align} The expression above is negated for library-based minimization in search of MLEs $\hat{\theta}^{(\bar{n},m)}$ or $\hat{g}^{(\bar{n},m)}$. Numerical methods such as BFGS \citep{Byrd1995} work well. Convergence and computing time of such optimizers is aided by closed-form derivatives, which are tedious to derive but are also available in closed form: \begin{align} \label{eq:concentrate_deriv} -\frac{\partial \ell \; (D_n,\boldsymbol{\Psi}_m, \theta, g)}{\partial \cdot} &\propto n\left(\mathbf{Y}_n^\top\Omega^{-1(m)}_n\mathbf{Y}_n-\bar{\mathbf{Y}}_{\bar{n}}^\top \Lambda_{\bar{n}}^{(m)}\mathbf{k}_{\bar{n}m}\mathbf{Q}_m^{-1(\bar{n})}\mathbf{k}_{\bar{n}m}^\top \Lambda_{\bar{n}}^{(m)}\bar{\mathbf{Y}}_{\bar{n}}\right)^{-1}\\ &\quad\times \frac{\partial\left(\mathbf{Y}_n^\top\Omega^{-1(m)}_n\mathbf{Y}_n-\bar{\mathbf{Y}}_{\bar{n}}^\top \Lambda_{\bar{n}}^{(m)}\mathbf{k}_{\bar{n}m}\mathbf{Q}_m^{-1(\bar{n})}\mathbf{k}_{\bar{n}m}^\top \Lambda_{\bar{n}}^{(m)}\bar{\mathbf{Y}}_{\bar{n}}\right)}{\partial \cdot}\nonumber\\ &\quad+\text{tr}\left(\mathbf{Q}_m^{-1(\bar{n})}\frac{\partial \mathbf{Q}_m^{(\bar{n})}}{\partial \cdot}\right)- \text{tr}\left(\mathbf{K}_m^{-1}\frac{\partial \mathbf{K}_m}{\partial \cdot}\right) + \sum_{i=1}^{\bar{n}} a_i \frac{\partial \log \omega_i^{(\bar{n}, m)}}{\partial \cdot}. \nonumber \end{align} Again, observe that none of these log-likelihood-derived quantities (\ref{eq:loglikR}--\ref{eq:concentrate_deriv}) involve matrices sized bigger than $m\times \bar{n}$. Conditioning on the estimated hyperparameters leaves us with the following re-expressions of the LIGP predictive equations \eqref{eq:GPpred}: \begin{align} \label{eq:GPpredR} \mu_{m,\bar{n}}(\mathbf{x}') &=\mathbf{k}_m^{\top}(\mathbf{x}')\mathbf{Q}_m^{-1(\bar{n})}\mathbf{k}_{\bar{n}m}^\top\Lambda_{\bar{n}}^{(m)}\bar{\mathbf{Y}}_{\bar{n}} \hspace{.5cm} \text{and}\\ \sigma_{m,\bar{n}}^2(\mathbf{x}') & =\hat{\tau}^{2(\bar{n}, m)} \left(k_\theta(\mathbf{x}',\mathbf{x}')+\hat{g}^{(\bar{n}, m)} - \mathbf{k}_m^{\top}(\mathbf{x}')\left(\!\mathbf{K}_m^{-1} - \mathbf{Q}_m^{-1(\bar{n})} \right)\mathbf{k}_m(\mathbf{x}') \right).\nonumber \end{align} Although these look superficially similar to \eqref{eq:GPpred}, the following remarks are noteworthy. Perhaps the biggest difference is that the average of replicates $\bar{\mathbf{Y}}_{\bar{n}}$ is used for the mean. The Woodbury identity ensures that the result is the same as \eqref{eq:GPpred}, both in mean and variance, if the replicate structure is overlooked. In both cases, many of the details are buried in matrices whose $(\bar{n})$ scripts mask a substantial difference in the subroutines that would be required to build the requisite quantities for \eqref{eq:GPpredR} as compared to \eqref{eq:GPpred}. Kriging with pre-averaged responses $\bar{\mathbf{Y}}_{\bar{n}}$, whether locally or globally, is a common technique for efficiently managing replicates. However, one must take care to (a) adjust the covariance structure appropriately, and (b) utilize all replicates in estimating scale $\hat{\tau}^2$. \citet{hetGP2} show that $\bar{\mathbf{Y}}_{\bar{n}}$ are not sufficient statistics. Using only pre-averaged responses risks leaving substantial uncertainty un-accounted for in prediction. Our Woodbury identities provide a full covariance structure (\ref{eq:SigR}), and the adjustments in $n$-quantities for an appropriate scale estimate (\ref{eq:nuhatR}). Alternative approaches, such as \citet{ankenman2010}'s stochastic kriging (SK), also use unique $\bar{n}$ inputs and pre-averaged outputs. Asymptotically covering (a), it may be shown that SK yields the best linear unbiased predictor (BLUP) when conditioning on estimated hyperparameters. However, the uncertainty in that predictive surface is not fully quantified. For example, SK may only furnish confidence intervals on predictions, not full predictive intervals, because it does not utilize the full set of sufficient statistics (b). Since our Woodbury application links Eq.~\eqref{eq:GPpredR} with \eqref{eq:GPpred} identically, a BLUP property holds (locally) for LIGP without asymptotic arguments, and with full predictive UQ. More specifically, consider the following comparison which upgrades an argument from \cite{hetGP1} to our local inducing points setting. We show how the MLE of the scale parameter $\tau^2$ is not the same (conditioned on $\theta, g$) when calculated on the original set of data versus the unique design locations with averaged responses. Using unique-$\bar{n}$ calculations based on $\bar{\mathbf{Y}}_{\bar{n}}$ only would result in $\bar{\tau}^{2(\bar{n},m)}=\bar{n}^{-1}\bar{\mathbf{Y}}_{\bar{n}}^\top \bar{\boldsymbol{\Sigma}}_{\bar{n}}^{-1}\bar{\mathbf{Y}}_{\bar{n}} $ where \begin{equation} \label{eq:Sig_avg} \bar{\boldsymbol{\Sigma}}_{\bar{n}}^{(m)}=\mathbf{k}_{\bar{n}m}\mathbf{K}_m^{-1}\mathbf{k}_{\bar{n}m}^\top+\Delta_{\bar{n}}^{(m)} +gA_{\bar{n}}^{-1}, \end{equation} weights the nugget (noise) based on the number of replicates $a_i$ at each unique location $\bar{\mathbf{x}}_i$. Our full neighborhood calculation for the local MLE for $\tau^{2}$ with inducing points in Eq.~\eqref{eq:nuhatR} can be rewritten as follows: \begin{align}\label{eq:tau2_avg} \hat{\tau}^{2(\bar{n},m)} &=N^{-1}\biggl(\bar{n}\bar{\tau}^{2(\bar{n},m)} + \mathbf{Y}_n^\top\Omega^{-1(m)}_n\mathbf{Y}_n-\bar{\mathbf{Y}}_{\bar{n}}^\top \Lambda_{\bar{n}}^{(m)}\bar{\mathbf{Y}}_{\bar{n}}-\\ & \qquad\qquad \bar{\mathbf{Y}}_{\bar{n}}^\top \bar{\boldsymbol{\Sigma}}_{\bar{n}}^{-1(m)}((A_{\bar{n}}^{-1}-\mathbb{I}_{\bar{n}})^{-1}\Delta_{\bar{n}}^{-1(m)}+\bar{\boldsymbol{\Sigma}}_{\bar{n}}^{-1(m)})^{-1}\bar{\boldsymbol{\Sigma}}_{\bar{n}}^{-1(m)}\bar{\mathbf{Y}}_{\bar{n}}\biggr). \nonumber \end{align} See the Appendix for details. Observe that $\bar{\tau}^{2(\bar{n},m)}$ above in Eq.~\eqref{eq:Sig_avg} is but a small part of \eqref{eq:tau2_avg}. The term following $\bar{\tau}^{2(\bar{n},m)}$ serves as a correction for the variance estimate. \subsection{Local neighborhood geography} \label{ss:local_neighbor} To dig a little deeper into the differences between LAGP and LIGP, especially regarding handling replicates and LIGP's upgraded capability, consider again the SIR example introduced in Section \ref{ss:lagp}. Whereas Figure \ref{fig:sir_slice} involved a continuum of predictions along a 1d slice, Figure \ref{fig:sir_neighborhood} shows relevant quantities involved in one of the locations $\mathbf{x}'=(0.47, 0.2)$ along that slice, indicated by the green triangle. Recall that the input space is in 2d with $\bar{N}=10000$ unique inputs and replicate degree $a_i\in \{1, 2, \dots, 20\}$ distributed uniformly. With such a high degree of replication, LAGP's default $n=50$ neighborhood is small, comprising of only $\bar{n}=5$ unique locations. As the green triangle moves along the slice of Figure \ref{fig:sir_slice}, eventually one of those five will be replaced, resulting in a change in conditioning set of upwards of 1/5 of $\bar{n}$. This provides some of the intuition as to why the LAGP surfaces in Figure \ref{fig:sir_slice} are so ``jumpy'' and often inaccurate. \begin{figure*}[ht!] \centering \includegraphics[trim=0 10 0 30, clip,width=.65\textwidth]{lagp_vs_ligp_neighborhoods.pdf} \caption{LAGP and LIGP local neighborhoods at $\mathbf{x}'=(0.47, 0.2)$, with the numbers denoting the number of replicates at each location. Gray dots represent $\mathbf{X}_N \setminus \mathbf{X}_n$.} \label{fig:sir_neighborhood} \end{figure*} LIGP's implementation of Eqs.~(\ref{eq:loglikR}--\ref{eq:GPpredR}) affords a much larger amount of data in the local model for commensurate computing effort through a template of $m=10$ inducing points. These are indicated as blue triangles in Figure \ref{fig:sir_neighborhood}. The neighborhood of $\bar{n}=100$ unique design locations are indicated with their number of replicates (black numbers), $n=1091$ in total. In this instance, LIGP conditions upon 20 times more training data than LAGP. This yields more accurate and stable mean and variance estimates, shown visually along a slice in Figure \ref{fig:sir_slice} and summarized in a more expansive Monte Carlo (MC) exercise in Section \ref{ss:sir}. Those latter results additionally show that such accurate predictions can be achieved at a computational cost that is substantially lower than LAGP. The location and spacing of the inducing points $\boldsymbol{\Psi}_m(\mathbf{x}')$ in Figure \ref{fig:sir_neighborhood} (blue triangles) come from a local space-filling template scheme based on wIMSE. The idea is that a local inducing point set of a desired size can be built up greedily, using integrated variance under a Gaussian measure centered at $\mathbf{x}'$. An expression using $\bar{n}$ unique neighborhood elements (together with all replicates, $n$) given \eqref{eq:SigR} is \begin{align} \label{eq:wimseR} &\text{wIMSE}_{\bar{n}}^{(m+1)} (\boldsymbol{\psi}_{m+1}, \mathbf{x}') =\int_{\breve{\mathbf{x}}\in \mathcal{X}}k_\theta(\breve{\mathbf{x}},\mathbf{x}')\frac{\sigma_{m+1,\bar{n}}^2(\breve{\mathbf{x}})}{\tau^2} \; d\breve{\mathbf{x}} \\ & \quad =\frac{\sqrt{\theta\pi}}{2}\prod_{k=1}^d\Bigg(\text{erf}\left\{\frac{\mathbf{x}'-a_k}{\sqrt{\theta}}\right\}-\text{erf}\left\{\frac{\mathbf{x}'-b_k}{\sqrt{\theta}}\right\}\Bigg) -\text{tr}\Big\{\Big(\mathbf{K}^{-1}_{m+1}-\mathbf{Q}^{-1(\bar{n})}_{m+1}\Big)\mathbf{W}'_{m+1}\Big\}, \nonumber \end{align} where $\text{erf}$ is the Gaussian error function, $a_k,b_k$ are bounds for a hyperrectangle study region $\mathcal{X} = [a_k, b_k]_{k=1}^d$, and $\mathbf{W}'_{m+1}=\prod_{k=1}^d \mathbf{W}'_{m+1,k}$. Again, the resemblance to a similar expression from \citet{cole2021locally} masks a substantial enhancement in its component parts due to a double-Woodbury application, as notated by $\bar{n}$ scripts. The $(i,j)^\text{th}$ entry of $\mathbf{W}'_{m+1,k}$ is $w_{m+1,k}(\boldsymbol{\psi}_{i}, \boldsymbol{\psi}_{j})$ defined in Eq.~(11) in \citet{cole2021locally}. A closed-form gradient with respect to $\boldsymbol{\psi}_{m+1}$ may also be derived. This is similar in form to \citeauthor{cole2021locally}, so we do not duplicate it here. Given $\mathbf{Q}^{-1(\bar{n})}_{m+1} \equiv \mathbf{Q}^{-1(n)}_{m+1}$, the calculation in \eqref{eq:wimseR} and derivative are equivalent to Eqs.~(10--12) in that paper. Consequently, a wIMSE optimized design of inducing points is not affected by the local distribution of replicates. Under replication $\mathbf{Q}^{-1(\bar{n})}_{m+1}$ can, of course, be calculated much faster than $\mathbf{Q}^{-1(n)}_{m+1}$, so the optimization is speedier. Regularity in local inducing point design also means that simple space-filling designs can serve as thrifty substitutes to the wIMSE design with similar predictive accuracy. The qNorm method \citep{cole2021locally} transforms a space-filling design with the inverse-CDF of a Normal distribution to mimic an wIMSE inducing point design. This is what was used for Figures \ref{fig:sir_slice}--\ref{fig:sir_neighborhood}. Once a set of inducing points $\boldsymbol \Psi_m(\mathbf{x}')$ is calculated for one $\mathbf{x}'$, \citet{cole2021locally} show that it can serve as a {\em template} for predictions at other members of a testing set $\mathcal{X}$ through displacement and warping, so long as the characteristics of the original design $\mathbf{X}_N$ are uniform. Templates based on wIMSE tend to fill the neighborhood in a more uniform manner than via qNorm, providing a higher density of inducing points near the predictive location. This often leads to more accurate prediction. Yet the reduced time required to build qNorm templates is also beneficial. We contrast both options in our empirical work in Section \ref{sec:results}. \section{Implementation and benchmarking} \label{sec:results} Now we provide practical details and report on experimental results showcasing LIGP's potential for superior accuracy and UQ at lower computational costs against LAGP and HetGP. Our examples include data from a toy function and real stochastic simulators. All analysis was performed on an eight-core hyperthreaded Intel i9-9900K CPU at 3.60 GHz. Every effort was made to take advantage of that distributed resource to minimize compute times. \subsection{Implementation details} \label{ss:implement} Open source implementation of LIGP can be found in the {\tt liGP} package on CRAN \citep{liGP}. {\sf R} code \citep{R} supporting all examples reported here and throughout the paper, may be found on our Git repository. \begin{center} \url{https://bitbucket.org/gramacylab/ligp/src/master/noise} \end{center} Our main competitors are {\tt laGP} \citep{gramacy2016lagp} and {\tt hetGP} \citep{hetGP}. While {\tt laGP} is coded in {\sf C} with {\tt OpenMP} for symmetric multiprocessing (SMC) parallelization ({\sf R} serving only as wrapper), and {\tt hetGP} leverages substantial {\tt RCpp} \citep{Rcpp}, our LIGP implementation coded purely in {\sf R} using {\tt foreach} for SMC distribution. With {\tt laGP} we use the default neighborhood size of $n=50$ built by NN and Active Learning Cohn \citep[ALC;][]{cohn1994adavances}, representing distance- and variance-based (similar to wIMSE) approaches, respectively. For {\tt hetGP}, we reduce the training data to a random subset of $\bar{N}=1000$ unique inputs (retaining all replicates) to keep decompositions tractable. Despite compiled {\sf C/C++} libraries and thrifty (local/global) data subset choices, our (more accurate and larger-neighborhood) LIGP models are competitive, time-wise, and sometimes notably faster. Our LIGP implementation uses an isotropic Gaussian kernel with scalar lengthscale $\theta$. To improve numerical conditioning of matrices $\mathbf{K}_m$ and $\mathbf{Q}_m^{(n)}$ for stable inversion, we augment their diagonals with $\epsilon_K=10^{-8}$ and $\epsilon_Q=10^{-5}$ jitter \citep{Neal1998}, respectively. Our implementation in {\tt liGP} automatically increases these values for a particular local model if needed. LAGP and HetGP results also utilize an isotropic Gaussian kernel. Using separable local formulations do not significantly improve predictive performance, especially after globally prescaling the inputs \citep{sun2019emulating}. Pre-scaling or warping of inputs \citep{wycoff2021sensitivity} has become a popular means of boosting predictive performance of sparse GPs \citep[e.g.,][]{katzfuss2020scaled}. In our exercises, we divide by square-rooted separable global lengthscales obtained from a GP fit to random $\bar{N}=1000$ data subsets with averaged responses $\bar{\mathbf{Y}}_{\bar{N}}$. See \cite{gramacy2020surrogates}, Section 9.3.4, for details. The time required for this, which is negligible relative to other timings, is not included in our summaries. For inducing point designs $\boldsymbol{\Psi}_m(\mathbf{x}')$, we use wIMSE templates based on Eq.~\eqref{eq:wimseR} built at the center of the design space $\check{\mathbf{x}}$, determined as the median of $\mathbf{X}_N$ in each dimension. For initial local lengthscale $\theta^{(0)}$, we adopt a strategy from {\tt laGP} via the 10\% quantile of squared pairwise distances between members of $\mathbf{X}_n$.\footnote{In {\tt laGP}, the function providing $\theta^{(0)}$ in this way is {\tt darg}.} When selecting each $\boldsymbol{\psi}_{m+1}$ to augment $\boldsymbol{\Psi}_m$, optimizing wIMSE is conducted via a 20-point multi-start derivative-based L-BFGS-B \citep{Byrd1995} scheme (using {\tt optim} in {\sf R} to a tolerance of 0.01) peppered within the bounding box surrounding the neighborhood $\mathbf{X}_n$. In addition to the wIMSE design for the inducing point template, we consider so-called ``qNorm'' templates derived from space-filling designs. These originate from $m-1$ point Latin hypercube samples \citep[LHS;][]{Mckay:1979} on the hyperrectangle enclosing $\mathbf{X}_n(\check{\mathbf{x}})$, augmented with $\check{\mathbf{x}}$ as the $m^\mathrm{th}$ point. These LHSs are warped with the inverse Gaussian CDF to closely mimic the wIMSE design. Individual local neighborhoods and predictions are made for a set of $N'$ testing locations $\mathbf{x}' \in \mathcal{X}$ given training data $\{\mathbf{X}_N,\mathbf{Y}_N\}$, neighborhood size $\bar{n}$, and number of inducing points $m$. We use $\bar{n}=100$ for each experiment, with $m=10$ and $30$ for the 2d and 4d problems, respectively. Each location $\mathbf{x}'_i$, for $i = 1, \dots, N'$ proceeds in parallel via 16 {\tt foreach} threads.\footnote{Two per hyperthreaded core.} To estimate scale and lengthscale, we used Eqs.~(\ref{eq:nuhatR}--\ref{eq:concentrate_deriv}) via {\tt optim} through the local neighborhoods of $\mathbf{x}'$. To aid in discerning signal from noise during hyperparameter optimization, we incorporate default priors for $\theta$ and $g$, from {\tt laGP}, described in Appendix A of \cite{gramacy2016lagp}. Predictions follow Eq.~\eqref{eq:GPpredR}. \subsection{Benchmark non-stationary data} \label{ss:syn_results} The toy 2d function known as Herbie's tooth \citep{herbtooth} is attractive as a benchmark problem due to its non-stationary mean surface with multiple local minima. The mean function is defined by $f(x_1, x_2)= -w(x_1)w(x_2)$, $x_1,x_2 \in [-2,2]$, where $$w(x)=\text{exp}\left\{-(x-1)^2\right\}+\text{exp}\left\{-0.8(x+1)^2\right\}-0.05\sin\left(8(x+0.1)\right).$$ For this experiment we introduce constant noise $\epsilon \sim N(0,0.02^2)$, creating a response $y(x_1, x_2) = f(x_1, x_2) + \epsilon$. Each of the 30 MC repetitions is comprised of a fresh training set of $\bar{N}=10000$ LHS locations, each with $a_i \stackrel{\mathrm{iid}}{\sim} \mathrm{Unif}\{1,2,\dots, 20\}$ for $i=1,\dots,\bar{N}$. Although our later experiments use a more common, fixed-degree setup for replicates, we choose random $a_i$ here to underscore that LIGP does not require a minimum amount of replication. A separate LHS of $N'=10000$ out-of-sample testing locations is created for each MC run. Our LAGP fits include $n=100$ via NN for a slightly fairer comparison to LIGP, in addition to the other LAGP options described earlier. \begin{figure*}[ht!] \centering \includegraphics[trim=0 0 20 20 , clip,width=.49\textwidth]{ht_rmse_vs_time.pdf} \includegraphics[trim=0 0 20 20 , clip,width=.49\textwidth]{ht_score_vs_time.pdf} \caption{RMSE (left) and score (right) vs.~log compute time over 30 MC repetitions for Herbie's tooth experiment. Median statistics are denoted with bold markers.} \label{fig:ht_results} \end{figure*} Figure \ref{fig:ht_results} shows out-of-sample accuracy statistics versus the logarithm of compute time across the MC repetitions. A particular method's median statistic, taken marginally across both axes, is represented with a bold symbol. The left panel shows the root mean-squared prediction error (RMSE; lower is better) against the (de-noised) truth along the vertical axis. In the right panel, the vertical axis shows proper scores (higher is better), combining mean and variance (UQ) accuracy \citep[][Eq.~(27)]{gneiting2007strictly} against the (noisy) test data. Concretely, RMSE (lower is better) and score (higher) follow: \begin{equation*} \label{eq:rmse_score} \text{RMSE}=\sqrt{\sum_{i=1}^{N'}(\hat{\mu}(\mathbf{x}_i)-y(\mathbf{x}_i))^2} \hspace{.4cm} \text{and} \hspace{.4cm} \text{Score}=-\sum_{i=1}^{N'}\frac{\left(\hat{\mu}(\mathbf{x}_i)-y(\mathbf{x}_i)\right)^2}{\hat{\sigma}^2(\mathbf{x}_i)}-\sum_{i=1}^{N'}\hat{\sigma}^2(\mathbf{x}_i). \end{equation*} LIGP methods yield the fastest predictions with the lowest RMSEs and highest scores. Our LIGP.qNorm (blue $+$'s) has the quickest compute time. LAGP.NN with $n=50$ (green inverted triangles) is the fastest among the LAGP models, but is least accurate. HetGP (black circles) is fit with substantial sub-setting, which explains its high-variance metric on both time and accuracy. Notice that LAGP.ALC (red diamonds) and LAGP.NN ($n=100$; navy triangles) perform similarly for RMSE, but the latter has a higher score. This supports our claim that a wider net of local training data is needed to better estimate noise. \subsection{Susceptible-infected-recovered (SIR) epidemic model} \label{ss:sir} We return to the SIR model \citep{hu2017sequential} first mentioned in Section \ref{ss:lagp}. SIR models are commonly used for cost-benefit analysis of public health measures to combat the spread of communicable diseases such as influenza or Ebola. We look at a simple model with two inputs: $x_1$ the initial number susceptible individuals; and $x_2$ the number of infected individuals. In {\tt hetGP} \citep{hetGP}, the function {\tt sirEval} accepts these two inputs on the unit scale. The response of the model is the expected aggregate number of infected-days across Markov chain trajectories until the epidemic ends. The signal-to-noise ratio varies drastically throughout $\mathcal{X}$, making this model an ideal test problem for LIGP. In this experiment we keep the same $\bar{N}=10000$ training set size as Section \ref{ss:syn_results}, but now use a fixed degree of 10 replicates at each location, a more common default design setup in the absence of external information about regions of high/low variability. We also keep a large $N'=10000$ testing set, which helps manage MC error in our out-of-sample metrics in this heteroskedastic setting. The experiment's results are displayed in Figure \ref{fig:sir_results}. The left panel's vertical axis shows the RMSE values between each method's mean predictions and the noisy testing observations. Variability across repetitions in the data generating mechanism looms large compared to the differences in RMSE values among the methods. Although RMSE/scores may look similar marginally, within each MC repetition there is a clearer ordering. To expose that, the left section of Figure \ref{fig:sir_results}'s table ranks the methods based on their RMSE (lowest/best first). The reported $p$-values are for one-sided paired Wilcoxon tests between a method's RMSE and the RMSE from the next best fit. Observe, for example, that LIGP.qNorm (blue $+$'s) produces a significantly lower distribution of RMSEs compared to the other models, with LIGP.wIMSE (purple $\times$'s) and HetGP (black circles) not far behind. \begin{figure*}[ht!] \centering \begin{subfigure}{.49\textwidth} \includegraphics[trim=0 0 20 20 , clip,width=\textwidth]{sir_rmse_vs_time.pdf} \end{subfigure} \begin{subfigure}{.49\textwidth} \includegraphics[trim=0 0 20 20 , clip,width=\textwidth]{sir_score_vs_time.pdf} \end{subfigure} \footnotesize \vspace{0.25cm} \begin{tabular}{|l r r|| l r r r|} Model & RMSE & $p$-value & Model & Score & $p$-value & Time\\ \hline LIGP.qNorm & 0.06156 & 0.0041 & LIGP.qNorm & 4.82 & 0.0031 & 16.2 \\ LIGP.wIMSE & 0.06156 & 0.6348 & LIGP.wIMSE & 4.819 & $<10^{-9}$ & 20.5 \\ HetGP & 0.06165 & $<10^{-8}$ & LAGP.NN ($n$=100) & 4.802 & 0.0288 & 122 \\ LAGP.NN ($n$=100) & 0.06186 & $<10^{-9}$ & HetGP & 4.796 & $<10^{-5}$ & 37.6 \\ LAGP.ALC ($n$=50) & 0.06217 & $<10^{-7}$ & LAGP.NN ($n$=50) & 4.773 & 0.7860 & 17.2 \\ LAGP.NN ($n$=50) & 0.06229 & & LAGP.ALC ($n$=50) & 4.772 & & 55.7 \\ \end{tabular} \caption{{\em Top:} RMSE (left) and score (right) vs.~log compute time over 30 MC repetitions for the SIR experiment. Median statistics are denoted with bold markers. {\em Bottom:} Median RMSEs (left) and scores (right) in ascending rank. The $p$-values are for one-sided paired Wilcoxon tests between the model and the model directly below. Median compute time (in seconds) for each model is listed in the last column. \label{fig:sir_results}} \end{figure*} Score (right panel) offers clearer distinctions between the methods, with LIGP besting LAGP and HetGP via paired Wilcoxon test. Using score as a metric highlights the differences in accuracy for the model estimates. By weighting the squared error by the predictive variance, not all errors of the same magnitude are considered equal (unlike in RMSE), which is crucial when modeling a heteroskedastic process. LIGP.qNorm and LIGP.wIMSE are statistically distinguishable from each other ($p$-value $< 0.01$) and better than LAGP.NN with $n=100$ ($p$-value $< 10^{-9}$), the next in the list. There is more variation in the computation times of the LIGP models compared to LAGP, which is likely due to LIGP's tendency to need more function evaluations for hyperparameter optimization. LIGP provides significant time savings despite an {\sf R} implementation. \subsection{Ocean oxygen concentration model} \label{ss:fksim} Here we consider a stochastic simulator modeling oxygen concentration deep in the ocean \citep{mckeague2005statistical}. This highly heteroskedastic simulator uses MC to approximate the solution of an advection-diffusion equation from computational fluid dynamics. There are four inputs: latitude and longitude coordinates, and two diffusion coefficients. The code required to run the simulation can be found in our repository. Inputs are scaled to the unit cube $[0,1]^4$; the output is the ocean oxygen concentration. \begin{figure*}[ht!] \centering \begin{subfigure}{.49\textwidth} \includegraphics[trim=0 0 20 20 , clip,width=\textwidth]{ocean_rmse_vs_time.pdf} \end{subfigure} \begin{subfigure}{.49\textwidth} \includegraphics[trim=0 0 20 20 , clip,width=\textwidth]{ocean_score_vs_time.pdf} \end{subfigure} \vspace{0.25cm} \footnotesize \begin{tabular}{|l r r|| l r r r|} Model & RMSE & $p$-value & Model & Score & $p$-value & Time\\ \hline LIGP.wIMSE & 4.3078 & 0.0759 & LAGP.NN ($n$=100) & -3.633 & 0.0502 & 199.8 \\ LAGP.NN ($n$=100) & 4.3135 & 0.0202 & LIGP.wIMSE & -3.641 & 0.0013 & 62.9 \\ LIGP.qNorm & 4.3137 & 0.0005 & LIGP.qNorm & -3.642 & $<10^{-4}$ & 34.8 \\ LAGP.ALC ($n$=50) & 4.3202 & $<10^{-9}$ & LAGP.ALC ($n$=50) & -3.673 & 0.0060 & 74.9 \\ LAGP.NN ($n$=50) & 4.4271 & 0.9725 & LAGP.NN ($n$=50) & -3.717 & $<10^{-5}$ & 20.2 \\ HetGP & 4.4230 & & HetGP & -3.842 & & 53.6\\ \end{tabular} \caption{{\em Top:} RMSE (left) and score (right) vs.~log compute time over 30 MC repetitions for Ocean Oxygen experiment. See Figure \ref{fig:sir_results} caption. \label{fig:fksim_results}} \end{figure*} We keep the same training/testing set sizes from the SIR experiment: $\bar{N}=10000$ with 10 replicates each and $N'=10000$. Figure \ref{fig:fksim_results} shows out-of-sample metrics similarly mirroring that experiment. At first glance, HetGP (black circles) is clearly worse (higher RMSEs, lower scores) than LIGP/LAGP. In 4d, using a subset of only 1000 unique locations does not provide enough information to model this surface. The variation in compute time for HetGP, due to challenges in modeling the latent noise, support this claim. Focusing on LIGP and LAGP results, we find LIGP again among the best in RMSE, score, and computation time. LAGP.NN with the larger neighborhood of $n=100$ (navy triangle) does well at modeling the mean and noise surfaces (its RMSE and score medians are comparable to the LIGP models), but takes nearly 6 times longer than LIGP.qNorm. HetGP (black circles) and LAGP.ALC (red diamonds) model the mean surface well, producing slightly worse RMSEs, but struggle with UQ as measured by proper score. \section{Bermudan Option Pricing} \label{sec:bermuda} An application of high-throughput stochastic simulation arises in computational methods for optimal stopping, which are particularly motivated by quantitative finance contexts. Several types of financial contracts -- the so-called American-type claims -- offer their buyer the option to exercise, i.e.,~collect, her contract payoff at any time until its maturity. Pricing and risk managing such a contract requires analysis of the respective optimal exercise strategy, such deciding when to exercise the option. Monte-Carlo-driven valuation of American-type claims consists of applying the dynamic programming formulation to divide the global dynamic control problem into local single-step optimization sub-problems. The latter revolve around partitioning the input space (interpreted as the underlying prices at the current time-step) into the \emph{exercise} and \emph{stopping regions}, to be learned by constructing a certain statistical surrogate. More precisely, one wishes to compare the $q$-value, namely the expected future payoff conditional on not exercising now, with the immediate payoff. While the latter is a known function, the $q$-value is specified abstractly as a recursive conditional expectation and must be learned. In the literature \citep{hetGP1,ludkovski2018kriging,ludkovski2020mlosp}, it has been demonstrated that GP surrogates are well suited for this emulation task, due to their flexibility, few tuning parameters, and synergy with sequential design heuristics. Nevertheless, their cubic scaling in design size $N$ is a serious limitation. The nature of the financial context implies an input space is 2-5 dimensional (1d problems are also common but are computationally straightforward) and a very low signal-to-noise ratio. Consequently, Monte Carlo methods for accurate estimation of the $q$-value call for $ N \gg 10^4$ simulations. \cite{ludkovski2018kriging} demonstrated that replication is pivotal to addressing this scaling challenge; \cite{lyu2022adaptive} explored adaptive replication. LIGP offers an additional boost by leveraging replication and local approximation, simultaneously addressing speed, accuracy and localization. Relative to existing surrogates LIGP brings several improvements. First, it overcomes limitations on the number of training simulations $N$. In previous experiments working with matrices of size $\gg 2000$ was prohibitively slow. This limited traditional GPs to data with dimension $d \le 3$ or excessive replication. Second, LIGP organically handles replicated designs that are needed to separate signal from noise, which is heteroskedastic and non-Gaussian in this application. Third, the localization intrinsic in LIGP is beneficial to capture non-stationarity. Typically the $q$-value is flat at the edges and has a strong curvature in the middle of the input space. Finally, the control paradigm implies that the surrogate is intrinsically prediction-driven -- the main use-case being to generate exercise rules along a set of price scenarios. Thus, the surrogate is to be evaluated at a large number of predictive locations and LIGP offers trivial parallelization that vastly reduces compute time relative to plain GP variants. \subsection{Illustrating the Exercise Strategy} We have added LIGP regressors as a new choice to the {\tt mlOSP} library \citep{ludkovski2020mlosp} for {\sf R}, which contains a suite of test cases that focus on valuation of American-type options on multiple assets. This allows benchmarking the LIGP module against alternatives, including plain GP and {\tt hetGP} solvers that are already part of {\tt mlOSP}. To fix ideas, we consider the $d$-dimensional Bermudan Max-Call with payoff function $$ h_\mathrm{MaxCall}(k,\mathbf{x}) = e^{-r k\Delta t}( \max_{i \le d} x_i - {\cal K})_+.$$ The parameter ${\cal K}$ is known as the strike, $r$ is the continuously compounded interest rate and $\Delta t$ is the exercise frequency measured in calendar time (e.g. daily, $\Delta t = 1/365$). The input space $\mathbf{x} \in \mathbb{R}^d_+$ represents prices $x_1, \ldots, x_d$ of $d$ stocks. Thus, the buyer of the Max-Call is able to collect $h_\mathrm{MaxCall}(k,\mathbf{X}(k\Delta t))$ dollars, the difference between the largest stock price and the strike, at any one of the $K$ exercise opportunities, $k=1,\ldots, K$. The choice of when to do so leads to $K$ decisions regarding whether to exercise the option at time step $k$ (assuming it was not exercised yet) or not. Thus, we need $K-1$ surrogates for the $q$-value $q(k,\mathbf{x})$, $k=0,\ldots,K-1$. The underlying stochastic simulator is based on generating trajectories of the asset prices. We stick to independent log-normal (Geometric Brownian motion) dynamics for the price of the $i^{\mathrm{th}}$ asset, \begin{align}\label{eq:gbm} dX_i(t) = (r - \delta_i) X_i(t) dt + \sigma_i X_i(t) dW_i(t), \qquad i=1,\ldots, d, \end{align} where $W_i(t)$ are independent standard Brownian motions, $\sigma_i$ is the volatility, and $\delta_i$ the continuous dividend yield of the $i$-th asset. This implies that given $X_i(s)$ for any $t>s$, $X_i(t)$ has a log-normal distribution. Denote by $\mathbf{X}_{k:K} = \mathbf{X}_{k\Delta t}, \ldots, \mathbf{X}_{K \Delta t}$ a realized trajectory of the $d$ asset prices on the interval $[k\Delta t, K\Delta t]$. The stochastic simulator yields empirical samples of $H_k(\mathbf{X}_k, \mathbf{X}_{k+1}, \ldots, \mathbf{X}_K)$ where the aggregate function $H_k$, representing the pathwise payoff, is a selector $$H_k(\mathbf{x}_k,\ldots,\mathbf{x}_K) = \left\{\sum_{s=k+1}^{K} h(s, \mathbf{x}_{s}) 1_{A_s}\right\}-h(k, \mathbf{x}_k),$$ and $A_k$ records the first pathwise exercise time along the given trajectory. The objective of learning the $q$-value at step $k$ is equivalent to regressing $H_k$ against $\mathbf{x}_k$ (exploiting the Markov property of the state dynamics) to obtain the so-called \emph{timing value} $\hat{T}_k(\mathbf{x}_k)$ and identify regions where the conditional mean is positive/negative. Note that this task must be done for \emph{each} time step $k=K-1,\ldots, 1$, and by construction the outputs at step $k$ depend on the $\hat{T}_{k+1:K-1}$'s fitted previously. This iterative estimation leads to non-trivial error back-propagation along the financial time dimension in $k$. Returning to the LIGP implementation, we have a sequence of surrogates that must be constructed. For each surrogate, we are given a data set of size $N$ with $\bar{N}$ unique inputs in $\mathbb{R}^d_+$ and a constant number of replicates $a$, $N = \bar{N} \cdot a$. For the experimental design we take an LHS on a user-specified sub-domain. After fitting the surrogate for $\hat{T}_k$, we need to predict on $N'=N$ unique outputs, which lie in the training sub-domain but are otherwise distinct from the training inputs. To illustrate how that looks, Figure \ref{fig:bermudan2d} compares global GP and LIGP fits for the timing value of the 2d Bermudan Max-Call option. The model parameters are ${\cal K}=100$, $r=0.05$, $\delta_1=\delta_2=0.1$, $\sigma_{1}=\sigma_{2} =0.2$, $T=3$ and $\Delta t = 1/3$ so that there are $K=9$ time periods. We display the fitted surrogates at one intermediate time step, $k=6$. In this problem, the option is out-of-the-money when both $x_1$ and $x_2$ are below the strike ${\cal K}=100$, hence the exercise strategy is to continue in that region and the latter (the white square in the bottom-left of each panel) is excluded from the surrogate prediction. For both problems, we have a randomized training set of $\bar{N} \approx 650$ inputs, with $a=25$ replicates each, created by a LHS design. The LIGP surrogate uses $m=10,n=50$, with estimated nugget and fixed lengthscale $\theta =1$. \begin{figure}[ht!] \centering \includegraphics[trim=0 0 0 20 , clip,width=.49\textwidth]{kmCall2d.png} \includegraphics[trim=0 0 0 20 , clip,width=.49\textwidth]{ligpCall2d.png} \caption{Fitted timing value and the corresponding exercise boundary (solid red curves) for the global GP (\emph{left}) and LIGP (\emph{right}) for the 2-d Max-Call problem at time step $k=6$. The colors indicate the fitted $\hat{T}_k(x_1, x_2)$ and the points the training inputs $\mathbf{x}=(x_1,x_2)$. The bottom left corner is excluded from the input space since it has zero payoff.} \label{fig:bermudan2d} \end{figure} The estimated strategy is to continue when the timing value $\hat{T}_k$ (color coded in both panels) is positive and to stop when it is negative, with the zero-contour (in red) demarcating the boundary of the stopping region. The stopping region consists of two disconnected components, in the bottom-right and upper-left; due to the symmetric choice of parameters, those regions (and the entire response) are symmetric along the $x_1=x_2$ diagonal. Thus, the response surface features a diagonal ridge with a global maximum around $(100,100)$ and two basins on either side. The height of the ridge and the depth of the basins change in $k$. The respective simulation variance is low in regions where $T_k(\mathbf{x}) \simeq 0$ and is high in regions where $|T_k(\mathbf{x})|$ is large. We emphasize that Figure \ref{fig:bermudan2d} is purely diagnostic; actual performance of the surrogate is based on the resulting estimated option price. The latter is obtained by generating a test set of $N'$ scenarios and using the collection of $K$ surrogates $\hat{T}_k$, $k=0,\ldots, K-1$ to evaluate the resulting exercise times and ultimately the \emph{average} payoff. Fixing a test set, the surrogate that yields a higher expected payoff is deemed better. Traditionally, a test set is obtained by fixing an initial $\mathbf{X}(0)$ and sampling $N'$ i.i.d.~paths of $\mathbf{X}_{0:K}$. For example, taking $\mathbf{X}(0) = (90,90)$ and using the surrogates displayed in Figure \ref{fig:bermudan2d} we obtain an estimated Max-Call option value of 8.02 via LIGP and 8.00 via the global GP. Note that this financial assessment of surrogate accuracy is not based on standard IMSE-like metrics, but is driven by the accuracy of correctly learning the exercise strategy, namely the zero-contour of $H_k$. Hence, the goal is to correctly specify the \emph{sign} of $T_k(\mathbf{x})$ which determines whether the option is exercised in the given state or not. Consequently, errors in the magnitude of $\hat{T}_k$ are tolerated, while errors in the sign of $\hat{T}_k$ will lead to degraded performance. \subsection{Results for Bermudan Option Pricing} The 2d example was primarily for illustrative purposes; for a more challenging case we take a 5d asymmetric Max-Call. We keep $T=3, \Delta t = 1/3, {\cal K}=100, r=0.05$ but adjust the parameters of the log-normal asset dynamics \eqref{eq:gbm} to be $\delta_1 = \ldots =\delta_5 = 0.1$ and $\sigma_i = 0.08 \cdot i$ to have different volatilities. The setting therefore is no longer symmetric and, due to larger variance, the third-through-fifth coordinates are progressively more important. The initial starting point is taken to be $\mathbf{X}(0) = (70,70,70,70,70)$. We benchmark the results on a fixed test set of $N' = 25000$ paths of $\mathbf{X}(t)$, comparing the resulting option price estimates. Our comparators include a global GP model {\tt homGP} and a {\tt hetGP} surrogate. Note that the above are not pre-scaled and take inputs as-is. We train the surrogates with an experimental design sampled from the log-normal density of $\mathbf{X}(t)$, with $\bar{N}=2000$ unique inputs and $a=10$ replicates each. In this case study we found that a relatively small number of inducing points $m=30$ works well along with a neighborhood size of $n=50$. We also left out various embellishments that can further fine-tune each surrogate, aiming for a level playing field. \begin{figure}[ht!] \centering \includegraphics[trim=0 0 0 0 , clip,width=.6\textwidth]{price_vs_model_v5.pdf} \caption{Results for the 5d Asymmetric Bermudan Max-Call. Distributions of price over 30 MC repetitions. Average compute time (mins) is below each box plot. All LIGP models (green) use the \texttt{qNorm} template. The default setting is $\bar{N}=2000,a=10,n=50$.} \label{tbl:bermudan5d} \end{figure} Figure~\ref{tbl:bermudan5d} presents the results, with the average compute times (in minutes) below each box plot. The reported compute time is for the entire option pricing problem, i.e., across $K=9$ surrogates. The reference option price is $11.83$ (black dashed line). With a design of $\bar{N}=2000$, all three approaches yield similar results that are close to optimal, but the compute times vary substantially. LIGP is more than four times faster than {\tt homGP} and an order of magnitude faster than {\tt hetGP}. In the problem context, methods that take more than a handful of minutes are impractical, and these major speedup gains greatly outweigh the small accuracy loss with LIGP. Not shown in Figure~\ref{tbl:bermudan5d} are the results from {\tt laGP}. Using LAGP.ALC with $n=50$ is prohibitively slow in this example (over an hour, like {\tt hetGP}), while using LAGP.NN yields very poor prices (below 11.5). Thus, {\tt laGP} fails either in terms of speed or in terms of accuracy and is not a viable alternative. Exploration of the input space tends to be the main driver of accuracy, so we consider upgrading to $\bar{N}=4000$ and $a=5$ replicates. This keeps the same budget for total number of simulations but is more exploratory. The new choice has minimal impact on the compute time of LIGP that is driven by $\bar{N} \times a$ and is to zeroth-order independent of $\bar{N}$. Indeed, the average compute times between $4000 \times 5$ (6.11 mins) and $2000 \times 10$ (6.26) are within 3\% of each other. On the other hand, $\bar{N} \gg 10^3$ is too large for a global GP: {\tt homGP} takes nearly three hours with $\bar{N}=4000$ and {\tt hetGP} is not considered as it takes even longer. Running times that exceed an hour (shown in red in Figure \ref{tbl:bermudan5d}) are prohibitive. A take-away here is that with a global approach one is restricted in the choice of $\bar{N}$, while LIGP has additional flexibility to survey the exploration-exploitation tradeoff. In this particular setting, having more unique inputs does not yield substantial performance improvement, but in related contexts it is a crucial factor for developing an accurate exercise strategy. \section{Discussion} \label{sec:discussion} Modern computing resources and advances in MC and agent-based modeling strategies have combined of late to produce large simulation campaigns for complex phenomena. The ability to adequately model such large data sets is limited, especially when the simulator is heteroskedastic. Methods for modeling large data sets exist, such as sparse matrix approximation and divide-and-conquer, but are easily fooled into interpreting noise as signal and provide inadequate UQ in the presence of input-dependent noise. Local approximations (LAGP) on local subsets of data (neighborhoods) perform well on predictive accuracy for deterministic data, because small local subsets yield a substantial computational advantage over competing methods. Scaling up to larger neighborhoods in the face of common replication-based design strategies for separating signal from noise is problematic in that context; larger neighborhoods wipe out that computational advantage. LIGP frees up resources through inducing points, and thus allow for increases in neighborhood size without severe computational bottlenecks, but is developed solely for deterministic data. HetGP was designed for heterogeneous noisy simulations, and replicated responses in the experimental design, and consequently makes thrifty use of sufficient statistics and provides excellent UQ. But it is not a local approximation, and so it does not scale well to the largest simulation campaigns. Here we provide upgrades to the LIGP framework, essentially by combining these three modern methods. We first redefine LIGP neighborhoods based on the number of unique design locations. Applying the common Woodbury identities allows us to take advantage of replication. This provides calculations on the order of the number of inducing points and unique locations. Consequently LIGP may entertain much larger neighborhoods compared to LAGP and the original version of LIGP. With these larger neighborhoods, we present evidence that LIGP is able to better, and more quickly, separate signal from noise. The promising results in this paper provide direction for further areas of study. While current work relies on NN to build local neighborhoods, variance-based alternatives (e.g., {\tt alcray} in {\tt laGP}, \cite{gramacy2016speeding}) may enhance modeling the mean surface. Extending the kernel support to other families such as Mat\'ern \citep{Stein2012} may also prove useful. Our empirical work relied on default choices of $(m,n)$ without much exploration. A better understanding of these hyperparameters (possibly through Bayesian optimization of out-of-sample RMSE or score) could yield better defaults for simple, immediate implementation. It is worth reinforcing every aspect of our local GP fits is unique to each local neighborhood, providing a discontinuous noise (and mean) surface. This is in contrast to global methods (e.g., HomGP, HetGP). We find that the computational and other model fidelity advantages of such a local approach outweigh the superficial disadvantages of a sometimes ``choppy'' predictive surface. That said, local-global approach where noise information is shared across neighborhoods \citep{edwards2021precision} could help smooth the noise across the input space. \section*{Acknowledgments} We would like to thank the journal editor and referees for their thorough review of this paper. They provided valuable insights and suggestions, helping improve the narrative and context of this work. The authors declare they have no conflict of interest. DAC and RBG recognize support from the National Science Foundation (NSF) Grant DMS-1821258. Ludkovski is partially supported by the NSF grant DMS-1821240. Many thanks to Andrew Cooper for help with proofreading. \bibliographystyle{jasa}
{'timestamp': '2022-06-01T02:03:47', 'yymm': '2109', 'arxiv_id': '2109.05324', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05324'}
arxiv
\section{Introduction} \label{sec:introduction} Supervised Deep learning (DL)\cite{sewak-overview-dl} models need plenty of task-specific labelled data to train. Collecting such a large corpus of labelled data can be challenging. Therefore, methods like Weak-Supervision (WS) \cite{snorkel} and Active-Learning (AL) \cite{AL-Survey} use either human-in-loop (HiL) or knowledge-base (KB) supports to generate sizable labelled data, are gaining traction. But the labels generated by these systems are very noisy, and hence not suitable for many critical applications; especially for use in security systems. Also, the HiL and KB supports are more relevant to domains/applications where human intuition/cognizance is considered as the gold-standard. But generating new labels may not be the only way to uplift the task-specific performance of any DL classification model. One example of this is the Transfer-Learning (TL) \cite{transfer-learning-survey} system. TL is used in many popular vision and transformer based DL models like the BERT \cite{bert}. In TL, most of the trainable parameters of a task-agnostic model are \textit{pre-trained} over a very large corpus of unlabelled data. Subsequently, a few task-specific layers of the model are \textit{fine-tuned} with (relatively) little labelled data. With this unsupervised pre-training approach, TL enables supervised DL models to outperform consistently non-TL models that are trained on similar sized labelled dataset. But TL remains a viable option only for domains like language and vision\cite{sewak-cnn}, where acquiring large unlabelled domains/application relevant data is rather inexpensive. For pre-training a Transformer based TL language models like the OpenAI’s GPT-3 \cite{GPT-3} or the Google's BERT \cite{bert}, billions to even trillions of (web) common-crawl documents could be easily and inexpensively made available. But in other domains, collecting such huge data corpus for pre-training may not be possible. Hence, TL could not gain popularity outside of such domains. One such domain where acquiring each data record is very expensive is \textit{security}, especially the area of malware detection. Such applications need malware data, and collection, analysis and validation of each unique malware record requires enormous investments. Hence, there exists no standardized malware dataset of the scale that could be used for pre-training under TL. For such domains, even the techniques like AL and WS are not useful, as for such applications, neither noisy labels are safe, nor could human intuition/cognizance be considered gold-standard. Therefore, in this paper, we present a novel data-scarce mechanism to achieve the objective of enhancing task-specific (supervised) classification performance under scarce-labelled data scenario. We call this mechanism as \textbf{DRo} (for \textit{\textbf{D}eep-\textbf{Ro}uting}). The DRo mechanism pre-determines which samples could be discriminated well by different downstream classifier in the network, and routes selective samples both for the training of and also for prediction from the different classifiers. Doing so, each model could fit better and faster during training and could be scored efficiently and effectively in production. The DRo mechanism is inspired by some of the very recent research developments in end-to-end (E2E) Deep Clustering (DC) \cite{DEC, imsat}. In particular, DRo exploits the self-augmented training (SAT) mechanism using synthetically generated local perturbations. The rest of the paper is organized as follows. We cover the background and motivation in section \ref{sec:background}, and some related work in section \ref{sec:related-work}. Then in section \ref{sec:proposed-model-architecture} we cover the mathematical and architectural details of the proposed model and mechanism. Next, we describe the experiments we conducted with the DRoID system in section \ref{sec:experiments}, and conclude the paper in section \ref{sec:conclusion}. \section{Background \& Motivation}\label{sec:background} In this section we first cover the mathematical basis of deep-clustering algorithms (subsection \ref{sec:clustering-algorithm} that are modified for the purpose of DRo. To prove the claims of the DRo mechanism, we propose an arduous challenge of making a worth classifier from a non-intuitive, non-enriched features, i.e. the Android implicit-intents. Therefore, next we describe these (subsection \ref{sec:intent}). \subsection{Deep Clustering: The Mathematical foundation of DRo}\label{sec:clustering-algorithm}\label{sec:dro-mathematics} Besides being extremely scalable, deep neural networks (DNN) are very flexible in representing complex non-linear decision boundaries. This makes DNN highly suitable for generating discrete representation of multi-dimensional data as required in clustering and hashing. But DNN are prone to over-fit owing to their high model complexity. In unsupervised learning since the target is not provided the problem is unconstrained, which further exacerbate the over-fit issue. Therefore such models require regularization to attain invariance against minor perturbations atypical to application domain to learn meaningful representations. IMSAT \cite{imsat}, one of the recent algorithms in the actively researched area of Deep Clustering currently (refer section \ref{subsec:relatedwork-deep-clustering} for other deep clustering algorithms and their evolution), uses Self Augmented Training (SAT), a mechanism that uses synthetically generated local perturbations from original data samples and rewards their predicted representation to be closer to the representation of the actual data from which the perturbation was generated. It further use a regularization coefficient $\lambda$ to weigh the SAT regularization penalties. Besides using the SAT penalties to provide regularization, IMSAT also use the (Regularized) Information Management (RIM) criteria \cite{NIPS-Regularized-Information-Maximization, NIPS-MI-Phantom-Targets} to ensure that the generated representation are meaningful clusters. RIM uses a stochastic classifier ($p_{\theta}$) for cluster predictions and rewards its cluster prediction outcomes such that the mutual information amongst the samples in a given cluster is maximized \cite{NIPS-Regularized-Information-Maximization}, while also simultaneously regularizing the classifier complexity. RIM minimizes the objective as in equation \ref{eq: rim-objective}, where, $X \in \mathbf{X}$ are the data samples, $Y \in \mathbf{Y} \equiv \{0, ..., {K-1}\}$ are the cluster assignments (for $K$ clusters), $\mathcal{R}_\theta$ is the regularization penalty, and $\mathbf{I} (\mathbf{X};\mathbf{Y})$ is MI between data samples and cluster assignments, \begin{equation}\label{eq: rim-objective} \mathcal{R}_\theta - \lambda \mathbf{I} (\mathbf{X};\mathbf{Y}) \end{equation} Considering multi-dimensional data, the RIM could be expressed as $p_{\theta}(y_1,..., y_m|x)$ by DNN. Assuming that the data dimensions are conditionally independent, the joint probability could be expressed as a product of individual conditional probabilities as in equation \ref{eq: multi-dimension}. \begin{equation} \label{eq: multi-dimension} p_{\theta}(y_1,..., y_m|x) = \prod_{m=1}^{M} {p_{\theta}(y_m|x)} \end{equation} If $T : \mathbf{X} \longrightarrow \mathbf{X}$ is the transformation function that generates the local perturbations (data augmentation) to ensure invariance, the SAT regularization penalty for the predictions $p_{\hat\theta}(y_m|x)$, generated by a network with parameter $\hat \theta$, for the original data point $x$ augmented with perturbations $T(x)$ could be expressed as equation \ref{eq: sat}. \begin{equation} \label{eq: sat} \begin{aligned} \mathcal{R}_{SAT}(\theta; x, T(x)) = \\ - \sum_{m=1}^{M} \sum_{y_m=0}^{V_m-1} p_{\hat\theta}(y_m|x)\log p_{\theta}(y_m|T(x)) \end{aligned} \end{equation} Similarly SAT penalty for the entire dataset $\mathbf{X} (x \in \mathbf{X})$ is the average of individual $\mathcal{R}_{SAT}(\theta; x, T(x))$, and is given as in equation \ref{eq: rsat-averaging}. \begin{equation} \label{eq: rsat-averaging} \mathcal{R}_{SAT}(\theta;T) = \frac{1}{N} \sum_{n=1}^N \mathcal{R}_{SAT}(\theta; x_n, T(x_n)) \end{equation} If $r$ is a small perturbation that does not alter the meaning of the data point for the given context, then in the simplest form, an illustrative augmentation function could be expressed as $T(x)=x+r$. Regularization against such small, local perturbations, $r$, enforces local-invariance in the data-representations, and hence ensures that the cluster-separation boundaries lie in the region where data-distribution-density is relatively low. Such cluster-separation-boundaries adhere to the low-density-separation principle and are hence preferable. IMSAT use a more sophisticated data augmentation method, called the Virtual Adversarial Training (VAT), in which the local-perturbation $r$ is computed in an adversarial setting \cite{Distributional-Smoothing-Virtual-Adversarial}. This is given in equation \ref{eq: r-vat}. \begin{equation}\label{eq: r-vat} r=\argmax_{r\prime}{R_{SAT}(\theta;x,x+r\prime); \vert\vert r\prime \vert\vert_2 \leq \epsilon} \end{equation} If $H(Y)$ is the marginal-entropy (ME) of the data (as expressed in equation \ref{eq: marginal-entropy}), and $H(Y|X)$ is the conditional-entropy (CE) of the cluster-assignments of the data given the features (as expressed in \ref{eq: conditional-entropy}), the MI gain due to \textit{clustering} could expressed as a difference between ME and CE \cite{book-information-theory}. Therefore the total loss $Loss_{total}$ as a function of loss due to regularization $Loss_{R_{SAT}}$ and loss due to clustering (negative information gain), as moderated by the coefficient $\lambda$, could be given as in equation \ref{eq: total-loss}. \begin{equation}\label{eq: total-loss} Loss_{total} = Loss_{R_{SAT}}-\lambda{H(Y)-H(Y|X)} \end{equation} \begin{equation}\label{eq: marginal-entropy} H(Y) \equiv h(p_\theta(y)) = h(\sum_{i=1}^N p_\theta(y|x)) \end{equation} \begin{equation}\label{eq: conditional-entropy} H(Y|X) \equiv \frac{1}{N}\sum_{i=1}^N h(p_\theta(y|x)) \end{equation} where $h(p(y)) \equiv -\sum_{y\prime} p(y\prime) log p(y\prime)$ is the entropy function. Since increasing the ME could enforce the cluster sizes to be uniform, while decreasing the CE could enforce unambiguous cluster assignments \cite{NIPS-MI-Phantom-Targets}, we add an extra parameter $\mu \in \mathbb{R}$ in DRo to further tune the CE in the \textit{`DRoID' or `Vault'} mode (figure \ref{fig:ids-vault-architecture}) settings. So the DRo's loss could be calculated as in equation \ref{eq: mu}. \begin{equation}\label{eq: mu} Loss_{clustering} = - (H(Y) - \mu H(Y|X)) \end{equation} \subsection{Android \textit{Implicit} Intent}\label{sec:intent} Android OS is a sophisticated eco-system of multiple apps that in aggregation work to provide a great user-experience and enhance productivity of both the end-consumer and the app-developers. Because of a mechanism called Intent, the app-developers could modularise their code into components, where each component could be coded to perform a few closely tied activities. The app could call other components to perform any ancillary functionality that the developer does not intend to code in a particular component. If the required component is pre-defined by the developer these could be declared as explicit-intent within the code, and could be sent to the Android system for execution during run-time. Alternatively, if these components are not pre-defined by the developer, these are sent to the Android system as a general intent for which the Androids systems need to first discover all apps that have a component that could effectively fulfill such an intent. Any app that can handle any type of implicit-intent, states the activities that it could fulfil in an implicit-intent filter in its readily discoverable implicit-intent \textit{xml} file. There could be multiple applications that could declare the same activity in their implicit-intent filter. In such a scenario, the Android system creates an interrupt for the user to select the best desired app to fulfil that intent if any app has not been set as default by the user, or the system. A very intuitive example of this is browsing activity. When a user clicks an URL in an app that cannot handle browsing activity, the browsing intent is sent to the Android system, which in turns finds the apps that could open the URL, e,g, browser. If there is over one browser installed in the system, then Android creates a pop-up for the user to choose a specific browser. Unlike Android-permissions, which are under the control of a malicious app developer to request and to execute, the implicit-intents could only be declared by the app-developer. Which application could call them, and if at all these are called, and if called, if the user selects the specific app to execute it are not in the app developers control and hence counter-intuitive to be used by a malware developer. Hence the implicit-intent, though are easy-to-extract, may not offer very rich features for designing a malware classifier. We cover more on this aspect in section \ref{sec:related-work}. \section{Related Work} \label{sec:related-work} Since DRo is mathematically inspired from developments in Deep Clustering, and we validate its claims by implementing it in an online mobile IDS that use low-information static features (like the Android Intent), so we present the related work corresponding to both of these aspects and accordingly split this section into two sub-sections as follows. \subsection{Related Work in the area of Deep Clustering} \label{subsec:relatedwork-deep-clustering} In the last 3 to 4 years, E2E DL for generating a discrete representation of data (clustering and hashing) has gained a lot of traction in research fraternity and different algorithms have been proposed that have been proposed to this end. Such discrete representation could be for clustering or hashing. When Deep Learning is used for clustering, we call it Deep Clustering (DC). Many of the conventional and popular \textit{representative} clustering and hashing algorithms like Gaussian Mixture Modeling (GMM) and K-Means are incapable of modelling non-linear boundary separation between clusters. Others like the \textit{kernel} \cite{NIPS-Maximum-Margin-Clustering, NIPS-Binary-Reconstructive-Embeddings} and \textit{spectral} \cite{NIPS-Spectral-Hashing} clustering-based techniques though can model arbitrary cluster boundaries, but are not scalable to large datasets. Here is where DC shines as it model non-linear and complex separation boundaries and is extremely scalable and flexible. Many of the recent algorithms in this field are also capable of producing data embeddings along with the cluster representations. Deep Embedding for Clustering (DEC) \cite{DEC} was the first DC algorithm that could simultaneous generate embedding and clustering representations. DEC did not use generative or variational augmentations of data for regularization. Other similar approaches for generating adversarial robustness were proposed by \cite{variational-deep-embedding}\cite{sewak2020doom}\cite{rathore2020robust}. In these approaches, the data is modelled by a \textit{generation} process, and they use GMM as prior distributions for deep generative models. This approach is atypical to data generation using variational AE. Leen \cite{DL-Regularization-Invariant-Learning} proved that applying data augmentation to a DL classifier gives similar effect as applying regularization to the original cost function of a conventional machine learning (ML) classifier. Miyato et al.\cite{Distributional-Smoothing-Virtual-Adversarial}, and Sajjadi et al.\cite{NIPS-Perturbations-Regularization} successfully adapted this approach to semi-supervised DL algorithms and demonstrated successful results. SAT is inspired by this approach of regularization. Dosovitskiy et al.\cite{NIPS-Discriminative-Unsupervised-Feature-Learning} proposed to use data augmentation to model the invariance of learned representations in even unsupervised algorithms like clustering. IMSAT takes similar approach, but applies invariance directly to the learned representation instead of applying it on the surrogate classes, and directly learns discrete representations (clusters), instead of learning continuous representations that are later converted to discrete class-predictions or cluster-assignments. \subsection{Related work on Android IDS and Android Intent features} \label{subsec:relatedwork-intent} Most personal edge-devices, like smartphones, have two things in common, Android OS and a mandate for battery-efficient endpoint protection platform (EPP). Therefore, besides signature-matching, these devices essentially rely on simple static features for malware detection. Thus, Android-permissions is an actively researched feature for Android EPP. One work \cite{PScout} on analysis of this feature shows that variance in specification vs. usage of the documented Android APIs. This inspired many work that use these features for Android EPP; one such example is Lindorfer et al. ‘s ANDRUBIS \cite{ANDRUBIS}. In this work, the researchers discovered that the malicious vs. non-malicious applications have slightly distinct patterns of using permissions, and the malicious apps requests for many extra permissions than their non-malicious counterparts. Other researchers have found using Android-permission for making machine-learning classifiers either in isolation (\cite{li-permission}\cite{rathore2020identification}), others have used it in combination with other, computationally more expensive features like opcodes (\cite{rathore2018android}\cite{rathore2020detection}, \cite{Intent-Permission-Idrees}), or multiple other features like API-calls and Android-components (\cite{DroidSieve}) and achieved better performance. Opcodes though are static features, but are more-computationally expensive to extract. API-calls, on the other hand,a are dynamic features, and are best extracted offline via a cloud based service. Android-implicit-intent, though co-exists with Android-permissions in the manifest but still few researchers have used it. One work that uses Android-intent, although with other complex dynamic and static features, is by Wu et al. \cite{DroidMat}. Another work by Arp et al. \cite{arp-drebin}, besides using most of the above covered complex features, also leveraged network address, to maximize on the feature-set and hence the result. The reasoning for using Android-intent here seems to leverage its efficiency to make an efficient production-ready system but to maximize on the theoretical feature availability. The only system that uses only Android-intent is by Ali et al. (\cite{AndroDialysis}). But the work was more inspired to use Android-intent as a theme, therefore they also extracted the Android-explicit-intents, which is almost similarly more involved as other complex features discussed in other works. Through Android-implicit-intent is as easy to extract as Android-permissions, it is hard to find any work that uses these as exclusive features for designing an efficient and effective edge or cloud EPP. But as illustrated in a recent work by Sewak et al. (\cite{sewak-pimrc-deepintent}), this is, however, not completely counter-intuitive. Sewak et al. used both an analysis approach and a DL classifier approach to investigate the usefulness on Android-implicit-intent features for malware-detection. They acknowledged that using the features in isolation was challenging and hence they intent to create a baseline for these features (instead of using these in isolation in a production-ready system). They used very sophisticated e2e DL architectures to do malware classification using Android-implicit-intent features only. Though the intention of their work was not to use the Android-implicit-intent features in isolation for an EPP, but the idea is not without its merit given the efficiency requirements for edge-device. Therefore, we believe this quest provides the best scenario to test the claims of the DRo system. \section{Proposed Model \& Architecture}\label{sec:proposed-model-architecture} In this section we cover an illustrative architecture for implementing a DRo based system like DRoID in subsection \ref{sec:dro-architecture}. Next we cover the advantages and limitation of the DRo system based on this architecture in subsection \ref{sec:dro-advantages}, and the process pre-processing the dataset for DRoID in subsection \ref{sec:data-preprocessing}. \subsection{Architecture of a DRo based systems}\label{sec:dro-architecture} Though, DRo could be used in any field, one domain where it may become indispensable is security, especially for enhancing the performance of Malware/Intrusion Detection Systems (MDS/IDS). The recent research trends in IDS indicate the shift towards using data hungry DL models \cite{rathore2018malware}, where the application of DRo can be revolutionary. Modern IDS, especially the ones used in mission-critical applications, often use layered analysis. In such layered IDS, the online classifier works on efficient, and cost-effective static features. Such IDS may also have a secondary, and more costly detection-mechanism in the form of a dynamic analysis layer. In such layered/hybrid IDS, costlier dynamic analysis is applied only to the samples that are not optimally covered (not classified, or classified with insufficient confidence) by the online classifier. The DRo mechanism when used to augment such an IDS, could automatically route the incoming file samples either to the online classifier or to a \textit{Vault} which could serve as a queue mechanism for the dynamic analysis scheduler and processor. We call such an implementation of DRo as \textit{DRoID} (\textbf{DRo} for \textbf{I}ntrusion \textbf{D}etection). The architecture for such an atypical DRoID system is shown in figure \ref{fig:ids-vault-architecture}. The algorithm algorithm/pseudo-code for training a DRo based system is as provided in algorithm \ref{alg:experimental-algo}) \begin{figure*}[!htbp] \centering \includegraphics[width=\textwidth]{pictures/DRo_architecture_vault_modified_v2.pdf} \caption{ Architecture of a DRo based Malware Detection, Protection \& Management System for Mobile \& Embedded devices.} \label{fig:ids-vault-architecture} \end{figure*} \begin{algorithm}[hbp!] \footnotesize \caption{Algorithm for Training a DRo based system}\label{alg:experimental-algo} \textbf{Input:} \\ $\mathbf{\lambda}$: trade-off parameter between Re-constitution error and Clustering Loss \\ $\mathbf{\mu}$: multiplier for Conditional Entropy Loss \\ $\mathbf{e}$: Number of training epochs \\ $\mathbf{T}$: set of training sample \\ $\mathbf{V}$: set of validation sample \\ $\mathbf{C}$: set of malware detection models \\ \textbf{Function} : \\ $\mathbf{C_P}$: prediction function in classification models trained on P\\ $\mathbf{F_m}$: feature vector modification function \\ $\mathbf{R}$: routing clustering function \\ \textbf{Output} : ${Sample (s_g, n_c, c)}$\\ $\mathbf{N_c}$: route-cluster assignment of the candidate sample\\ $\mathbf{L_{v}}$: reconstitution loss \\ $\mathbf{L_{routing}}$: routing/ clustering loss\\ $\mathbf{L_{total}}$: total loss\\ $\mathbf{E_m}$: Embedded dimension of $E_{layers}-1$ of Encoder\\ $\mathbf{Lift_a}$: Router accuracy lift for r=1\\ \begin{algorithmic}[1] \State $a_{benchmark} \leftarrow C_T(V)$ \State $N_{routes} \leftarrow 2$ \Comment{r<-0 indicates ambiguity and r<-1 indicated dis-ambiguity} \For{each epoch in [1, e]} \For {each batch b $\mathbf{\in}$ T} \State $L_{mi} \leftarrow E(Y) - \mu \times {E(Y | X)}$ \State $L_{total} \leftarrow L_{v} + \lambda \times L_{mi}$ \State $W_t = W_{t-a} - \alpha \times (\delta L_{total})$ \EndFor \EndFor \For{each batch b $\mathbf{\in}$ T} \State $r \leftarrow R^t(b)$ \State ${f = F_m^t(b)}$ \If {${(r == 1)}$} \State ${C_T = C(f,b)}$ \Else \State route sample to alternative-analysis/ vault \EndIf \State ${a_b \leftarrow N(C_T(V_b)==Y(V_b))/N(b)}$ \EndFor \State ${a_{deeprouter} \leftarrow average(a_{b1},...,a_{bn})}$ \State ${Lift_a \leftarrow a_{deeprouter} - a_{benchmark}}$ \end{algorithmic} \end{algorithm} \raggedbottom To put DRo/DRoIDs claims to test, we take an extreme example. We build a mobile IDS using the DRoID architecture, and in it we use the Android \textit{Implicit Intent} features \ref{sec:intent} alone. These features are not considered very insightful for developing an IDS \cite{sewak-pimrc-deepintent}, and hence no IDS exist (beyond benchmarks) that use these features in isolation \cite{sewak-pimrc-deepintent}. From the experiments conducted on DRoID using a popular and standard Android malware (\textit{Drebin}) dataset \cite{arp-drebin}, we found that the DRo mechanism could successfully reduce the \textbf{false-alarms} generated by the downstream classifier by up to $\mathbf{67.9\%}$, while also simultaneously boosting its \textbf{accuracy} by $\mathbf{11.3\%}$. To the best of our knowledge, this quantum of enhancement to an existing IDS classifier (especially without re-training the classifier or using additional auxiliary data) is unheard of in any available public literature. Hence, this extreme and challenging illustration provides utmost credibility to the claims of the DRoID system and the DRo mechanism. \subsection{Advantages \& Limitations of DRo} \label{sec:dro-advantages} Unlike TL, DRo does not replace/substitute an existing classifier, but could alternatively be used to augment it. This is a very significant and revolutionary shift, as because of this, DRo could even be retrofitted to any existing classification system, and does not mandates a redesign and retraining of the system. There are several other advantages that DRo offers over TL, these are enumerated next. \begin{enumerate} \item Where TL is incompatible with existing DL/ML classifiers, and mandates to replace them for any incremental performance improvements, DRo aims to augment an existing classification system, and does not mandate any changes to an existing classifier, not even re-training it. \item Unlike TL, DRo can be developed and re-trained independent of the task-specific model. \item DRo is based on deep-clustering architectures which have a much smaller model foot-print and hence are economical to train than their TL counterparts. \item DRo can also work on much simpler features than that used by the classifier (refer section \ref{sec:intent}). Coupled with smaller size, DRo based systems offer easy and efficient online deployment opportunities, without mandating distillation. \label{dro-adv:simpler-features} \item DRo does not require (large) corpus of un-labelled data. It can even work on the same task-specific labelled dataset as the task-specific model and yet improve its performance. \item DRo can be retrofitted to any existing task-specific model without mandating it to be re-trained or even (re-)fine-tuned. \item DRo offers on-demand coupling, where if required the feedback from the task-specific model can be served to improve DRo (fig: \ref{fig:ids-vault-architecture}). \item The on-demand coupling also work in the reverse direction, where the output from DRo can also be optionally served as input to the downstream model (fig: \ref{fig:ids-vault-architecture}) \label{dro-adv:reverse-on-demand-coupling}. \item DRo can uplift a model's performance (Table:\ref{table:experiments-lam-acc}), and also influence the accuracy-FPR balance of a downstream classifier without re-training the model or altering any of its parameters. \end{enumerate} These benefits come at a cost of reduced coverage for classification for a system augmented with DRo. This aspect may look like a shortcoming prima-facie, but is actually an added advantage. For systems which need to capture noisy data so as to augment the classification system, this aspect is an added advantage as this process is automated by DRo. For systems that favors, coverage over false-alarms, the reduced coverage records could still be used with \textbf{known} classification limitations for those records, a feature that any standard classifier cannot offer by default. \subsection{Dataset and its Pre-Processing} \label{sec:data}\label{sec:data-preprocessing} We use a very popular standardized Android malware dataset \textit{`Drebin’} dataset\cite{arp-drebin} for our experiments. This is an old and had been an actively researched dataset in the past, and hence we assume that maximum performance that could be derived from this dataset is available in the literature. As opposed to producing benchmarks on an under-explored dataset, we prefer using such adequately explored dataset to ensure that the improvement achieved rightly attribute credibility to DRo mechanism and not application of a different classifier-parameter setting or any different feature-extraction technique. The dataset contains $\approx 5,000$ malicious apk samples across $20$ different families. Therefore, to balance this positive dataset, we collected similar sized negative dataset, and verified that each sample of the negative dataset in non-malicious using the ensemble classification from the \textit{VirusTotal} utility. From each of the collected sample, we extracted their respective `manifest.xml’ (manifest) file using the open-source \textit{APKTOOL} utility. Next, we parsed the manifest using a custom-utility to extract all implicit-intents as declared under the intent-filter section in the manifest file and mapped them to one of $273$ unique Android-implicit-intent types. Next, using these raw features we trained a series of benchmark classifiers without the DRo. The same dataset was also used for experiments with the best benchmark classifier, augmented with DRo for comparison. This entire process is summarized in figure \ref{fig:data-process}. \begin{figure}[htb!] \centering \includegraphics[height=\textheight]{pictures/dro_data_processing.pdf} \caption{Data Collection and Processing} \label{fig:data-process} \end{figure} \section{Experiments and Results} \label{sec:experiments}\label{sec:results} To establish the improvement that could be attributed to the DRo mechanism, we conducted experiments in 2 series. In the first series of experiment, we benchmark the performance of an atypical (\textit{`existing'}) IDS classifiers that have provided leading results in the work covered in section \ref{subsec:relatedwork-intent}. In the next section, we repeat the experiments with DRo enabled DRoID on the same dataset and the `same' classifier. The baseline models whose performance were bench-marked in the first series are shown in table \ref{table:experiments-benchmark}. In this benchmark the Random Forest (RF) provided the best results. To eliminate chances of any bias in favor of DRo, we use this `best' bench-marked classifier as the baseline performance, and hence we will be using this configuration as a downstream classifier to compare the different configuration of DRoID. As indicated in figures \ref{fig:ids-vault-architecture}, and advantage \ref{dro-adv:reverse-on-demand-coupling}, the features generated from the DRo could be shared with the downstream classifier, but to avoid any positive bias in favor of DRo arising from the inclusion of these richer features, we use the best benchmark-ed classifier (RF) \textit{as-is} on raw (sparse) features only. Also as per figure \ref{fig:data-process} several experiments were carried with different configuration (and 2 setups) of the DRoID. Each of these experiments followed the algorithm \ref{alg:experimental-algo}. \begin{table}[hbp!] \small \begin{center} \begin{tabular}{|c|c|c|c|} \hline \textbf{B.ID.} & \textbf{Algorithm} & \textbf{Accuracy} & \textbf{FPR} \\ \hline \textbf{B1} & \textbf{Random Forest} & \textbf{0.777} & \textbf{0.106} \\ B2 & AdaBoost & 0.761 & 0.127 \\ B3 & 1-L MLP-DNN & 0.741 & 0.116 \\ B4 & 2-L MLP-DNN & 0.745 & 0.138 \\ B5 & 3-L MLP-DNN & 0.752 & 0.111 \\ B6 & 4-L MLP-DNN & 0.772 & 0.11 \\ \hline \end{tabular} \caption{Baseline classifier performance without DRo} \label{table:experiments-benchmark} \end{center} \end{table} Table \ref{table:experiments-lam-losses} and \ref{table:experiments-mu-losses} are conducted with the same classifier as assisted with the DRoID system (fig: \ref{fig:ids-vault-architecture}). In these configurations DRoID is fine-tuned mathematically to alter its available adjustable parameters (refer section \ref{sec:dro-mathematics}). The tables \ref{table:experiments-lam-losses} indicates the effect of varying the regularization parameter $\lambda$. The results indicates that keeping the value pf $\mu$ constant (at 4) a good balance between lower $Loss_{total}$, higher $H(Y|X)$ (or lowest $-H(Y|X)$) and lower $R_{SAT}$ could be reached at $\lambda=0.4$. At any value of $\lambda > 0.4$ CE is almost $0$. Though values of $\lambda < 0.4$ could also be considered. \begin{table}[hb!] \begin{center} \begin{tabular}{|c|c|c|c|c|c|} \hline \textbf{\begin{tabular}[c]{@{}c@{}}Conf. \\ ID\end{tabular}} & $\mathbf{\lambda}$ & $\mathbf{\mu}$ & $\mathbf{L_{total}}$ & $\mathbf{H(Y|X)}$ & $\mathbf{R_{SAT}}$ \\ \hline 1 & 0 & 4 & 0.132 & 0.152 & 0.132 \\ 2 & 0.1 & 4 & -0.228 & 0.002 & 0.049 \\ 3 & 0.2 & 4 & -0.482 & 0.001 & 0.071 \\ 4 & 0.3 & 4 & -0.755 & 0.001 & 0.074 \\ 5 & \textbf{0.4} & 4 & \textbf{-1.018} & \textbf{0.001} & \textbf{0.086} \\ 6 & 0.5 & 4 & -1.318 & 0 & 0.066 \\ 7 & 0.7 & 4 & -1.902 & 0 & 0.036 \\ 8 & 0.8 & 4 & -2.161 & 0 & 0.054 \\ 9 & 0.9 & 4 & -2.449 & 0 & 0.043 \\ 10 & 1 & 4 & -2.713 & 0 & 0.055 \\ \hline \end{tabular} \caption{Configurations and Losses with different values of $\lambda$} \label{table:experiments-lam-losses} \end{center} \end{table} To validate these findings and identify a specific value of $\lambda$, we conduct experiments with layered DRoID with hybrid online-classifier and dynamic-analysis. Table \ref{table:experiments-lam-acc} shows these results. Here route $C1$ belongs to the online downstream (baseline) classifier. Route $C0$ indicated to the Vault in \textit{Vault} mode, in which we have put another similar classifier to mimic the dynamic-analysis mode to assess the dis-ambiguity in both the routes. The classifiers used for the assessment (RF) and the associated features (raw, sparse, \textit{implicit} Intent(s)) are the same as indicated in the benchmark setup. These results validate that the regularized \textit{configuration-5}, with \textit{$\lambda=0.4$} provides the best result for the constant $\mu$. In this configuration, $51\%$ of the data sample flows into the route where the (baseline) classifier was, and this data could be unambiguously classified with much better accuracy of $86.5\%$ as compared to $77.7\%$ (boost of $\mathbf{11.3\%}$) and even better FPR of $0.034$ as compared to $0.106$ (reduction in false alarms by $\mathbf{77.7\%}$) of the best baseline/benchmark classification. The results also indicate that the samples in the $C0$ route could not be classified decently, hence validating that these were ambiguous and hence correctly sent to the vault for dynamic-analysis in a layered IDS. \begin{table}[hb!] \begin{center} \begin{tabular}{|c|c|c|c|c|c|} \hline \textbf{\begin{tabular}[c]{@{}c@{}}Conf. \\ ID\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}Ratio \\ C0:N\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}C0 \\ Acc.\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}C0 \\ FPR\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}C1 \\ Acc.\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}C1 \\ FPR\end{tabular}} \\ \hline 1 & 0.32 & 0.849 & 0.176 & 0.722 & 0.176 \\ 2 & 0.5 & 0.689 & 0.032 & 0.856 & 0.032 \\ 3 & 0.5 & 0.687 & 0.033 & 0.857 & 0.033 \\ 4 & \textbf{0.49} & 0.685 & 0.032 & \textbf{0.861} & \textbf{0.032} \\ 5 & \textbf{0.49} & 0.68 & 0.034 & \textbf{0.865} & \textbf{0.034} \\ 6 & 0.54 & 0.406 & 0.838 & 0.858 & 0.838 \\ 7 & 0.54 & 0.406 & 0.838 & 0.859 & 0.838 \\ 8 & 0.54 & 0.405 & 0.837 & 0.857 & 0.837 \\ 9 & 0.54 & 0.406 & 0.837 & 0.861 & 0.837 \\ 10 & 0.54 & 0.406 & 0.837 & 0.858 & 0.837 \\ \hline \end{tabular} \caption{Coverage ($1 - {Ratio\frac{C0}{N}}$) and Classifier Performance (C1 Acc., C1 FPR) with different values of $\lambda$ in a layered/hybrid IDS} \label{table:experiments-lam-acc} \end{center} \end{table} Next, we freeze the value of the parameter $lambda$ at $lambda=0.4$ as obtained from the earlier results and altered the value of parameter $\mu$. The parameter $\mu$ is altered to provide a varying degree of trade-off between the accuracy and false-alarms (FPR) of the classifier in route $C1$. Table \ref{table:experiments-mu-losses} shows these experiments and indicates that even for a constant value of CE $H(Y|X)$ the value of $L_{total}$ increasing with higher $\mu$ multipliers for the CE. The implications of these changes could be seen when similar configurations are viewed in \textit{Layered/Hybrid-IDS} mode as shown in table \ref{table:experiments-mu-acc}. \begin{table}[htb] \begin{center} \begin{tabular}{|c|c|c|c|c|c|} \hline \textbf{\begin{tabular}[c]{@{}c@{}}Conf. \\ ID\end{tabular}} & $\mathbf{\lambda}$ & $\mathbf{\mu}$ & $\mathbf{L_{total}}$ & $\mathbf{H(Y|X)}$ & $\mathbf{R_{SAT}}$ \\ \hline 11 & 0.4 & 1 & -0.205 & 0.001 & 0.071 \\ 12 & 0.4 & 3 & -0.746 & 0.001 & 0.083 \\ 13 & 0.4 & 5 & -1.285 & 0.001 & 0.095 \\ 14 & 0.4 & 7 & -1.846 & 0.001 & 0.089 \\ 15 & 0.4 & 9 & -2.415 & 0.001 & 0.077 \\ \hline \end{tabular} \caption{Configurations and Losses with different values of $\mu$} \label{table:experiments-mu-losses} \end{center} \end{table} This result demonstrates that as $\mu$ is increased initially we could strike a trade-off between better accuracy at the cost of greater FPR. Increasing $\mu$ even further deteriorates both accuracy and FPR. Configuration-11 provides slightly lower accuracy while decreasing false alarms. Whereas, Configuration-11 raises the FPR slight to improve upon the accuracy. Anyone of the configurations could be selected depending upon the domain requirement. \begin{table}[hb!] \begin{center} \begin{tabular}{|c|c|c|c|c|c|} \hline \textbf{\begin{tabular}[c]{@{}c@{}}Conf. \\ ID\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}Ratio \\ C0:N\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}C0 \\ Acc.\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}C0 \\ FPR\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}C1 \\ Acc.\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}C1 \\ FPR\end{tabular}} \\ \hline \hline 11 & 0.48 & 0.684 & 0.017 & \textbf{0.859} & \textbf{0.017} \\ 12 & 0.49 & 0.686 & 0.032 & \textbf{0.864} & \textbf{0.032} \\ 13 & 0.49 & 0.683 & 0.034 & 0.855 & 0.034 \\ 14 & 0.49 & 0.683 & 0.034 & 0.857 & 0.034 \\ 15 & 0.5 & 0.689 & 0.034 & 0.852 & 0.034 \\ \hline \end{tabular} \caption{Coverage ($1 - {Ratio\frac{C0}{N}}$) and Classifier Performance (C1 Acc., C1 FPR) with different values of $\mu$ in a layered/hybrid IDS} \label{table:experiments-mu-acc} \end{center} \end{table} \section{Conclusion} \label{sec:conclusion} In this paper we proposed DRo, a novel data-scarce alternative to TL, WS, and AL for enhancing performance of supervised DL models under scarce-label scenario. DRo neither requires a large corpus of unsupervised data that is required for pre-training in TL; nor does it require human-judgement or generates noisy-labels as with WS or AL. Further, to implement DRo no changes to or re-training of the existing classifier is required and it is also more efficient to train and infer a classifier with DRo. We benchmarked DRo’s capability and established that it could not only reduce the false-alarms generated by a DL classifier by $67.9\%$, but can also achieve the contradictory goal of simultaneously uplifting its accuracy by $11.3\%$. Not only such performance gains are unparalleled by any other system, but it is also capable of training a classifier even under abysmal feature scenarios. The results suggest that the novel DRo mechanism is a very able and feature rich alternative to TL, WS, and AL mechanisms for data-scarce domains and applications.
{'timestamp': '2021-09-14T02:20:52', 'yymm': '2109', 'arxiv_id': '2109.05470', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05470'}
arxiv
\section{Introduction} \label{sec:introduction} Recently, pre-trained deep learning models have proven their effectiveness in a variety of tasks \cite{radford2018improving,devlin2018bert, brown2020language}. One consequence of this is that the linguistic resources received less attention. In the digital age, the amount of data generated per second is enough to train a model capable of abstracting many different patterns. With a sufficiently large amount of data, these models are shown to be able to abstract the linguistic features on their own \cite{liu2019linguistic}. Even so, training the model unsupervised using data on the internet can generate noisy, biased models \cite{bender2021dangers} and make deep learning black boxes to humans. Therefore, we want to find a balanced solution between those two extremes. Pre-trained models derive their power from the attention mechanism especially multi-head self-attention \cite{vaswani2017attention}. This mechanism mimics human observation, i.e. only cares about important aspects of the data that are relevant to the decision that needs to be made. The model using attention mechanisms are often learned from data through unsupervised tasks. This helps to increase the performance of tasks without requiring much human intervention. Even so, automation without explanation can carry risks when it is widely adopted. Training models using only data can produce highly accurate but still fallacious models. Table \ref{tab:examples} shows a small dataset where if the model is based on the occurrence of the word "is", it can correctly classify 100\% of the sentiment labels of the samples. Linguistically, "is" is a functional word and should not be used to make a decision in this case. This is a contrived example, but the same thing can happen for a huge data set that humans are not capable of verifying \cite{chen2021evaluating}. For that reason, before this work, there are proposals trying to force deep learning models to follow the knowledge of linguistic resources \cite{zhang2020semantics,zhou2019head,zhang2020sg}. We observe that such coercion could reduce the flexibility of the model and overall efficiency in exceptional cases. \begin{table} \caption{A hypothetical data in which a model can achieve 100\% accuracy without the need of understanding the semantic.} \label{tab:examples} \centering \begin{tabular}{|l|l|} \hline \textbf{Sentence} & \textbf{Sentiment} \\ \hline This \textbf{is} a great product. & Positive \\ \hline Awful service. & Negative \\ \hline This product \textbf{is} great. & Positive \\ \hline The battery of this product \textbf{is} very good. & Positive \\ \hline I don't like this restaurant. & Negative \\ \hline The song \textbf{is} perfect. & Positive \\ \hline This \textbf{is} another awesome product from Google. & Positive \\ \hline Nothing special. & Negative \\ \hline I think this product should not be sold. & Negative \\ \hline It was a terrible experience. & Negetive \\ \hline \end{tabular} \end{table} Finding a neutral solution, we investigate the possibility of injecting some linguistic knowledge for pretrained models to refer to without completely depending on them. With this approach, the model can both use linguistic knowledge for the majority of cases and observe actual cases appearing in the data to adjust its understanding. In addition, this approach guides the model to use the features that are accepted by humans, so that their decision-making is explainable by humans. The challenge of this approach is to find a balance between the information learned in the pretraining and the injected knowledge. We propose an unprecedented approach to incorporating linguistic knowledge into transformers architecture. This approach has 3 advantages compared to other methods. First, this is a knowledge injection method that can take the edge of many different types of annotated resources in NLP. Second, the injected information is not rigid but only a reference source for the model to reach its final conclusion. Third, training and storing the appended component are extremely efficient, helping to solve environmental and financial problems. Although we only experiment with dependency structure as the knowledge source in the scope of this paper, the approach is general to all linguistic knowledge which expresses relationships between internal elements of a sentence, is friendly with transformer architecture, and is extendable. We believe this approach will create a new research direction in injecting knowledge into the transformer architecture. Our paper includes the following main contributions as follows: \begin{itemize} \item We first propose a novel framework to pretrain attention heads separately using the linguistic information without pretrain the whole model again. \item Next, we introduce HYDRA, a knowledge-injected component to the transformer model, which is pretrained with dependency structure relations. \item Finally, from the experimental result, we draw conclusions and future directions of this research. \end{itemize} In the remainder of this paper, we present related work in the attention mechanism and knowledge injection methods in Section~\ref{sec:background}, the detail of our method in Section ~\ref{sec:method}. Next, we investigate the effectiveness of the proposed method in comparison with the baseline in Section~\ref{sec:experiments}. Finally, the conclusion and future works are presented in Section~\ref{sec:conclusions}. \section{Related Work} \label{sec:background} \subsection{Attention Mechanism} Transformer \cite{vaswani2017attention} has become the architecture that drastically changes the way deep learning is designed and used. With previous models such as LSTM or CNN, all the information of the inputs would be compressed into a single representation. The human need in NLP is to solve longer and longer sentences. With long inputs, these models run into problems, their representations are not able to store all the information of the input. Instead of storing a loop of information in the architecture like the LSTM, the transformer uses the attention mechanism to perceive constraints in the inputs. Attention can be described as aggregating a query and key-value pairs to the representation. The output (attention vector) is calculated as the weighted sum of the values, where the weight assigned to each value is computed by the query with the corresponding key. In the paper, the authors recommend of a combination of multiple aspects to the final representations, so-called multi-head attention. This mechanism allows the model to view data with different aspects to make decisions. \subsection{Knowledge Injection} Knowldge injection is the method of providing deep learning model with external knowledge. In their paper, Nguyen and colleagues \cite{nguyen2021knowledge} use the similarity of the distribution as additional knowledge for the learning process. The knowledge was injected into the neural network (LSTM) to guide the model to make better predictions. The author also conduct the experiment to extract the knowledge from the data and use it to guide the model in another task. However, with the advent of transformers, LSTM gradually became obsolete. Pretrained transformer-based language models such as BERT \cite{devlin2018bert} have demonstrated their effectiveness in many NLP tasks. However, these bulky models also reveal weaknesses through unsupervised learning of data \cite{chen2021evaluating,bender2021dangers}. As a result, using additional knowledge is a promising way to improve the models. Recent works \cite{zhang2020sgnet,sachan-etal-2021-syntax} discover that the performance of transformer models could be improved by incorporating either semantic information or syntactic information into the transformer models. To encode syntactic information into a transformer model, the authors \cite{zhang2020sgnet} consider using a syntactic representation to incorporate it into the attention mechanism so-called Syntax-guided network(SG-NET). The key component in SG-NET is the SDOI-SAN, which is a combination of syntactic dependency of interest (SDOI) and self-attention network (SAN). SG-NET used both SDOI-SAN and SAN of the original transformer model for better linguistics-inspired representation. This is a matrix $n \times n$ with $n$ as the number of words in the input sentence. An element in this metric is assigned a value of 1 if there is a dependency link of the words in the corresponding row and column, otherwise, it is assigned to 0. With the same idea of injecting knowledge to the model, Zhang et al. \cite{zhang2020semantics} proposes an architecture with combined semantic information and attention mechanism, so-called Semantics-guided neural network (SGN). The authors assign semantic labels for every token, encode them and integrate this kind of knowledge to the pretrained model using a convolutional neural network. We observe that in terms of implementation, this design is not friendly with the existing architecture of transformers and is hard to extend. \section{Method} \label{sec:method} Observing the limitations of the previous methods, in this paper, we propose a novel partial pretraining method on the Transformer architecture. Attention heads are essentially abstractions of data from different perspectives formed during the pretraining process. The information in the heads interacts with each other to make the final decision. So, we want to verify the possibility of pretraining the heads seperately with linguistic information and then incorporate them into the general architecture as an ordinary component. The overall architecture of the proposed framework is shown in Figure \ref{fig:framework}. Based on the transformer's architecture, we add one more transformer layer at the end of the architecture containing heads, which are pretrained with linguistic knowledge. The model can choose to use the information of these heads or ignore it with the residual connections. Therefore, we can use linguistic knowledge as a reference source for the model without forcing it to accept such knowledge rigidly. Since the idea is derived with a dependency structure, we give this architecture an inspiring name, \textit{HYDRA}, which stands for \textit{Hyper Dependency Representation Attentions}. \subsection{Pretraining HYDRA Heads} Let the input be $X = \{x_1, x_2, ..., x_n\}$ with $n$ be the sequence length, we obtain an $n \times n$ matrix $M^*$ containing the linguistic relationship of the words as introduced by Zhang et al.~\cite{zhang2020sgnet}. After passing the input through the transformer layers, we get hidden state $H_{l}$ at the last layer with $l$ be the number of layers of the original transformer body. We initiate and append $l+1^{th}$ layer containing HYDRA heads and pass $H_{l}$ to this layer. With $W_q$, $W_k$ are learnable parameters in the layer ${l+1}^{th}$, we calculate query and key vectors as in Equations \ref{eq:qvec} and \ref{eq:kvec}: \begin{align} q_{l+1}^h &= W_q \cdot H_{l} \label{eq:qvec} \\ k_{l+1}^h &= W_k \cdot H_{l} \label{eq:kvec} \end{align} \noindent With $d_k$ be the dimension of the key matrix $k_{l+1}^h$, we calculate the attention matrix for each head $M^h$ following Equation~\ref{eq:attn_mtx}: \begin{equation} \label{eq:attn_mtx} M^h = \frac{q_{l+1}^h \cdot {k_{l+1}^h}^\intercal}{\sqrt{d_k}} \end{equation} \noindent We then minimize the element-wise MSE loss ($\mathcal{L}$) between $M^*$ and $M^h$ for every HYDRA head: \begin{align} \mathcal{L} &= \frac{1}{n^2} \sum_{i=0}^{n^2} (M^*_i - M^h_i)^2 \end{align} \noindent where $i$ $(0 \leq i < n^2 )$ is the index of element in flatten attention matrix SDOI ($M^*_i$). The weights of the transformer body are frozen and the weights in $Q_{l+1}^h$ and $K_{l+1}^h$ in every HYDRA heads are updated via the backpropagation process. After pretraining, we get the HYDRA heads corresponding to the transformer body coupled to it. These HYDRA heads are saved in the storage and ready to be delivered as a form of deep learning resource. Compared to storing pretrained transformer models, storing HYDRA heads saves much more storage space. A transformer model checkpoint can be measured in gigabytes, while a HYDRA head checkpoint in our experiment is less than 10 megabytes. \subsection{Fine-tuning with HYDRA Heads} Different from approaches that use linguistic knowledge that is rigidly injected into the model, we attach pretrained HYDRA heads to the transformer bodies. These models can refer to but are not limited by the linguistic knowledge learned in the HYDRA heads. At this phase, the weights of the transformer body and HYDRA head are both updated to match the training data. The final model now contains $l+1$ layers, first $l$ layers are from the original transformer body and the last layer contains HYDRA heads. We simply pass the $H_{l+1}$ to a fully connected layer to get the logits for each downstream task. The loss function of each downstream task is defined similarly to the work \cite{devlin2018bert}. We have experiments to observe the performance of the model in Section \ref{sec:experiments}. Intuition in this phase is that by acquiring linguistic knowledge, the system can properly model the problem rather than try to fit into the local minima. \begin{figure*} \centering \includegraphics[width=0.8\textwidth]{figures/HYDRA.png} \caption{The general architecture of the framework. \textit{Transformer Body} is the pre-trained model (e.g. BERT). SDOI matrix $(M^*)$ is the relation matrix parsed from an external Linguistic Parser tool (e.g. Stanford NLP tool or spaCy). \label{fig:framework}} \end{figure*} \section{Experiments} \label{sec:experiments} \subsection{Experimental Settings} \subsubsection{Pretraining Stage} In the pretrain phase, we collect data from Wikimedia Downloads\footnote{https://dumps.wikimedia.org/} using WikiExtractor package~\cite{Wikiextractor2015}. We use the variant of dependency parser described by Honnibal and Johnson~\cite{honnibal2015improved}, provided by spaCy\footnote{https://spacy.io/}. After data processing, we obtain 330,000 samples for training and 50,000 samples for validation. We use BERT~\cite{devlin2018bert} as the base model to pretrain the HYDRA heads. We set the maximum sequence length to 512 and only use sentences whose length does not exceed this number to pretrain the HYDRA heads. The goal of this setting is to help the model learn the linguistic structure of complete sentences of the longest possible length. With 1.8 million parameters, in our experiment, it takes only one or two epochs for the HYDRA heads to reach optimal loss on both the training set and the validation set. \subsubsection{Task Adaptation Stage} \label{sec:task_adap} To understand the model's behavior and the method's effectiveness, we run experiments and compare the performance of the HYDRA variants with the corresponding non-HYDRA baselines. The experiments are run on datasets and standard settings of several famous benchmarks in natural language processing which include: \begin{itemize} \item QNLI~\cite{rajpurkar2016squad}, MNLI~\cite{N18-1101,bowman2015large}, RTE~\cite{dagan2005pascal,bar2006second,giampiccolo2007third,bentivogli2009fifth} : Natural Language Inference and Texture Entailment \begin{itemize} \item Metric for QNLI and RTE: Accuracy. \item Metric for MNLI: Accuracy for both matched (m) and mismatched (mm) versions. \end{itemize} \item QQP~\cite{iyer2017qqp} and STS-B~\cite{cer2017semeval}: Semantically Equivalence Judgment \begin{itemize} \item Metric for QQP: Accuracy. \item Metric for STS-B: Pearson Spearman Correlation. \end{itemize} \item SQuAD~\cite{rajpurkar2016squad} and SQuAD 2.0~\cite{rajpurkar2018know}: Question Answering \begin{itemize} \item Metric for SQuAD and SQuAD 2.0: Exact Match and Macro-averaged F1 Score. \end{itemize} \end{itemize} \noindent With these benchmarks, we can investigate in detail the effectiveness of the proposed method. We conduct experiments with both the cased and uncased versions of BERT and average the performance. \subsection{Experimental Result and Discussion} Table \ref{tab:result} shows the results of the models on the benchmarks and metrics described in Section~\ref{sec:task_adap}. BERT is a very strong baseline, it achieved high performance on all benchmarks. Even so, our model still can slightly improve the results of BERT with the appended HYDRA heads. This result supports the hypothesis that linguistic knowledge pretrained in HYDRA heads can boost the performance of the vanilla model. In addition to the performance improvement, this is a novel approach to inject linguistic knowledge into language models. One notable feature of our improvement is that this new component is lightweight, requires low pretraining computation cost and storage. With this paradigm, we can improve the bulky transformers models without pretraining the whole network again or force them to follow rigid linguistic rules. \begin{table} \centering \caption{Experimental results on dev set of benchmark datasets\label{tab:result}} \begin{tabular}{|l|c|c|} \hline \textbf{Benchmark} & \textbf{BERT} & \textbf{BERT HYDRA} \\ \hline QNLI & 0.9065 & 0.9090 \\ \hline MNLI\_m & 0.8373 & 0.8401 \\ \hline MNLI\_mm & 0.8419 & 0.8458 \\ \hline RTE & 0.6300 & 0.6336 \\ \hline QQP & 0.9062 & 0.9067 \\ \hline STS-B & 0.8800 & 0.8812 \\ \hline SQuAD EM & 0.8105 & 0.8124 \\ \hline SQuAD F1 & 0.8838 & 0.8851 \\ \hline SQuAD 2.0 EM & 0.7137 & 0.7161 \\ \hline SQuAD 2.0 F1 & 0.7458 & 0.7480 \\ \hline \end{tabular} \end{table} \section{Conclusions} \label{sec:conclusions} This paper proposes an architecture-friendly and extensible method to improve the effectiveness of the transformer-based language models by pretraining and appending new knowledge-guided heads to their architecture. We conduct the experiment with BERT as the base model and the dependency information as the external knowledge. Our experiment shows that our lightweight component can help to boost the performance of transformer models and provide a flexible paradigm to partially inject the knowledge into bulky models without pretraining them again. Extending this work, we can analyze the possibility of pretraining this component with different knowledge forms for problems in narrower domains or explore the potential of this approach for other data such as photos or~videos. \bibliographystyle{plain}
{'timestamp': '2021-09-14T02:15:58', 'yymm': '2109', 'arxiv_id': '2109.05349', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05349'}
arxiv
\section{#1}\vspace{0in}} \newcommand{\mypar}[1]{\noindent \textbf{#1:}} \newcommand{\vspace{-0.1cm} \item}{\vspace{-0.1cm} \item} \newcommand{\note}[1]{\textbf{NOTE: [#1]}} \newcommand{\NOTE}[1]{\textbf{NOTE: [#1]}} \newcommand{\todo}[1]{\textbf{TODO: [#1]}} \newcommand{\TODO}[1]{\textbf{TODO: [#1]}} \newcommand{\fixme}[1]{\textbf{FIXME: [#1]}} \newcommand{{\bf FIXME:}}{{\bf FIXME:}} \newcommand{\remark}[1]{\textbf{REMARK [#1]???}} \newcommand{\response}[1]{\textbf{RESPONSE [#1]???}} \newcommand{\dropme}[1]{\textbf{DROPME [#1]???}} \newcommand{\reviewcomment}[2]{\textbf{REVIEW \##1}{\xspace\emph{#2}}} \newcommand{\WORDS}[1]{} \newcommand{\WORDSresponse}[1]{#1} \newcommand{\WORDSchange}[1]{#1} \newcommand{\textit{e.g.}}{\textit{e.g.}} \newcommand{\textit{i.e.}}{\textit{i.e.}} \newcommand{\textit{et al.}\xspace}{\textit{et al.}\xspace} \newcommand{\codesm}[1]{\texttt{\small #1}} \newcommand{\ignore}[1]{} \newcommand{\budget}[1]{\textbf{SPACE BUDGET: #1}} \newcommand{\myincludegraphics}[2]{\resizebox{#1}{!}{\includegraphics{#2}}} \newcommand{\red}[1]{{\color{red} #1}} \newcommand{\haris}[1]{{\color{red} #1}} \newcommand*\BitAnd{\mathrel{\&}} \newcommand*\BitOr{\mathrel{|}} \newcommand*\ShiftLeft{\ll} \newcommand*\ShiftRight{\gg} \newcommand*\BitNeg{\ensuremath{\mathord{\sim}}} \newcommand{\texttt{clwb}\xspace}{\texttt{clwb}\xspace} \newcommand{\texttt{clflush}\xspace}{\texttt{clflush}\xspace} \newcommand{\texttt{clflushopt}\xspace}{\texttt{clflushopt}\xspace} \newcommand{\texttt{pcommit}\xspace}{\texttt{pcommit}\xspace} \newcommand{\texttt{epoch}\xspace}{\texttt{epoch}\xspace} \newcommand{\texttt{fence}\xspace}{\texttt{fence}\xspace} \newcommand{\texttt{mov}\xspace}{\texttt{mov}\xspace} \newcommand{\texttt{movnti}\xspace}{\texttt{movnti}\xspace} \newcommand{\texttt{sfence}\xspace}{\texttt{sfence}\xspace} \newcommand{\texttt{lazy\_pcommit}\xspace}{\texttt{lazy\_pcommit}\xspace} \newcommand{\texttt{cas}\xspace}{\texttt{cas}\xspace} \newcommand{PMBench\xspace}{PMBench\xspace} \newcommand{Memory-oriented distributed computing\xspace}{Memory-oriented distributed computing\xspace} \newcommand{Message-based distributed computing\xspace}{Message-based distributed computing\xspace} \newcommand{memory-oriented distributed computing\xspace}{memory-oriented distributed computing\xspace} \newcommand{message-based distributed computing\xspace}{message-based distributed computing\xspace} \newcommand{MODC\xspace}{MODC\xspace} \newcommand{region\xspace}{region\xspace} \newcommand{regions\xspace}{regions\xspace} \newcommand{copy-on-write\xspace}{copy-on-write\xspace} \newboolean{expandConfidential} \setboolean{expandConfidential}{true} \ifthenelse {\boolean{expandConfidential}} { \newcommand{\confidential}[1]{#1} } { \newcommand{\confidential}[1]{} } \newcommand{disaggregated memory}{\douppercase{d}isaggregated memory\xspace} \newcommand\douppercase[1]{\ifnum\ifhmode\spacefactor\else2000\fi>1000 \uppercase{#1}\else#1\fi} \newcommand{Disaggregated memory\xspace}{Disaggregated memory\xspace} \section{Background} We begin by providing background on task-parallel programming models and disaggregated memory systems, as well as stating our system model. \subsection{Task-parallel programming} In task-parallel programming~\cite{blumofe:cilk:ppopp:1995}, the programmer decomposes an application into units of work, called \emph{tasks}, that may execute in parallel. Programmers focus on structuring their program to expose parallelism, while an underlying runtime system takes on the responsibility of dynamically scheduling and executing tasks among a pool of workers. \WORDSresponse{Traditionally, tasking systems have primarily relied on global checkpoint/restart mechanisms for tolerating task failures. However, recent work has investigated other approaches to handling task failures}. Resilient X10~\cite{cunningham:resilient-x10:ppopp:2014} proposes extensions to the X10 task-parallel language~\cite{charles:x10:oopsla:2005} to expose failures to programmers, who can then handle individual task failures by exploiting domain-specific knowledge. CIEL~\cite{murray:ciel:nsdi:2011} and Ray~\cite{moritz:ray:osdi:2018}, like us, provide transparent lineage-based fault tolerance. They log function calls and require arguments and results of tasks to be immutable, so that they can \WORDSresponse{use the lineage to} transparently restart individual tasks on the event of a failure. A key difference is that our work leverages disaggregated memory to fail over computation from a failed worker to another live worker in a decentralized manner, by letting live workers steal work from a failed worker. \WORDSresponse{ Dataflow systems, such as MapReduce~\cite{dean:mapreduce:osdi:2004}, Dryad~\cite{isard:dryad:eurosys:2007}, and Spark~\cite{zaharia:spark:nsdi:2012} adopt a bulk-synchronous parallel (BSP) execution model, where all tasks within the same stage perform the same computation and cannot recursively create other tasks. MapReduce limits the dataflow to a bipartite graph comprising map and reduce tasks. Dryad extends the MapReduce model to allow computation to be expressed into a more general directed acyclic graph (DAG), but lacks support for dynamic task graphs, which can be useful for iterative and incremental computation. Spark does support dynamic task graphs, by dynamically tracking task dependencies through a centralized scheduler and adopting lineage-based fault tolerance. However, invoking the centralized scheduler at the end of each task adds overhead and increases latency. Streaming dataflow systems, such as Naiad~\cite{murray:naiad:sosp:2013} and Flink~\cite{carbone:flink:vldb:2017}, implement the dataflow using a graph of continuous operators or long running tasks, avoiding frequently invoking a centralized scheduler, but limiting support to static task graphs. } \WORDSresponse{ \WORDSchange{Architectures based on dataflow languages~\cite{Dataflow} control program execution using \emph{actors} that consume \emph{objects} as inputs and produce objects as outputs.} While these architectures also track dependencies among actors as part of program execution, the underlying actors are much more granular than our tasks, rely on specialized hardware for program execution and dependency management, and are not focused on resilience. } \subsection{Rack-scale disaggregated memory} Resource disaggregation is a popular approach for specializing resources allocated to a workload. Increasing attention is being paid to leveraging memory resources outside of traditional compute nodes. Here we focus on \emph{disaggregated memory}, rather than remote memory solutions where compute nodes share their memory with other compute nodes. In disaggregated memory system organizations, memory that is distinct from compute node memory is exposed over a fast network\ignore {, and can be scaled independently of the compute or storage capacity of the system}. Disaggregated memory may be constructed with intelligent memory servers containing general-purpose processors (\textit{e.g.},\cite{lim:memory-blade:isca:2009, lim:system-memory-blade:hpca:2012}) connected via RDMA (\textit{e.g.},~\cite{binnig:nam:pvldb:2016, ma:asymnvm:asplos:2019, sidler:strom:eurosys:2020}) or special purpose interconnects (\textit{e.g.},~\cite{novakovic:so-numa:asplos:2014, shan:legoos:osdi:2018}), or as network-attached memory controllers with more limited intelligence (\textit{e.g.},~\cite{hpe:machine, aguilera:farmem:hotos:2019}). Depending on the implementation, disaggregated memory may also be augmented with additional support for metadata operations (\textit{e.g.},~\cite{tsai:atc:2020}). Disaggregation provides separate fault domains between processing and memory, meaning that the failure of a compute node doesn't render disaggregated memory unavailable. \subsection{Target environment and assumptions} In this work, we target a disaggregated memory architecture containing a high-capacity pool of memory that can be shared by compute nodes at low latency. This memory is directly connected to the interconnect, as defined in the Gen-Z standard~\cite{GenZ}, without an explicit memory server with general-purpose processing capabilities. Memory controllers serve non-volatile memory (NVM) on the fabric, which offers durability without the overheads of traditional storage devices. Compute nodes also have local memory, which is treated as private, while the disaggregated memory is treated as shared. Compute nodes access disaggregated memory using load and store operations, atomic memory fabric operations (\textit{e.g.}, compare-and-swap (\texttt{cas}\xspace)) and one-sided (\textit{e.g.}, get and put) operations. Disaggregated memory presents a \emph{logical address space} that is uniform across all compute nodes. Thus, any compute node can access any part of disaggregated memory in a byte-addressable manner. Since rack-scale disaggregated NVM forms the primary persistence layer, it needs to be protected against memory hardware failures to avoid data loss. Hardware redundancy schemes have been proposed to protect both DRAM (\textit{e.g.}, ~\cite{kim:allinclusiveecc:isca:2016, zheng:raim:isca:2017}) and NVM (\textit{e.g.}, ~\cite{kateja:tvarak:isca:2020, golov:redundant-nvm:patent:2015, lesartre:fault-pmem:patent:2014}). While these schemes protect against memory cell or chip failures, they do not protect against failures that render a whole memory node unavailable, such as memory controller or power supply failures. Hence, we assume a hardware redundancy scheme is used in combination with software-managed memory replication to protect disaggregated NVM. Using memory-side accelerators (e.g.,~\cite{daehyeok:hyperloop:sigcomm:2018}) can decentralize and minimize compute node overheads for memory replication. Additionally, we assume that the memory interconnect incorporates sufficient component and path redundancy to prevent partitions. \subsection{Prototype and evaluation platform} \WORDSresponse{ Our evaluation goal is to understand the fault tolerance benefits of MODC\xspace, as well as its overheads. We have implemented a prototype of MODC\xspace's resilient task programming model and runtime system, including the components described in the previous section. Our implementation builds on several open source libraries, including lock-free data structures~\cite{RadixTree-github}, memory management~\cite{NVMM-github, librarian-lfs:2017} and fabric atomics~\cite{fam-atomics:2017}. } Our emulation platform for disaggregated memory is an HPE Superdome X machine running Red Hat Enterprise Linux 7.2 with 288 cores and 12 TB DRAM. Each of the 16 NUMA sockets has an E7-8890 v3 CPU with 18 cores and 768 GB DRAM. We use Quartz~\cite{volos:quartz:middleware:2015} to emulate disaggregated memory performance. Quartz emulates compute nodes by binding each\ignore{application} worker process to a NUMA socket, with\ignore{worker} processes evenly distributed across the\ignore{NUMA} sockets. It emulates disaggregated memory by binding a single instance of the \texttt{tmpfs} in-memory file system to a remote NUMA socket used exclusively for emulating disaggregated memory. This results in 768 GB of disaggregated memory with remote latency of 400ns, as measured using a memory latency-sensitive pointer-chasing microbenchmark. This latency is 3x slower than the local latency and on par with previous research proposals on rack-scale fabrics~\cite{novakovic:so-numa:asplos:2014}. \WORDSresponse {Our PageRank implementations use one-dimensional row partitioning (also known as vertex partitioning): each task is responsible for a set of rows and the non-zeroes within those rows. Each experiment uses a $64M \times 64M$ recursive matrix (RMAT)~\cite{chakrabarti:rmat:siam:2004} graph, and results are averaged over four runs. } \subsection{Sensitivity to task size} \label{sec:tasksize} \WORDSresponse{ We begin our analysis by exploring the sensitivity of the MODC\xspace PageRank implementation to the task size. Figure~\ref{fig:modc-tasksize} shows MODC\xspace execution time relative to the best execution time (empirically determined to be 15,000 rows). This experiment uses eight workers. MODC\xspace performs well for a wide range of task sizes: performance is within 5\% of the best for tasks of 5000 rows to 100,000 rows, and within 17\% of the best for tasks of up to 8M rows. We use tasks of 15,000 rows for our subsequent MODC\xspace experiments. } \begin{figure}[ht!] \centering \myincludegraphics{0.9\linewidth}{figures/PageRank-Unbalanced-MODC-TaskSize-figure.pdf} \vspace{-0.1in} \caption{MODC\xspace PageRank sensitivity to task size} \label{fig:modc-tasksize} \vspace{-0.05in} \end{figure} \subsection{Fault tolerance} We compare the resilience of the MODC\xspace implementation of PageRank against the resilience of an MPI-based implementation with emulated checkpoints. In both cases, fourteen workers execute PageRank’s iterative algorithm for 10 iterations. We inject a failure by crashing one of the workers, and let each implementation recover and continue execution. We assume non-shrinking recovery for these experiments: a new worker is instantiated upon a worker failure, to ensure that the number of active workers remains constant. The MPI and MODC\xspace implementations use the same data structures and mmap data access methods, but use distinct scheduling and recovery mechanisms. The MODC\xspace implementation dynamically decomposes the problem into jobs and tasks. The failure is detected using MODC\xspace's heartbeat mechanism, and a new worker is activated from a hot standby spare. The task being executed when the worker died, along with any additional tasks in the failed worker’s queue, are stolen for execution by one of the remaining workers. The MPI implementation uses a bulk synchronous parallel programming model, with barriers between iterations. Each iteration's work is statically partitioned among the workers, with no work stealing. Partitioning assigns sets of 10,000 rows (the empirically determined best MPI set size) to workers in a round robin fashion. For fault tolerance, the MPI implementation uses checkpoints of the dense per-iteration output vector (512 MiB) to the emulated disaggregated memory. Recovery from a failure includes the time to read the checkpoint and the time to re-run all of the iterations since the last checkpoint. We assume a checkpoint interval of four iterations in the analysis below. \begin{figure}[ht!] \centering \myincludegraphics{0.9\linewidth}{figures/modc-mpi-ft.pdf} \vspace{-0.1in} \caption{Comparison of fault tolerance approaches} \label{fig:acme-mpi-ft} \vspace{-0.05in} \end{figure} Figure~\ref{fig:acme-mpi-ft} illustrates the overall execution time for\ignore{to complete} 10 PageRank iterations, with\ignore{in the face of} a failure injected at the iteration shown on the x-axis. We measure execution with and without the failure. With a failure injected, MODC\xspace only needs to restart the task that was executing when the worker crashed. As a result, its overall execution time with a failure is 23.3s, less than 1\% degradation from its failure-free execution. Execution time for MPI with checkpointing depends on how soon the crash occurs after the last checkpoint, ranging from 1.06X – 1.35X of the failure-free execution time. Checkpoint-recovered execution is slower than MODC\xspace resilient execution, ranging from 19\% slower than MODC\xspace (if the crash occurs just after the checkpoint) to as much as 51\% slower (if the crash occurs just before the next checkpoint). \section{MODC\xspace programming model} \label{sec:task-model} Programmers use resilient parallel jobs and tasks as a way to decompose and recover data processing computations. A resilient parallel application is structured as a set of restartable execution units (idempotent \emph{tasks}). Each task is defined as a function with an explicitly specified set of disaggregated memory-resident inputs and outputs. It applies a transformation on its input data to produce its output data. The output of one task may serve as an input to another task, creating an input-output \emph{data dependency}. Inputs and outputs are specified by names, which are resolved at runtime, thus permitting decoupled execution of producer and consumer tasks. A producer task can produce output data without knowing which consumer task (if any) will consume it, and a consumer task can consume data without knowing which task produced it. Similarly, output data may be treated as a future, allowing a consumer function to be scheduled before its inputs are fully generated; its execution is delayed until those inputs are ready (i.e., when the task(s) that produce the data are done). Additional \emph{control dependencies} (e.g., completion of all tasks in a set or task ordering that depends on the specific values produced rather than the existence of data) are expressed using a \emph{job} abstraction, which describes a collection of tasks. Control dependencies may exist between jobs, but not between tasks within a single job. An application is comprised of one or more jobs and their constituent tasks (Figure~\ref{fig:task-parallelism}). Expressing data dependencies with named data items rather than explicit communication between tasks means that tasks don’t need to be aware of where they (or their predecessors or successors) are run. Since tasks can be scheduled for execution on an arbitrary node, and may be restarted on a different node in case of failure, they are required to be \emph{idempotent}: given the same input, they are expected to produce the same output. \WORDSresponse{To enable restarting an idempotent task, the task's input data must remain available until the task successfully completes.} Tasks are also expected to be \emph{side-effect free} in the sense that they don’t have side channels for communicating state that aren’t visible to the framework. The programming model supports a dynamic parallelism form of autoscaling, where work can be dynamically decomposed to provide (arbitrary) levels of parallelism, depending on the amount of data to be processed. The programmer defines the granularity of the jobs and tasks, and thus can strike a balance on a case-by-case basis between increased parallelism, lower chance of stragglers, and reduced recovery time from smaller tasks vs. increased efficiency from larger tasks (due to lower scheduling overhead and greater execution efficiency without intra-task communication). The application dynamically spawns tasks, and manages control dependencies while the underlying framework handles data dependencies, task scheduling, and failure recovery. The framework asynchronously executes each task with all-or-nothing\ignore{(at most once)} semantics, and re-schedules tasks that fail. \begin{figure}[t!] \centering \myincludegraphics{3.0in}{figures/task-scheduler.pdf} \caption{Resilient task execution by two workers.} \vspace{-0.2in} \label{fig:task-parallelism} \end{figure}
{'timestamp': '2021-09-14T02:15:17', 'yymm': '2109', 'arxiv_id': '2109.05329', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05329'}
arxiv
\subsection{Baseline GPU Architecture} Figure \ref{fig:baseline_gpu} shows a baseline GPU architecture, which is similar to the real-world GPU products \cite{nvidia2009nvidia, nvidia2012nvidia, turingGPU, gv100}. Specifically, the baseline GPU consists of multiple streaming multiprocessors (SMs), shared L2 cache and memory controllers, all of which are connected through an interconnect network. Within the SMs, a group of 32 threads, called \emph{warp} \cite{nvidia2009nvidia}, are executed in a lockstep. During the execution, a set of instructions for each warp is fetched from the underlying GPU memory. The instructions are then decoded and stored in the register files. Afterwards, the warp scheduler schedules the warps to execute. Arithmetic instructions are executed by ALUs, while load/store instructions generate memory requests. SMs firstly try to find out data associated with the memory requests from L1D cache. If L1D cache misses, the requests will be forwarded to the shared L2 cache via the interconnect network. If L2 cache also misses, the requests will be sent to the memory controller. A traditional GPU memory controller in practice buffers and schedules incoming memory requests \cite{zhang2020zng}. For each request, the memory controller issues the memory transactions with DRAM via GDDR6 protocol. \begin{figure} \centering \includegraphics[width=1\linewidth]{figs/mc.eps} \caption{\label{fig:mc}Memory controller in heterogeneous memory.\vspace{-5pt}} \vspace{-5pt} \end{figure} \subsection{Challenges in GPU Memory System} The existing GPU memory system becomes the performance bottleneck of executing large-scale applications in the GPU due to its low capacity, limited throughput, and high energy consumption \cite{zhang2015nvmmu,zhang2020zng,zhang2019flashgpu}. As the GPU on-chip DRAM cannot accommodate all data sets of large-scale applications, the data often require being loaded/stored from/to an external storage. To be precise, we evaluated a computing system that integrates a high-performance GPU \cite{nvidia2012nvidia} and an SSD \cite{ZSSD} together. Figure \ref{fig:exe_brkdown} shows a breakdown analysis to execute different GPU applications \cite{che2009rodinia,pouchet2012polybench,nai2015graphbig} on our testbed system. The storage access delay and data transfers between the GPU and SSD account for 21\% and 45\% of the total execution time, on average, respectively. This data movement overhead takes a time longer than the GPU computing time itself by 2.3$\times$, on average. We also analyze the impact of DMA and DRAM accesses on the GPU memory system in terms of execution time and energy consumption, and the results are shown in Figure \ref{fig:dram_brkdown}. Transferring data via electrical memory channels (i.e., DMA) degrades the performance of the GPU memory system by 31\% and 19\% in terms of execution time and energy consumption, respectively. \subsection{Heterogeneous Memory System} \label{sec:mcarch} Combining DRAM and 3D XPoint (\emph{XPoint}) as a heterogeneous memory system is considered as a good solution to take advantage of DRAM's high-performance and XPoint's large-capacity in parallel. Figure \ref{fig:mc} shows the details of a heterogeneous memory system proposed by prior work \cite{ramanujan2014dynamic, nale2019memory}. One can observe from the figure that the heterogeneous memory system places both DRAM and XPoint together to share the same memory channel for data transfers. However, DRAM and XPoint require different memory control logic to manage their communication protocols and process memory transactions. To address this, the heterogeneous memory system includes a customized memory controller and a XPoint controller to handle the communication protocols \cite{ramanujan2014dynamic, nale2019memory}. \noindent \textbf{XPoint controller.} Unfortunately, the memory controller cannot directly communicate with XPoint due to two root causes: 1) XPoint operates in a different clock frequency from the memory channel; 2) Xpoint has a limited lifetime, which can easily wear-out if there exist intensive memory accesses. A XPoint controller is deployed between the memory controller and XPoint to handle the different clock frequency and the wear-out issues of XPoint, as shown in Figure \ref{fig:mc}. Specifically, to address the asymmetric frequency issue, the XPoint controller employs read and persistent write buffers, which temporarily store the incoming memory requests and data. The XPoint controller then processes the memory requests asynchronously and leverages a XPoint protocol engine to access data from XPoint. To improve the endurance of XPoint, the XPoint controller also employs address translation and wear-levelling algorithms, which are similar to the reliability management of flash-based SSD controllers \cite{micheloni2013inside,kim2002space,gupta2009dftl,chang2007efficient}. The ``metadata'' of these algorithms (e.g., address mapping table) are stored in an external DRAM buffer \cite{optane-test}. \noindent \textbf{Memory controller.} In contrast to the DRAM controller, the memory controller employs two different protocols, DDR and DDR-T \cite{ramanujan2014dynamic}, to communicate with DRAM and the XPoint controller, respectively. This is because the memory access latencies of XPoint are non-deterministic and incompatible with the deterministic memory timing protocol such as DDR; DDR-T is an asynchronous communication protocol. Specifically, after sending commands to the XPoint controller, the memory controller switches to process other memory requests. Once the memory controller gets any response message from XPoint controller, it turns to receive the data over memory channel. \begin{figure} \centering \includegraphics[width=1\linewidth]{figs/optic_basic.eps} \caption{\label{fig:optic_basic}Details of optical network and modulator.\vspace{-5pt}} \vspace{-5pt} \end{figure} \begin{figure*} \centering \includegraphics[width=1\linewidth]{figs/background_overview.eps} \caption{\label{fig:background}Overview of Ohm-GPU architecture with an Ohm memory system.\vspace{-10pt}} \end{figure*} \subsection{Optical Network} \label{sec:optical} \noindent \textbf{Optical channel.} Silicon nano-photonic technologies enable an optical network to replace the existing electrical memory channel \cite{shacham2007design, beausoleil2008nanoelectronic}. The optical channel can be an ideal candidate to connect between memory controllers and multiple memory chips as it improves the interconnect bandwidth by two orders of magnitude and reduces the power consumption of an electrical channel by 10$\times$ \cite{li2013exploring}. Figure \ref{fig:optic_basic}a shows a typical design of an optical channel \cite{bergman2014photonic}. In contrast to the electrical memory channels, the optical channel uses laser light of multiple wavelengths to carry different data streams from multiple transmitters to receivers. These laser lights traverse through a transmission medium, referred to as \textit{waveguide} \cite{bergman2014photonic}. The external vertical-cavity surface-emitting laser (VCSEL) sources generate lights of different wavelengths and inject the lights into a single waveguide by using dense wavelength-division multiplexing (DWDM) \cite{bergman2014photonic}. To send a message via the optical channel, each transmitter employs a micro-ring resonator as a photonic modulator to modulate its electrical data on the light generated by the laser source \cite{bergman2014photonic}. On the other hand, the receivers can get the messages by using a micro-ring resonator as a photonic detector to couple and absorb the incoming laser lights. The receiver then converts the light bits into electrical signals, which will be forwarded to the controllers or memories. \noindent \textbf{Micro-ring resonator.} In this work, we adopt an \textit{active micro-ring resonator} (MRR) to implement photonic modulators and detectors \cite{bahadori2016comprehensive}. MRR is a closed loop of transmission medium, which can couple and absorb the light of a wavelength by tuning the resonance wavelength. A photonic modulator leverages MRR to modulate the laser lights. Figure \ref{fig:optic_basic}b shows a transmission power distribution, generated by an MRR-based photonic modulator. When MRR is tuned to the resonance wavelength $\lambda_{0}$, the photonic modulator fully couples the light of wavelength $\lambda_{0}$, and thus, the transmission power of wavelength $\lambda_{0}$ in a waveguide is low, denoted by logic ``0''. Otherwise, when MRR is tuned to resonance wavelength $\lambda_{1}$, the light of wavelength $\lambda_{0}$ directly passes the MRR. At this time, the transmission power of wavelength $\lambda_{0}$ in the waveguide is high, denoted by logic ``1''. The photonic detector also leverages MRR to couple/absorb the light. It detects the data by sensing the light strength. Note that a laser light can be used by a single pair of photonic modulator and detector. This is because, once the light of a wavelength is fully coupled in an MRR, other MRRs cannot absorb or modulate data in the same light. Due to this, incoming nominal memory requests and data migration have to be serialized in the optical channel. \section{High-level View of Ohm-GPU} Figure \ref{fig:background}a shows an overview of our baseline Ohm-GPU design. Compared to the traditional GPU (cf. Figure \ref{fig:baseline_gpu}), Ohm-GPU integrates a new memory system, called \textit{Ohm memory system}, to replace the existing DRAM-based GPU memory system. Specifically, the Ohm memory system employs DRAM and XPoint as a heterogeneous memory to increase the memory capacity while maintaining high performance. DRAM in Ohm-GPU also accommodates write-intensive data, which can significantly reduce the number of writes on XPoint, thereby extending the lifetime of XPoint. To improve the bandwidth and energy consumption behaviors of the memory system, Ohm-GPU also integrates an optical infrastructure, which jointly connects the memory controllers and the memory devices. \subsection{Ohm-GPU Architectural Design} \noindent \textbf{Optical infrastructure for Ohm-GPU.} Figure \ref{fig:background}b shows a high-level overview of our optical infrastructure design. An optical channel replaces hundreds of electrical lanes to connect between the GPU memory controllers and memory devices. Directly attaching multiple memory controllers to a single optical channel can introduce channel-level conflicts, as these memory controllers can compete to occupy the same optical channel. To address this challenge, we statically split the optical channel into multiple virtual channels and assign a dedicated virtual channel to each memory controller. Our ``key insight'' is that an optical channel transfers different data streams in multiple wavelengths by using the wavelength-division multiplexing. Therefore, we can split the available wavelengths to compose different virtual channels. While the virtual channels ensure no channel conflicts among all memory controllers, the transmitters and receivers of massive memory devices may compete to occupy a virtual channel. To address this, we leverage the control logic and photonic demultiplexers proposed in \cite{li2013exploring} to arbitrate the competition of an optical channel usage, as shown in Figure \ref{fig:background}b. Specifically, if a memory device is ready to serve memory requests, the photonic demultiplexer sets up the communication between the memory controller and the memory device (cf. Figure \ref{fig:background}b) by enabling the photonic detector of this memory device. Meanwhile, the photonic detectors of the remaining memory devices are disabled to yield the optical channel. \noindent \textbf{Integration of DRAM and XPoint.} Unfortunately, DRAM and XPoint cannot be directly attached to the optical channel via the photonic transmitters and receivers. There are two reasons. Firstly, the command, address, and data are simultaneously accessed in the memory devices, while all the data are serialized in the optical channel. Secondly, XPoint requires assistance of a XPoint controller to enable ECC, manage the endurance of XPoint, and control its I/O transactions. Figure \ref{fig:background}c shows our designs to address such challenges. To make the XPoint and DRAM compatible with the optical channel, we employ a SerDes circuit \cite{aoyama20033} to transform data between serial and parallel I/Os. We also employ a small size of registers (i.e., 16KB) in front of the memory devices to buffer the data from the optical channel. To integrate XPoint in the optical channel, one simple solution is to employ a XPoint controller for each XPoint. However, having multiple XPoint controllers can increase the area cost, which is critical as the limited GPU space is concerned. In addition, the XPoint controller requires a DRAM buffer to store the metadata of address translation. Since XPoint stacks its storage cores into multiple layers, we can save the area cost by integrating the XPoint controller in XPoint as a logic layer, which is adopted by several prior logic-in-memory designs\cite{pawlowski2011hybrid,shulaker2014monolithic,zhu2013accelerating}. In addition, we implement a simple wear-levelling scheme inspired by Start-Gap \cite{qureshi2009enhancing}, which periodically shifts the logical address of incoming I/Os rather than maintaining a huge mapping table in DRAM buffer \cite{zhou2009durable}. Thus, our XPoint controller design can fully eliminate the usage of the DRAM buffer. \subsection{Operational Modes of Ohm Memory} \label{sec:operational} In our design, the Ohm memory system can be organized in two operational modes to meet different purposes. \noindent \textbf{Planar memory mode.} To maximize the capacity of our heterogeneous memory, DRAM and XPoint can be configured as a planar memory, incarnating a unified address space. However, as XPoint is directly exposed to GPU kernels in this memory mode, GPU kernels suffer from the long NVM read and write delays. To hide such latency, one may use DRAM as prefetching caches by loading hot data from XPoint in advance and serving them directly from DRAM. Unfortunately, each data movement introduces significant OS overhead, including changing page table entries and shooting down translation lookaside buffers. To address this challenge, We adopt an OS-transparent data migration design inspired by \cite{wang2016duang}. Specifically, the entire memory space is split into multiple groups, each containing a DRAM page and a few XPoint pages based on the capacity ratio of DRAM and XPoint. If a XPoint page experiences intensive memory accesses, the XPoint page is considered as hot, and thus, the data of the XPoint page is swapped with the data of a DRAM page (cf. \redcircled{2}\redcircled{3}\redcircled{4}\redcircled{5} in Figure \ref{fig:motiv}a). The memory controllers record the mapping information of logical address and data location in a simplified mapping table. When serving memory requests, the memory controllers look up the table for the target data. Note that during this \textit{swap}, the memory controller can still issue memory requests coming from the GPU kernels to access DRAM/XPoint, which are not busy (\bluecircled{1}). However, the data migration generated by the swap procedure blocks the memory channel, which postpones the data response for the GPU kernels with a significantly long delay (\bluecircled{6}). \begin{figure} \centering \includegraphics[width=1\linewidth]{figs/motiv.eps} \caption{\label{fig:motiv}Data movement in heterogeneous memory.\vspace{-5pt}} \vspace{-5pt} \end{figure} \noindent \textbf{Two-level memory mode.} DRAM in a two-level memory mode is configured as an inclusive cache of XPoint \cite{yang2020empirical,dhiman2009pdram,park2018bibim}. We adopted a typical design of memory controllers \cite{nale2019memory,yang2020empirical} to implement the two-level memory mode, and it employs a tag check module to examine if data presents in DRAM (cf. Figure \ref{fig:mc}). Specifically, as shown in Figure \ref{fig:motiv}b, when a memory request arrives at the memory controller, its address is decoded into an index, a tag, and an offset. The memory controller scans the DRAM cache, based on the index of the memory request (\redcircled{1}). The tag check module then compares the tag of the memory request with the metadata of the target DRAM cache-line. If matched, the memory controller directly services the memory request with the data fetched from DRAM. Otherwise, the memory controller accesses the data from XPoint based on the target address of the memory request (\redcircled{2}). The memory controller then serves the memory requests with the fetched data (\bluecircled{3}). Note that it is impractical to build a large tag array within the controller as it requires a high space to store the metadata of the entire DRAM cache. Instead, we configure DRAM as a direct-map cache, which can reduce a large tag size to a few bits. Thanks to the reduced tag size, the memory controller can store the small metadata (including 1 valid bit, 1 dirty bit, and 3$\sim$6 tag bits) along with ECC in the ECC region of each DRAM cache-line \cite{nale2019memory}. This new design can eliminate the space cost of the tag array. In addition, while traditional DRAM cache fetches the metadata and data via two separate memory accesses, the memory controller in our new design can fetch the data, ECC, and corresponding metadata from a single DRAM cache-line. This can eliminate potential overhead of the metadata accesses. Nevertheless, the controller is yet frequently involved in migrating data between DRAM and XPoint (\redcircled{4}\redcircled{5}), which can impose migration overhead. \section{Acknowledgement} This research is mainly supported by NRF 2021R1AC4001773 and IITP 2021-0-00524. The work is also supported in part by KAIST start-up package (G01190015), and Samsung (G01200447). Other product names used in this publication are for identification purposes only and may be trademarks of their respective companies. Myoungsoo Jung is the corresponding author. \subsection{Overall Performance Analysis} \label{sec:overall-eva} \noindent \textbf{IPC.} Figure \ref{fig:norm_ipc} shows the IPC values of different GPU platforms under various workloads, normalized to \texttt{Ohm-base}. Due to the relatively small memory size, \texttt{Origin} invokes data copies between the host and the GPU more frequently. As a result, \texttt{Origin} degrades the overall performance, compared to \texttt{Hetero}, by 42\%. Since the optical network in our default configuration has the same bandwidth as electrical memory channels (cf. Table \ref{tab:sys-config}), \texttt{Hetero} and \texttt{Ohm-base} exhibit similar performance each other. Nevertheless, \texttt{Ohm-base} consumes a lower power and less area space than \texttt{Hetero} (cf. Section \ref{sec:sensitive}). Note that \texttt{Ohm-base} can significantly outperform \texttt{Hetero} by employing multiple waveguides which will be discussed in Section \ref{sec:sensitive}. \texttt{Auto-rw} improves the performance by 9\% and 4\%, respectively, in planar and two-level memory modes, compared to \texttt{Ohm-base}. This is because \texttt{Auto-rw} leverages the auto-read/write function to automate the data transfers from DRAM to XPoint without the interference from the memory controller. On the other hand, \texttt{Ohm-WOM} can improve the performance by 18\% and 16\%, compared to \texttt{Auto-rw}, in the two operational modes. Specifically, \texttt{Ohm-WOM} in planar memory mode adopts the swap function to fully decouple the memory controller from the management of data migration. \texttt{Ohm-WOM} in planar memory mode also hides the impact of data migration on latency-critical read requests by issuing the data migration with write requests at background. By adopting this approach, the performance of \texttt{Ohm-WOM} is further increased by 4\%. Lastly, \texttt{Ohm-WOM} in two-level memory mode automates the data transfer from XPoint to DRAM with the reverse-write function, which reduce the optical channel traffic. Compared to \texttt{Ohm-WOM}, \texttt{Ohm-BW} further improves the performance by 4\% in the planar mode. This is because \texttt{Ohm-BW} increases the effective bandwidth of optical channels for the memory requests, thereby improving the overall performance. As DRAM delivers up to 6$\times$ higher throughput than XPoint \cite{optane-perf}, \texttt{Oracle} outperforms all the evaluated GPU platforms that employ heterogeneous memory systems (i.e., \texttt{Hetero}, \texttt{Ohm-base}, \texttt{Auto-rw}, \texttt{Ohm-WOM} and \texttt{Ohm-BW}). Note that \texttt{Ohm-BW} achieves 88\% of the ideal GPU performance (\texttt{Oracle}) with a much lower cost (cf. Section \ref{sec:sensitive} for details). \begin{figure} \centering \includegraphics[width=1\linewidth]{figs/datamove_compact1.eps} \caption{\label{fig:datamove}Memory usage of evaluated GPU systems.} \end{figure} \begin{figure} \centering \includegraphics[width=1\linewidth]{figs/energy_compact2.eps} \caption{\label{fig:norm_energy}Energy breakdown of GPU memory systems.} \end{figure} \noindent \textbf{Memory latency analysis.} Figure \ref{fig:norm_memlat} shows the average memory latencies of different GPU platforms under various workloads, normalized to \texttt{Ohm-base}. \texttt{Auto-rw} can reduce the average memory latencies by 14\% and 4\%, respectively, in planar and two-level memory modes, compared to \texttt{Ohm-base}. This is because \texttt{Auto-rw} can reduce the time of the optical channel to do data migration, so that memory devices can use the optical channel earlier to serve the regular memory requests. \texttt{Ohm-WOM} in planar memory mode leverages swap function to schedule the data migration through the dual routes in parallel with the memory requests, which does not occupy the optical channel. Thus, \texttt{Ohm-WOM} achieves the minimum memory access latency, which is 28\% shorter than \texttt{Auto-rw}, in planar memory mode. Similarly, the benefit of memory latency reduction brought by \texttt{Ohm-WOM} in two-level memory mode is 24\%, compared to \texttt{Auto-rw}. Although the reverse-write function in \texttt{Ohm-WOM} cannot shorten the latency of serving the memory requests from XPoint, the reverse-write function leverages the dual routes to reduce the latency of copying data from XPoint to DRAM, making the data migration procedure complete earlier. Compared to \texttt{Ohm-WOM}, \texttt{Ohm-BW} can serve the memory requests faster when swap function is invoked. Therefore, \texttt{Ohm-BW} further reduces the memory latency by 6\% in planar memory mode. \texttt{Ohm-BW} reduces the performance gap between a heterogeneous memory system and an ideal memory system from 67\% to 18\%. This is because \texttt{Ohm-BW} effectively leverage its DRAM cache to serve the most incoming memory requests. \noindent \textbf{Optical channel usage.} Figure \ref{fig:datamove} shows the fraction of the optical channel bandwidth consumed by data migration in different memory platforms. As \texttt{Auto-rw} can partially do the data migration in the dual routes, it can reduce the bandwidth usage for data migration by 8\% and 17\%, respectively, in planar and two-level memory modes. \texttt{Ohm-WOM} in planar memory mode further reduces the bandwidth usage by 54\% because it performs most of data migrations in the dual routes. \texttt{Ohm-WOM} in the two-level memory mode can fully eliminate the optical channel occupancy caused by data migration. This is because the auto-read/write and reverse-write functions migrate the data in an independent route, when DRAM and XPoint serve the memory requests. \noindent \textbf{Energy consumption.} Figure \ref{fig:norm_energy} shows the energy consumption of different components within the memory systems of the evaluated GPU platforms. Compared to \texttt{Hetero}, \texttt{Ohm-base} replaces the electrical memory channels with an optical channel, which can reduce the DMA's power by 57\%, on average. As the user applications generate a fixed amount of memory requests to DRAM, the dynamic DRAM energy to serve the memory requests is the same as those of \texttt{Ohm-base}, \texttt{Auto-rw}, \texttt{Ohm-WOM} and \texttt{Ohm-BW}. On the other hand, the static DRAM energy is proportional to the total execution time when DRAM is powered on. As \texttt{Ohm-WOM} can reduce the execution time of user applications, it, on average, can reduce the static DRAM energy by 19\% and 11\%, respectively, compared to \texttt{Ohm-base} and \texttt{Auto-rw}. Similar to dynamic DRAM energy, the XPoint in different heterogeneous memory platforms serve the same number of memory requests, which consumes the same amount of energy. \texttt{Auto-rw}, \texttt{Ohm-WOM} and \texttt{Ohm-BW} consume higher optical channel energy than \texttt{Ohm-base}. This is because the laser source needs to increase its power to meet the sensing accuracy of the photonic detectors in the dual routes. As laser power has a minor impact on the energy cost than DRAM and XPoint, \texttt{Ohm-WOM} still decreases the overall energy consumption by 2\% and 1\% in planar and two-level memory modes, against \texttt{Ohm-base}. \begin{figure} \centering \subfloat[Sensitive testing.]{\label{fig:sensitive3}\rotatebox{0}{\includegraphics[width=0.48\linewidth]{figs/sensitive3}}} \hspace{3pt} \subfloat[Bit error rates.]{\label{fig:ber}\rotatebox{0}{\includegraphics[width=0.48\linewidth]{figs/ber}}} \caption{\label{fig:}Performance analysis of varying optical waveguides and reliability analysis of Ohm-GPU.} \end{figure} \subsection{Sensitive testing, reliability and Overhead} \label{sec:sensitive} \noindent \textbf{Sensitive tests.} While a single optical waveguide can achieve the bandwidth same as electrical memory channels of 192 lanes, Ohm-GPU can employ multiple optical waveguides under the same area constrains as the electrical memory channels. Figure \ref{fig:sensitive3} shows the performance improvement brought by multiple optical waveguides in Ohm-GPU. \texttt{Ohm-base} with 8 optical waveguides improves the system performance than \texttt{Hetero}, by 41\%, on average. This is because employing multiple optical waveguides can significantly reduce the DMA latency of the heterogeneous memory system. \texttt{Ohm-BW} also benefits from the increased number of optical waveguides. The performance improvement can be 17\%. \noindent \textbf{Reliability.} We evaluate the data integrity of the end-to-end communication in various GPU memory systems, and the results are shown in Figure \ref{fig:ber}. When serving memory requests, \texttt{Ohm-base} can achieve BER as low as 7.2$\times$10$^{-16}$ with our default configuration of laser light power. Since \texttt{Ohm-WOM} and \texttt{Ohm-BW} deploy more MRR-based modulators and detectors in the optical infrastructure for the auto-read/write and swap functions, modulating and detecting data in these MRRs can attenuate the strength of laser signals (cf. optical power model in Table \ref{tab:sys-config}). To compensate for the laser power loss, we increase the powers of the laser source by 2$\times$ and 4$\times$ in \texttt{Ohm-WOM} and \texttt{Ohm-BW}, respectively. The measured BER of auto-read/write and swap functions are 6.1$\times$10$^{-16}$ and 9.9$\times$10$^{-16}$, respectively, in \texttt{Ohm-WOM}, while the worst BER in \texttt{Ohm-BW} is 9.3$\times$10$^{-16}$. To sum up, the optical channel of Ohm-GPU satisfies the reliability requirement of 10$^{-15}$ BER. \begin{table}[] \resizebox{\linewidth}{!}{ \begin{tabular}{|l|c|c|c|c|} \hline \textbf{Modes} & \multicolumn{2}{c|}{\textbf{Planar memory}} & \multicolumn{2}{c|}{\textbf{Two-level memory}} \\ \hline \textbf{DRAM} & \multicolumn{2}{c|}{1GB x 12, \$140} & \multicolumn{2}{c|}{1GB x 6, \$70} \\ \hline \textbf{XPoint} & \multicolumn{2}{c|}{8GB x 12, \$125} & \multicolumn{2}{c|}{32GB x 12, \$499} \\ \hline & Modulators & Detectors & Modulators & Detectors \\ \hline \textbf{Ohm-base} & 2,112/\$3 & 2,112/\$3 & 2,368/\$3 & 2,368/\$3 \\ \hline \textbf{Ohm-BW} & 2,176/\$3 & 3,136/\$5 & 2,368/\$3 & 4,928/\$7 \\ \hline \textbf{VCSEL} & \multicolumn{4}{c|}{\$100} \\ \hline \end{tabular}} \caption{\label{fig:overhead}Cost estimation of different Ohm memories. \vspace{-10pt}} \end{table} \noindent \textbf{Overhead analysis.} Table \ref{fig:overhead} lists the estimated cost of the key components in different platforms. We configure up to 24 memory devices in a GPU, while the number of DRAM and XPoint chips are set to follow the capacity ratio listed in Table \ref{tab:sys-config}. The price of memory devices are calculated based on \cite{gddr6-price,optane-price}. We refer to Figure \ref{fig:optical_overall} to calculate the total number of MRRs required in each memory platform. The fabrication cost of MRRs is estimated based on \cite{optic-fab}. Although \texttt{Ohm-BW} employs 41\% more MRRs (at the cost of \$4) than \texttt{Ohm-base} to support the dual routes in the optical channel, \texttt{Ohm-BW} improves the performance by 20\%, demonstrating higher performance/cost ratio. In addition to optical components, \texttt{Ohm-BW} also employs a DDR monitor and DDR sequence generator in the memory controller and the XPoint controller, respectively. The DDR monitor is comprised of control logic and a few registers, which enable/disable a DDR interface controller to receive data from the data bus, while the DDR sequence generator converts the memory requests into DDR packets. Our implementation of DDR sequence generators requires 2.8K LUTs and 4.7K flip-flops in FPGA, whose cost is negligible to the XPoint controller. Considering the launch price of NVIDIA K80 GPU (\$5k), planar and two-level memory modes enabled \texttt{Ohm-BW} only increase total cost by 7.6\% and 13.5\%, respectively. We also evaluate the cost-performance (CP) ratio of NVIDIA K80 GPU (\texttt{Origin}), our Ohm-GPU (\texttt{Ohm-BW}) and an ideal GPU (\texttt{Oracle}), and the results are shown in Figure \ref{fig:cpvalue_fig}. The CP ratio of \texttt{Ohm-BW} is 155\% and 24\% higher than that of \texttt{Origin} and \texttt{Oracle}, respectively, indicating that the performance benefits brought by Ohm-GPU overwhelms its cost overhead. \subsection{Challenges of Ohm Memory System} \label{sec:motivation} We perform a simulation-based study of the two heterogeneous memory modes to measure the data migration overheads observed in the baseline Ohm memory system. We measure the effective memory bandwidth (consumed by different GPU workloads) and the wasted memory bandwidth (used for the data migration) of diverse benchmarks \cite{che2009rodinia,pouchet2012polybench,nai2015graphbig}. In addition, we compare average memory access latencies of our baseline Ohm memory system (\texttt{baseline}) with an oracle Ohm memory system (\texttt{Oracle}), which allocates a dedicated optical channel for the data migration. Figure \ref{fig:motiv1} shows each fraction of effective and wasted memory bandwidths. Our evaluation shows that the data migration in the planar memory mode accounts for 39\% of the total memory bandwidth, on average. Similarly, in the two-level memory mode, the data migration between DRAM and XPoint overall accounts for 26\% of total memory bandwidth. As a result, compared to \texttt{Oracle}, the data migration of \texttt{baseline} increases the average memory access latencies by 54\% and 47\% in the planar and two-level memory modes, on average, respectively. \subsection{Memory System Design to Remove Migration Overhead} \noindent \textbf{Overall design.} To hide the data migration penalties, we propose a design of \emph{dual routes} that can serve the memory requests and data migration in parallel. Specifically, we design a new optical network infrastructure to create two routes in the same optical channel: 1) a \emph{data route} connects the memory controller and memory devices together and 2) a \emph{memory route} connects between two memory devices. While processing memory requests via the data route of an optical channel, Ohm-GPU can simultaneously perform the data migration via the memory route in the same optical channel. Since the dual routes are unfortunately not supported by the existing memory system, we also introduce a few new memory system designs to reap the benefits of our dual routes. \begin{figure} \centering \includegraphics[width=1\linewidth]{figs/timing.eps} \caption{\label{fig:timing}Timing diagram of auto-read/write.\vspace{-5pt}} \vspace{-5pt} \end{figure} \noindent \textbf{Auto-read/write function.} Traditional memory system relies on the memory controller to copy data back and forth for data migrations between two memory modules. The data migrations make the memory channel and controller unavailable for 39\% of total execution time (cf. Figure \ref{fig:motiv1}). To address this, Ohm-GPU introduces a new function, referred to as \textit{auto-read/write}, in the XPoint controller. Figure \ref{fig:timing} shows a timing diagram of data migrations with assistance of our auto-read/write function. As an example of the planar memory mode (cf. Figure \ref{fig:timing}a), the memory controller needs to perform the data migration between DRAM and XPoint (\redcircled{2}$\sim$\redcircled{4}) while serving a memory request (\whitecircled{1}\whitecircled{5}). To migrate data from DRAM to XPoint, the memory controller firstly reads the target data from DRAM via the data route (\redcircled{2}). During this time, our XPoint controller also performs a \emph{snarf} operation \cite{ramanujan2014dynamic}. The snarf enables us to monitor the communication between the memory controller and DRAM (\redcircled{2}) and hook necessary information from the memory route such as a command type, address, data, ECC, and tag bits. The XPoint controller utilizes the collected request information to perform a data migration in XPoint without assistance of the memory controller. Since DRAM lacks a controller to perform the snarf operation, the auto-read/write function cannot be used in the process of copying data blocks from XPoint to DRAM. That is, the memory controller still needs to read the target data from XPoint (\redcircled{3}) and write this data to DRAM (\redcircled{4}) one by one. Figure \ref{fig:timing}b shows auto-read/write assisted data migrations in the two-level memory mode. When the memory controller inquires the target metadata/data from DRAM (\whitecircled{1}\whitecircled{2}), the XPoint controller leverages a snarf operation to extract the request information and the target metadata/data. The XPoint controller detects a DRAM cache miss by comparing the request's address and the tag bits stored in the DRAM cacheline. As the inquired data should be evicted to XPoint, the XPoint controller takes over the task of a DRAM data eviction from the memory controller. However, the memory controller is required copying new data from XPoint to the DRAM cache-line (\whitecircled{3}\whitecircled{4}). \noindent \textbf{Swap and reverse write functions.} To reduce the overhead of migrating data from XPoint to DRAM, we design two new memory functions, each being referred to as \emph{swap} and \emph{reverse write}. These new functions compensate the drawbacks of the auto-read/write. Specifically, the swap function allows the XPoint controller to directly manage the read and write memory transactions in DRAM via the DDR interface. However, the swap function faces three challenges: first, unlike the auto-read/write function, which snarfs I/O commands and data from the memory channel, a XPoint controller should be informed of the request information to initialize the swap function. Second, the XPoint controller cannot generate correct DDR command sequences as it is unaware of the states (i.e., precharged, activated, etc.) of the target DRAM bank. Third, the memory controller may have channel-level conflicts with the XPoint controller during the execution of our swap function. Since the memory controllers cannot issue memory requests during a DRAM refresh period, one possible solution to resolve the conflicts is to constrain the direct data copy operations in the DRAM refresh period \cite{lee2020nvdimm}. This approach, unfortunately, serializes the memory requests and data migration requests, which can severely degrade the GPU performance. To address all these challenges, we compose a new memory command, \emph{SWAP-CMD}, which is used by the memory controller to demand the swap function in the XPoint controller (cf. \redcircled{1} in Figure \ref{fig:timing_swap}a). This command reuses the data route to transfer the metadata information such as DRAM address, XPoint address, and data size. Afterwards, the memory controller can serve the incoming memory request (\whitecircled{2}) while the XPoint controller migrates data between DRAM and XPoint. The XPoint controller signals the memory controller once the data migration completes (\redcircled{3}). Note that, since the memory controller records the states of all DRAM banks, we leverage the memory controller to preset the target DRAM bank to a stable state (i.e., activated state) before it issues the SWAP command to the XPoint controller. To avoid a potential memory channel conflict, the XPoint controller can synchronize its progress with the memory controller by leveraging the DDR-T protocol. \begin{figure} \centering \includegraphics[width=1\linewidth]{figs/timing_swap.eps} \caption{\label{fig:timing_swap}Timing diagram of data migration with our auto-read/write, swap, and reverse write.\vspace{-5pt}} \vspace{-5pt} \end{figure} The swap function yet cannot completely reduce memory traffic for the two-level memory mode due to two issues: 1) the communication between the memory controller and DRAM cannot be avoided, as the memory controller always needs to read data and tag information from DRAM to check if there is a DRAM cache miss; 2) when there is a DRAM cache miss, a memory controller should read the target data from XPoint to serve the memory request as soon as possible, rather than being stalled by the swap function. Instead, the reverse write function can address such the issue by collaborating with our auto-read/write function. Specifically, while the auto-read/write function can use the dual routes to reduce the bandwidth of transferring data from DRAM to XPoint (cf. \whitecircled{1} in Figure \ref{fig:timing_swap}b), our reverse-write function can leverage the same independent route to move data from XPoint to DRAM in addition to transferring data to the memory controller through the data route (cf. \whitecircled{2} in Figure \ref{fig:timing_swap}b). \subsection{Optical Network Infrastructure} \noindent \textbf{MRR design for dual routes.} The traditional optical channel does not allow the co-existence of dual routes owing to a design issue of the MRR-based photonic transmitter and receiver \cite{shacham2007design,beausoleil2008nanoelectronic}. In practice, the laser light of one wavelength can be modulated and absorbed by only a pair of photonic transmitter and receiver, respectively. This makes it difficult for other photonic transmitters or receivers to either reuse or snarf the same laser light. We may employ an optical power splitter \cite{vantrease2008corona} to split a single laser light to multiple memory devices such that the same light bits can be shared among the memory controller, DRAM and XPoint. However, most power splitters cannot change their status (i.e., enabled/disabled) or adjust the split ratio at a runtime. This inflexibility renders the power splitters difficult to build a flexible independent route between any two memory devices. Although \cite{zhou2013probe, morris2013extending} proposed a tunable power splitter, the tuning time, unfortunately, is as long as 6 $ns$, which is even longer than DRAM data burst latency. Instead, we adopt an idea from \cite{peter2016active}, which proposes a new tunable power splitter based on a modified MRR. Compared to the traditional power splitter \cite{vantrease2008corona,zhou2013probe, morris2013extending}, the MRR-based power splitter is flexible to change the split ratio and consumes shorter tuning time. \cite{peter2016active} reports that the MRR-based power splitter reduces the resonance tuning time to only 500 $ps$. The key insight behind this approach is that MRR can partially couple the laser light of a specific wavelength if the MRR is tuned to be in partial resonance with the laser light. The uncoupled laser light can traverse to other memory devices. The status between fully-coupled (MRR fully absorbs the laser light) and non-coupled (not absorbs the laser light) is called \emph{half-coupled}. We'll explain how a half-coupled MRR (HCMRR) enables dual routes in an optical channel, shortly. \noindent \textbf{Photonic transmitter and receiver design.} To enable the dual routes for our auto-read/write and reverse write functions, Ohm-GPU configures the photonic receiver in DRAM as the half-coupled MRR. Since the half-coupled MRR based photonic receiver only splits the laser light rather than fully absorbs it, the laser light, which is modulated by the memory controller, can transverse to the XPoint. The XPoint controller can, thus, snarf request/data information from the laser light. On the other hand, to enable dual routes for swap function, one laser light stream needs to carry two pieces of data, one from memory requests and another from data migration requests. To this end, we leverage a write-once memory (WOM) coding \cite{zhang2015opennvm}. By using WOM coding, Ohm-GPU can modulate two different 2-bit data in a 3-bit laser light signal. We will explain more details in Section \ref{sec:hcmrr}. Since a 3-bit laser light signal can only carry 2-bit data, WOM coding reduces the effective memory bandwidth by 33\% for the memory requests. To avoid the bandwidth wastage, we propose an aggressive approach. Specifically, photonic transmitters are also configured as the half-coupled MRR to enable the dual routes for our swap function. While the traditional photonic transmitter in the memory controller modulates the data bit 0 by fully absorbing the laser light, the half-coupled MRR ensures that the laser light maintains at least half of power strength, regardless of carrying the data bit 0 or 1. Thanks to the half-coupled MRR, the XPoint controller can reuse the remaining laser light to modulate its own data. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{figs/swap.eps} \caption{\label{fig:swap}Design details of swap function.\vspace{-5pt}} \vspace{-5pt} \end{figure} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{figs/reversewrite.eps} \caption{\label{fig:reversewrite}Design details of our reverse-write function.\vspace{-5pt}} \vspace{-5pt} \end{figure} \begin{figure*} \centering \includegraphics[width=1\linewidth]{figs/optical.eps} \caption{\label{fig:optical}Auto-read/write and swap functions under the assistance of dual routes in the optical channel.\vspace{-5pt}} \vspace{-5pt} \end{figure*} \begin{figure} \centering \includegraphics[width=1\linewidth]{figs/wom.eps} \caption{\label{fig:wom}Creating dual routes with wom coding.\vspace{-5pt}} \vspace{-5pt} \end{figure} \noindent \textbf{Optical channel optimization for low cost.} While the proposed photonic transmitter and receiver designs make the dual routes feasible in an optical channel, it is challenging to deploy the corresponding photonic hardware in our GPU memory system. The main reason behind such a difficulty is that it needs a fine-granule tuning method for one MRR to precisely switch the status among coupled, half-coupled, and non-coupled. For example, \cite{peter2016active} reports the tuning procedure increases the latency by 5$\times$ from 100 $ps$ to 500 $ps$, which is too long compared to the data transmission rate of the laser light. To address this challenge, we propose to employ an array of photonic transmitters and detectors in each memory device. To configure an independent route between any two devices, each memory device needs four pairs of photonic transmitters and detectors in total; two pairs, which are made from the fully-coupled and half-coupled MRRs, respectively, are attached to the forward path from memory controller to memory device, and the same two pairs are attached to the backward path. Unfortunately, this new design introduces a huge area cost. We optimize such array by reducing the number of MRRs to be just sufficient to serve our auto-read/write, reverse-write and swap functions. We simplify the array by leveraging the insight that different operational modes of heterogeneous memory require different memory functions. \begin{figure*} \centering \includegraphics[width=1\linewidth]{figs/optical_overall.eps} \caption{\label{fig:optical_overall}The transmitter and receiver layout of our optical channel.} \end{figure*} \subsection{Swap and Reverse-Write Functions} To realize swap function, we introduce a DDR sequence generator in the XPoint controller to manage the memory read and write transactions of DRAM. Figure \ref{fig:swap} shows the implementation details of our swap function. As shown in the figure, before sending a swap command to XPoint, the memory controller firstly checks the state of the target DRAM. If the target data is not loaded in DRAM row buffer, the memory controller issues the precharge and activate commands to clean the row buffer and load the target data from DRAM cells to row buffer, respectively (\whitecircled{1}). Afterwards, the memory controller informs the XPoint controller of the swap command and postpones scheduling the memory requests that conflict with the swap command (\whitecircled{2}). The XPoint controller then leverages the DDR sequence generator to control the read and write transactions of the target DRAM (\whitecircled{3}\whitecircled{4}). Once the swap function completes, the XPoint controller sends a ready signal to the memory controller via DDR-T protocol (\whitecircled{5}). The memory controller then responds with confirmation signal and resumes the stalled requests (\whitecircled{6}). To implement the reverse-write function, we also introduce a DDR monitor in the memory controller. Similar to XPoint, the DDR monitor module enables the memory controller to monitor the memory channel and extract request information from the communication between XPoint and DRAM. Figure \ref{fig:reversewrite} shows the implementation details of the reverse-write function. Before XPoint starts the reverse-write function, the XPoint controller sends a ready signal to notify the memory controller to snarf data from the memory channel (\whitecircled{1}). The memory controller then stops issuing new memory requests, enables the DDR monitor, and then sends a confirmation signal to the XPoint controller (\whitecircled{2}). Afterwards, the memory controller snarfs the data from the memory channel, while XPoint writes data to DRAM (\whitecircled{3}). Once XPoint sends a completion signal to the memory controller (\whitecircled{4}), the memory controller serves the requests with the collected data. \subsection{Half-coupled Micro Ring Resonator} \label{sec:hcmrr} Figure \ref{fig:optical}a shows our approach of generating dual routes to support auto-read/write and reverse-write functions. To snarf messages from the optical channel, the photonic receiver of XPoint tunes its resonance wavelength to $\lambda_{0}^{'}$, whose frequency shifts slightly from the message-carrying wavelength $\lambda_{0}$. Due to this wavelength shift method, the photonic receiver partially couples the laser light of wavelength $\lambda_{0}$. Thus, the remaining laser light traverses from XPoint to DRAM and its data are detected by DRAM's photonic detector. Figure \ref{fig:wom} shows how our Ohm-GPU can leverage the half-coupled MRR and WOM coding to generate our dual routes for the swap function. Specifically, by referring the data-code mapping table, the transmitters of the target memory and the XPoint controllers can encode their data into 1st and 2nd write codes, respectively. The write codes are then modulated in the same light signals, which will be detected and decoded by the corresponding receivers. In the figure, the memory and XPoint1 controllers send data to XPoint0 and DRAM, respectively. When the memory controller transfers data ``10'' to XPoint0, the target data is encoded into a write code ``010'' and modulated into a laser light (\redcircled{1}). The half-coupled MRR-based receiver (HCMRR) of XPoint0 controller gets the laser light and decodes the write code to data ``10''. This process consumes the laser light by half, which is ``$\dfrac{1}{2}$1$\dfrac{1}{2}$''. XPoint1 controller can modulate its own data ``01'' in the same laser light, which turns the light bits to ``11$\dfrac{1}{2}$'' (\redcircled{2}). DRAM can decode the laser light to retrieve data ``01'' by referring to the data-code mapping table. To fully utilize bandwidth of the optical channel, we propose an aggressive approach to multiplex the data of memory requests and data migration requests on the same optical channel, which is shown in Figure \ref{fig:optical}b. Specifically, when modulating electrical bit `0' as light bit, the transmitter in memory controller does not tune MRR to fully couple the laser light. Instead, the photonic transmitter tunes its resonance wavelength to $\lambda_{0}^{'}$, reducing the strength of the laser light by half. For example, a data stream of ``00110'' is modulated as ``$\dfrac{1}{2}\dfrac{1}{2}$11$\dfrac{1}{2}$'' in terms of laser light strength. The photonic detector can identify bits 0 or 1 based on the light strength. Note that the photonic detector in XPoint also modulates the resonance wavelength to $\lambda_{0}^{'}$, which partially couples the laser light. At this juncture, the remaining laser light maintains at least one fourth of its original transmission power (``$\dfrac{1}{4}\dfrac{1}{4}\dfrac{1}{2}\dfrac{1}{2}\dfrac{1}{4}$'' in the example). The laser light continues to traverse between XPoint and DRAM. The transmitter of XPoint can modulate its own data stream ``10101'' in the remaining laser light by tuning MRR to fully-coupled or non-coupled. After modulation, the strength of the laser light becomes ``$\dfrac{1}{4}$0$\dfrac{1}{2}$0$\dfrac{1}{4}$''. The photonic detector in DRAM fully couples the laser light and detects the data stream of ``10101'' by checking the light strength. \subsection{Optical Channel Optimization for Low Cost} Creating dual routes to support auto-read/write, write-reverse and swap functions in any memory device requires at least three transmitters and three receivers in DRAM, and two transmitters and three receivers in XPoint. Figure \ref{fig:optical_overall}a shows a general optical channel design. Specifically, DRAM and XPoint need to employ a pair of MRR-based photonic transmitter and receiver (i.e., \textit{T3}, \textit{R8}, \textit{T5}, \textit{R6}, \textit{T7} and \textit{R5} in Figure \ref{fig:optical_overall}a) to support conventional photonic communication. While both DRAM and XPoint need to employ half-coupled MRR-based photonic receivers in both the forward path and backward path to enable auto-read/write function (i.e., \textit{R1}, \textit{R2}, \textit{R3}, \textit{R4}, \textit{R7} and \textit{R11}), DRAM needs half-coupled MRR-based photonic receivers in the backward path to enable write-reverse function (i.e., \textit{R4} and \textit{R7}). Lastly, to support data swap function in the dual routes, the half-coupled MRR-based photonic transmitters should be employed in DRAM and XPoint (i.e., \textit{T4}, \textit{T6} and \textit{T8}). While the photonic transmitters of \textit{T9}, \textit{T10} and \textit{T11} are not necessary, they can improve the parallelism of scheduling memory requests and data swap function in parallel. We further reduce the number of MRRs based on the characteristics of different operational modes in heterogeneous memory. Specifically, planar memory mode only needs data swap function and two-level memory mode only needs auto-read/write and reverse-write functions. Figure \ref{fig:optical_overall}b shows the MRR deployment in different operational modes. Our customized design can reduce the number of required MRRs by 58\% and 42\% in planar and two-level memory modes, respectively, compared to the general design. Note that, for simplicity, only a pair of DRAM and XPoint is depicted in the figure. But our analysis can be applied to any number of DRAM and XPoint. \section{#1}} \newcommand{\subsect}[1]{\subsection{#1}} \newcommand{\subsubsect}[1]{\subsubsection{#1}} \newcommand{\mysect}[1]{\subsect{#1}} \newtheorem{ourtask}{Task} \section{Introduction} \label{sec:intro} \input{introduction} \section{Background} \label{sec:background} \input{background} \section{Designs for Migration Reduction} \label{sec:highlevelview} \input{highlevelview} \section{Hardware Implementation} \label{sec:implementation} \input{implementation} \section{Evaluation} \label{sec:evaluation} \input{evaluation} \section{Related Work} \label{sec:relatedwork} \input{relatedwork} \section{Conclusion} \label{sec:conclusion} \input{conclusion} \bibliographystyle{IEEEtranS}
{'timestamp': '2021-09-14T02:19:03', 'yymm': '2109', 'arxiv_id': '2109.05430', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05430'}
arxiv
\section{Introduction} \vspace{-1mm} Visual understanding of scenes are broadly covered by object detection \cite{szegedy2013deep,papageorgiou2000trainable} and localization \cite{sullivan2001bayesian, conaire2007improved} for single or multiple objects. Evolved from detection of various objects, image segmentation \cite{cooper1998tractability, alvarez2012road} is another research topic which helps to understand the attributes of the scene. While these techniques supply some useful information of the image, but a scene also largely depends on the interactions or relations between objects. This idea led to scene graphs which describe the scene by incorporating the objects and their pairwise relations. This relation is represented by a directed edge pointing from the subject to the object. Evaluating a scene by detecting the objects and the relationships between them allows building a graph consisting of nodes representing the objects and the edges representing the relations. It consists of number of triplets represented in $<$subject-relationship-object$>$ form. They help in aiding deep understanding of the scene for various vision tasks such as visual reasoning \cite{shi2019explainable}, image captioning \cite{yang2019auto, li2019know}, image retrieval \cite{johnson2015image, schuster2015generating, schroeder2020structured} and visual question answering \cite{zhang2019empirical,ghosh2019generating,teney2017graph}. To improve these applications and their benefits, it is crucial to have a well performing model which generates scene graphs that corresponds to the actual visual scene. The directional nature of a triplet in scene graph defines the subject and object in a triplet. Scene graph generation (SGG) is considered a complex problem in computer vision because of the imbalanced nature of the datasets and intricate relationship information. As stated in MOTIFS \cite{zellers2018neural}, combinations of at least two triplets appear in many images. So, the presence of some objects highly increase the probability of the presence of other objects. Communication i.e. information flow between the detected objects has been shown to be beneficial for improving the performance of scene graph generation models \cite{zellers2018neural, chen2019counterfactual}. \begin{figure} \includegraphics[scale=0.33]{./figures/sgg1.png} \caption{Two different scene graphs of the same given image on the left. Top: The ground-truth scene graph as annotated in the Visual Genome dataset. Below: A generated scene graph. As in many cases, the generated scene graph does capture the visual scene correctly, since the scene graph generation model only predicts frequently appearing relationships.} \vspace{-7mm} \label{sgg_1} \end{figure} The frequency distribution of the relationship within the Visual Genome dataset is long-tailed \cite{KrishnaZGJHKCKL16}. Due to this, scene graph detection models can already achieve good performance by only predicting the most frequent relationship for the respective subject-object pair. Figure \ref{sgg_1} illustrates the problem almost every SGG model faces. In many object pairings, the relationship is trivial and mostly possessive or geometric (e.g. \textit{on}, \textit{under}, or \textit{next to}). The detailed descriptive and semantic relationships such as \textit{jumping over} as shown in Figure \ref{sgg_1} (given in the ground-truth) will not often be predicted since it rarely occurs. For creating models that represent less frequent relationships more precisely, an approach to handle dataset bias must be found. Since the bias in the dataset can also be beneficial, e.g. the probability for the relationship \textit{reading} will be much higher than for \textit{eating} if the subject-object pair given is person and book \cite{tang2020unbiased}, traditional debiasing methods will most likely strongly harm the performance of the model. For this reason, the handling of the bias in the dataset is one of the most under-explored properties of the scene graph generation task. In this paper, we propose a novel model for SGG. The objects present in an image are highly dependent on the presence of other objects, for instance, if there is a bike in the scene, then there will be two tyres in the same scene with a very high probability. This model uses a bidirectional GRU (BiGRU) layer to send information from every object to every other. This allows benefiting from the fact that some objects will increase the possibility for specific other objects to be present. Subsequently to this layer that covers the object-object communication, a transformer encoder layer is used to predict the object classes. Objects and their preferred or observed relations are closely connected. To extract the information for the edge, a similar approach as in \cite{zellers2018neural} is followed to specify the edge context for every detected object. We use an additional transformer encoder layer for this task of extracting the edge context features. Using the object representations, their respective edge context is then used for the relationship prediction. In this procedure, a log-softmax function is applied to the subject-object pairwise relationship distribution. Following this Frequency Softening (FS), a Bias Adaptation (BA) approach \cite{lin2020gpsnet} is used. The bias for every subject-object is controlled by the bias adaptation term which takes scene-specific inputs to vary the amount of added bias. The contribution summary of the proposed BGT-Net is given in four modules to improve scene graph generation performance: (1) Object-object communication is performed using the BiGRU's. (2) A transformer encoder with scaled-dot-product attention is used to predict object classes after they have received information about the other objects present in the scene. (3) For every object, a second transformer encoder is used to gather information for the edges. (4) To tackle the bias in the relationship distribution, FS and BA \cite{lin2020gpsnet} is adopted. The evaluation efficacy of the proposed BGT-Net is performed on three SGG datasets: Visual Genome (VG) \cite{KrishnaZGJHKCKL16}, OpenImages (OI) \cite{abs-1811-00982}, and Visual Relationship Detection (VRD) \cite{lu2016visual}. We perform extensive experiments and ablation study to demonstrate the effectiveness of BGT-Net. Experimental results illustrate that the proposed BGT-Net outperforms the state of the art SGG results on a common metric Recall@K and on different datasets to the best of our knowledge. \vspace{-2.5mm} \begin{figure*}[tbp] \setlength\abovecaptionskip{-1.8\baselineskip} \setlength\belowcaptionskip{2pt} \begin{center} \vspace{-3mm} \includegraphics[height=5cm, width=17.5cm]{./figures/BGT-Net.png} \vspace{0mm} \topcaption{The framework of BGT-Net uses Faster R-CNN (with VGG-16 or ResNext-101 as the backbone) to get the visual features and spatial locations of object proposals. It includes various sub-modules for the task of SGG: (1) New technique of using BiGRU for object-object communication, (2) Novel method of using a transformer encoder with scaled-dot-product attention for predicting object classes after they have received information of the other objects present in the scene, (3) Additional transformer encoder is used to get the edge features, (4) FS and BA are used for dealing with the bias in the dataset. } \vspace{-1mm} \label{BGT-Model} \end{center} \end{figure*} \vspace{-0.075mm} \section{Related Work} \vspace{-1.5mm} From the ongoing research in scene graph generation, two different approaches for scene graph construction have developed. In the less common two-stage approach \cite{DBLP:journals/corr/abs-1812-01880, herzig2018mapping, chen2019counterfactual, DBLP:journals/corr/abs-1812-01880}, attributes of the scene graph are used in the second training step to refine the results produced by the first stage. Much more common are the one-stage approaches \cite{chen2019counterfactual,zellers2018neural,chen2019knowledge,DBLP:journals/corr/XuZCF17, yang2018graph, lin2020gpsnet,li2017scene,lu2016visual,li2018factorizable, qi2019attentive} which focus only on object detection and relationship classification, while almost neglecting intrinsic features. The proposed BGT-Net follows a one step approach and has the following advantages as compared to the literature work: (1) It uses object-object communication which improves the performance in SGG; (2) It deploys transformer encoder for object and edge context prediction which has shown to be highly beneficial in optimizing the parameters of SGG; (3) It is easy to train. The MOTIFS \cite{zellers2018neural} stated in the early days of scene graph generation, that there are different combinations of triplets that appear in a lot of images. Therefore, a dependency between object appearances is present in the datasets. To leverage this information object communication has been examined in the CMAT model \cite{chen2019counterfactual} and improved the performance of the model. All of the published works show difficulties with the bias present in the Visual Genome dataset, which is widely used in the scene graph generation task. This bias arrives from the long-tailed relationship distribution. The GPS-Net \cite{lin2020gpsnet} tackled this problem with FS and BA which worked well compared to the previous works. The overall performance of the model could be improved as well as improvements in mean Recall@K were achieved, which gives reasoning about the positive effect of their approach in handling the dataset bias. So, motivated from GPS-Net, BGT-Net uses FS and BA. \break While the GPS-Net changed the way the model was built, another recent work \cite{tang2020unbiased} developed a Scene Graph Diagnosis toolkit that can be used on a casually built scene graph. This tool kit is based on casual inference. Drawing the counterfactual causality to the proposed graph allows inferring with the bad bias. This approach did largely improve the mean Recall@K but decreased the other metrics significantly. Similarly \cite{yan2020pcpl}, adaptively changed the weights of the loss by using the correlation between the relationship classes. This work improved mean Recall@K but had overall quite low Recall@K results. \vspace{-1mm} \section{Approach} \label{chp:GRU-Transformer} The illustration of the BGT-Model can be found in Figure \ref{BGT-Model}. The regions of interest and object proposals are obtained by employing a Faster R-CNN object detector \cite{ren2015faster}. Following the VG-split \cite{DBLP:journals/corr/XuZCF17}, there are 151 object categories (including 'background') and 50 relationship categories (including 'no relation'). For every proposal $i$, the visual feature $\boldsymbol{\hat{x_{i}}}$ is formed by concatenating the ROI (region of interest) feature $\boldsymbol{f_{i}} \in \mathbb{R}^{2048}$, the class confidence scores $\boldsymbol{s_{i}} \in \mathbb{R}^{151}$, and the spatial feature of the proposal bounding box $\boldsymbol{s_{i}} \in \mathbb{R}^{4}$. For the next step, the $\boldsymbol{x_{i}} \in \mathbb{R}^{512}$ gets transformed by the projection of $\boldsymbol{\hat{x_{i}}}$ into a 512-dimensional subspace. For the relationship classification, the union feature $\boldsymbol{u_{i,j}} \in \mathbb{R}^{2048}$ for every pair of objects $i$ and $j$ is extracted in the object detection stage. These feature vectors representing the scene are used in the following modules of the BGT-Model. In Section \ref{subsec:obj_com}, the object communication step implemented with a BiGRU is explained in detail. Section \ref{chp:transformer}, introduces the object classification and edge information generation step using transformers. In Section \ref{chp:soft_adapt}, the FS of the long-tailed relationship distribution and the BA as a pre-processing for the relationship classification is described. \subsection{Object Communication} \label{subsec:obj_com} The object communication module takes the visual features $\boldsymbol{x_{i}}$ as input. The communication between the objects is implemented by a BiGRU. Due to the architecture of BiGRU, information from every object can flow to every other object. This information flow can be regulated by the BiGRU by learning which information shall be passed and which information shall be blocked. The output of the object communication step is therefore given by: \begin{equation} \hat{O} = BiGRU([x_{i}]_{i=1,2,...,n}) \end{equation} Where $\hat{O} = \{\hat{o}_{1}, \hat{o}_{2}, ... , \hat{o}_{n} \}$ are the object features after the communication step. The $\hat{o}_{i} \in \mathbb{R}^{1028}$ is obtained by concatenating the outputs $\overrightarrow{\hat{o}}_{i}$ (left to right in BiGRU) and $\overleftarrow{\hat{o}}_{i}$ (right to left in BiGRU), such that: \vspace{-2mm} \begin{equation} \hat{o}_{i} = [\overrightarrow{\hat{o}}_{i}, \overleftarrow{\hat{o}}_{i}] \in \mathbb{R}^{1028} \end{equation} \vspace{-5mm} \subsection{Object and Edge Transformers} \label{chp:transformer} The output $\hat{O}$ is projected to a 512-dimensional subspace to be fed into the Object transformer encoder. This transformer encoder follows the model architecture proposed by \cite{DBLP:journals/corr/VaswaniSPUJGKP17}, and takes the encoder block of the complete transformer model. This transformer encoder is built up by a Multi-Head attention layer, an Add \& Norm layer, a Feed Forward layer, and another Add \& Norm layer. The three inputs to the Multi-Head Attention layer are the values $V$, the keys $K$ and the queries $Q$. According to \cite{DBLP:journals/corr/VaswaniSPUJGKP17}, these three inputs are obtained from a single input. Using three different feed-forward fully-connected layers, yields the queries, keys, and values. For every attention head $i$ (here i=1,2,..,8) these values are calculated by: \vspace{-2mm} \begin{equation} Q_{i} = \hat{O} * W^{Q}_{i} \end{equation} \vspace{-5mm} \begin{equation} K_{i} = \hat{O} * W^{K}_{i} \end{equation} \vspace{-4mm} \begin{equation} V_{i} = \hat{O} * W^{V}_{i} \end{equation} \vspace{-1mm} Where $W^{Q}_{i} \in \mathbb{R}^{512 \times d_{k}}$, $W^{K}_{i} \in \mathbb{R}^{512 \times d_{k}}$ and $W^{V}_{i} \in \mathbb{R}^{512 \times d_{v}}$ are learnable parameter matrices. Also, $d_{k} = d_{v} = 64$ are the same for this application. From these values, the Scaled Dot-Product attention is calculated, such that the output of each attention head is given by: \vspace{-3mm} \begin{equation} Z_{i} = softmax(\frac{Q_{i} * K_{i}^{T}}{\sqrt{d_{k}}}) * V_{i} \end{equation} \vspace{-1mm} Concatenating $Z_{i}$'s give the output of the Multi-Head Scaled Dot-Product layer as $Z$. This is then fed through another fully-connected layer to bring it back to the dimension of the input matrix $\hat{O}$. \vspace{-3mm} \begin{equation} Z = concatenate(Z_{1}, Z_{2}, ... , Z_{n_{heads}}) \end{equation} \vspace{-1mm} The Add \& Norm layer adds the input of the previous Multi-Head Attention layer as a residual connection to the output of the attention layer. The normalization applied is a normalization layer following the approach of \cite{ba2016layer}. Here, it is suggested that the `covariate shift' problem can be reduced by changing the mean and the variance of the summed inputs in every layer. This is followed by a Feed Forward layer with two linear transformations and a ReLU activation followed by another Add \& Norm layer. This transformer encoder block gets repeated 6 times. The output $Z_{6}$ of the last repetition is then used to predict the object labels: \vspace{-3mm} \begin{equation} O = softmax(W_{o} * Z_{6}') \end{equation} \vspace{-1mm} Where $W_{o} \in \mathbb{R}^{512 \times 151}$ predicts the object class distribution for each detected object. Repeating this procedure but using the output $Z_{6}$ of the Object transformer as input to the Edge transformer yields feature vectors having information about the edges for every object. Similarly to \cite{zellers2018neural}, this information then can be used in the relationship prediction step. This edge information is given formally by: \vspace{-3mm} \begin{equation} E = TransformerEncoder(Z_{6}) \end{equation} \vspace{-1mm} Where $E = \{e_{1}, e_{2},..., e_{n}\}$ contains the edge information for every object. \subsection{Frequency Softening(FS), Bias Adaptation(BA)} \label{chp:soft_adapt} To handle the long-tailed relationship distribution present in the Visual Genome dataset, the procedure of softening this distribution and adapting the bias term for every subject-object pair form \cite{lin2020gpsnet} is adopted. The used features in this step is different than in the GPS-Net \cite{lin2020gpsnet} , but the principle stays the same. The softening of the relationship distribution is done by applying a log-softmax function to the original distribution. The softened frequency distribution is therefore given by Eq. \ref{eq:10}. The probability distribution $p_{i \rightarrow j}$ of every object pair $i$ and $j$ must be softened separately. Based on this definition, softening does not take any information of the respective visual scene into account. \vspace{-3mm} \begin{equation} \label{eq:10} \tilde{p}_{i \rightarrow j} = log\ softmax(p_{i \rightarrow j}) \end{equation} \vspace{-4mm} BA is used to get a case-specific adaptation of the above term. BA allows us to adjust the bias in the relationship prediction step. This adaptation term takes the appearance of the subject-object pair $i$, $j$ into account, by using their union feature $u_{i,j}$. The BA term $d$ can be calculated by: \vspace{-3mm} \begin{equation} d = W_{p} * u_{i,j} \end{equation} \vspace{-1mm} Where $W_{p} \in \mathbb{R}^{2048}$ is the transformation matrix and $u_{i,j}$ is the union feature of the subject-object pair. In the relationship prediction step, this bias term can be used as follows: \vspace{-3mm} \begin{equation} p_{i,j} = softmax( W_{r}(o'_{i} * o'_{j} * u_{i,j}) + d \odot \tilde{p}_{i \rightarrow j} ) \end{equation} \vspace{-0.5mm} In this equation, the bias $d \odot \tilde{p}_{i \rightarrow j}$ can be adjusted by changing $d$ accordingly. Here, $o'_{i} = [o_{i}, e_{i}]$ (same for $o'_{j}$) with '[-,-]' denotes the concatenation function representing the object features obtained in earlier steps. $W_{r}$ is the classifier that projects the features to the relationship class dimension. $ \odot $ denotes the Hadamard Product and $ * $ the fusion function. The fusion function for $ (x * y)$ is given by: \vspace{-3mm} \begin{equation} (x*y) = (W_{x}x + W_{y}y) - (W_{x}x - W_{y}y) \odot (W_{x}x - W_{y}y) \end{equation} \vspace{-1mm} With the parameter matrices $W_{x}$ and $W_{y}$, the fusion function is proposed to learn to count objects in images. \cite{DBLP:journals/corr/abs-1802-05766}. The predicted relationship between objects $i$ and $j$ is given by: \begin{equation} r_{i,j} = argmax(p_{i,j}(r)) \end{equation} Where $r$ lies in the set of relationship classes including background BG. \vspace{-1mm} \section{Experiments} \vspace{-1mm} We performed experiments using three different datasets, i.e., Visual Genome (VG) \cite{KrishnaZGJHKCKL16}, Visual Relationship Detection (VRD) \cite{lu2016visual}, and OpenImages (OI) \cite{abs-1811-00982}. \vspace{-1mm} \subsection{Visual Genome} \vspace{-1mm} Visual Genome dataset \cite{KrishnaZGJHKCKL16} is the most frequently used dataset for the SGG task. We use the same data statistics and evaluation metrics as widely used by the state of the art in this field, i.e., 150 object categories and 50 relationship categories are used. 70\% of the dataset is used for training and 30\% for testing. An additional 5000 images are taken from the training set and are used for validation. As used by the state of the art, we also employed Faster R-CNN \cite{ren2015faster} with VGG-16 or ResNext-101 as a backbone to get the characteristics of object proposals. To keep the fairness in the comparison with state-of-the-art, we chose same experimental factors as chosen by \cite{lin2020gpsnet}. \textbf{Performance Diagnosis:} The scene graph generation model is evaluated in three different sub-tasks: (1) Predicate classification, (2) Scene graph classification, and (3) Scene graph generation. These are the three protocols for which the model's performance is evaluated separately. Predicate Detection is used to specify the relation of given objects. This protocol evaluates the set of possible relations between a pair of given objects. The prediction of relationships without the effect of object detection is examined. In Phrase Detection, the input is an image and the outputs are triplets of subject-predicate-object. Additionally, one bounding box must have an overlap of at least 0.5 with the corresponding ground truth. For Relation Detection, the same input and output as in Phrase Detection is used. In this case, not only one but two bounding boxes of the pair of objects must have at least 0.5 overlap with the ground truth. \textbf{Metrics.} The evaluated metrics for the diagnosis of the model performance is Recall at K (R@K), no graph constraint Recall at K (nGR@K), zero-shot Recall at K (zsR@K), and mean Recall (mR@K), where $K$=20, 50, and 100, respectively. \textbf{Object Detector:} A pretrained Faster R-CNN object detector with a VGG-16 net \cite{han2015learning} or ResNeXt-101-FPN \cite{xie2017aggregated} as a backbone is used which is taken from \cite{lin2020gpsnet}. This detector was trained on the VG dataset, with batch size 8 and initial learning rate $8*10^{-3}$ which is decayed at the $30k^{th}$ and $40k^{th}$ iteration by the factor of 10. After training this detector on 4 2080Ti GPU, 28.14 mAP (with 0.5 IoU) was achieved. \textbf{Scene Graph Generation:} The scene graph generation is trained with an SGD optimizer \cite{bottou2012stochastic}. The learning rate is set at $10^{-3}$ for all three protocols. This learning rate was decayed by a factor of 10 twice after hitting a validation performance plateau. Per-Class non-maximal suppression (NMS) was applied with 0.5 IoU. 160 RoIs for each image were sampled. In contrast to previous works, we also considered non-overlapping regions for relationship prediction. To generalize the scene graph generation task, we used similar settings as used in literature \cite{lin2020gpsnet}. For model training, an RTX Titan was used. The batch size was set to 12 and the learning rate started at $10^{-3}$ and was reduced two times by a factor of 10 after hitting a validation performance plateau. The number of solver iterations was set to 18000. \vspace{-3mm} \subsection{OpenImages} \vspace{-1mm} The training and validation sets of the OpenImages dataset contain 53,953 and 3,234 images. For comparison, we use the same Faster R-CNN detector with a pre-trained ResNeXt- 101-FPN backbone as used by \cite{lin2020gpsnet,zhang2019graphical}. Also, the same data processing and evaluation metrics are used as in these previous works \cite{lin2020gpsnet,zhang2019graphical}. The evaluation metrics are Recall$@$50, weighted mean average precision (AP) of relationships wmAP\textsubscript{rel}, and weighted mean AP of phrase wmAP\textsubscript{phr}. The final score is given by $0.2*R@50 + 0.4*wmAP_{rel} + 0.4*wmAP_{phr}$, which was adopted from the OpenImages challenge formula \cite{DBLP:journals/corr/abs-1903-02728}, where the mAP was replaced by its weighted counterpart. The replacement of the mAP with the wmAP was done \cite{DBLP:journals/corr/abs-1903-02728} due to the extreme predicate class imbalance. The wmAP is achieved by scaling each predicate category by their relative ratios in the val set from the mAP. Important to note is that the wmAP\textsubscript{rel} evaluates the AP of the predicted triplet where both the subject and object boxes have an IoU of at least 0.5 with ground truth. The wmAP\textsubscript{phr} is quite similar but is utilized for the union box of the subject and the object. \vspace{-2mm} \subsection{Visual Relation Detection} \vspace{-1mm} The Visual Relation Detection (VRD) dataset was introduced by \cite{lu2016visual}. We adopt the same detectors as \cite{DBLP:journals/corr/abs-1903-02728}. Specifically, we use a pre-trained Faster R-CNN detector with VGG-16 backbone trained on the COCO dataset \cite{lin2014microsoft}. The evaluation process is given by \cite{lu2016visual} and the metrics used are R$@$50 and R$@$100. \subsection{Implementation Details} We follow the same implementation parameters as used by \cite{lin2020gpsnet}. To ensure a fair comparison with state of the art, we used VGG-16 and ResNext-101 as backbone. We use the 10$^{-3}$ as the learning rate and 6 as the batch-size which is the same as used by \cite{lin2020gpsnet}. We use SGD with momentum as the optimizer for the training process. We use the relationship between overlapped bounding boxes and subject-object pairs for the SGDet process. NMS with an IoU of 0.3 is used and the topmost 64 object proposals are chosen. The ratio of 3:1 is maintained during training between the subject-object pairs with and without any relationship. \subsection{Comparisons with State-of-the-Art Methods} \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llccccccccccccc} \hline & & & SGdet & & & & SGCls & & & & PredCls & & \\ \hline \textbf{Model} & \vline & $R@20$ & $R@50$ & $R@100$ & \vline & $R@20$ & $R@50$ & $R@100$ & \vline & $R@20$ & $R@50$ & $R@100$& \vline & Mean \\ \hline MOTIFS $\star$ \cite{zellers2018neural} & \vline & 21.4 & 27.2 & 30.3 & \vline & 32.9 & 35.8 & 36.5 & \vline & 58.5 & 65.2 & 67.1 & \vline & 43.7\\ FREQ $\star$ \cite{zellers2018neural} & \vline & 20.1 & 26.2 & 30.1 & \vline & 29.3 & 32.3 & 32.9 & \vline & 53.6 & 60.6 & 62.2 & \vline & 40.7\\ VCTREE-SL $\star$ \cite{DBLP:journals/corr/abs-1812-01880} & \vline & 21.7 & 27.7 & 31.1 & \vline & 35.0 & 37.9 & 38.6 & \vline & 59.8 & 66.2 & 67.9 & \vline & 44.9\\ VCTREE-HL $\star$ \cite{DBLP:journals/corr/abs-1812-01880} & \vline & 22.0 & 27.9 & 31.3 & \vline & 35.2 & 38.1 & 38.8 & \vline & 60.1 & 66.4 & 68.1 & \vline & 45.1\\ GB Net $\star$ \cite{Zareian_2020_ECCV} & \vline & - & 26.3 & 29.9 & \vline & - & 37.3 & 38 & \vline & - & 66.6 & 68.2 & \vline & 44.4\\ NODIS $\star$ \cite{yuren2020nodis} & \vline & 21.5 & 27.4 & 30.7 & \vline & 36 & 39.8 & 40.7 & \vline & 58.9 & 66 & 67.9 & \vline & 45.4\\ GPS-Net $\star$ \cite{lin2020gpsnet} & \vline & 22.6 & 28.4 & 31.7 & \vline & 36.1 & 39.2 & 40.1 & \vline & 60.7 & 66.9 & 68.8 & \vline & 45.9\\ CMAT $\star$ \cite{chen2019counterfactual} & \vline & 22.1 & 27.9 & 31.2 & \vline & 35.9 & 39 & 39.8 & \vline & 60.2 & 66.4 & 68.1 & \vline & 45.4\\ KERN $\star$ \cite{chen2019knowledge} & \vline & - & 27.1 & 29.8 & \vline & - & 36.7 & 37.4 & \vline & - & 65.8 & 67.6 & \vline & 44.1 \\ Graph R-CNN $\star$ \cite{yang2018graph} & \vline & - & 11.4 & 13.7 & \vline & - & 29.6 & 31.6 & \vline & - & 54.2 & 59.1 & \vline & 33.3\\ IMP $\star$ \cite{DBLP:journals/corr/XuZCF17} & \vline & - & 3.44 & 4 .24 & \vline & - & 21.72 & 24.38 & \vline & - & 44.75 & 53.08 & \vline & 25.3\\ \hline \textbf{BGT-Net (no BiGRU)} $\star$ & \vline & \textbf{23.61} & \textbf{ 30.4} & \textbf{ 34.81} & \vline & \textbf{ 33.81} & \textbf{ 37.22} & \textbf{ 38.12} & \vline & \textbf{ 57.98} & \textbf{ 64.75} & \textbf{ 66.63} & \vline & \textbf{46.9}\\ \hline \textbf{BGT-Net} $\star$ & \vline & \textbf{23.1} & \textbf{28.6} & \textbf{32.2} & \vline & \textbf{38.0} & \textbf{40.9} & \textbf{43.2} & \vline & \textbf{60.9} & \textbf{67.3} & \textbf{68.9} & \vline & \textbf{46.9}\\ \textbf{BGT-Net} $\diamond$ & \vline & \textbf{25.5} & \textbf{32.8} & \textbf{37.3} & \vline & \textbf{41.7} & \textbf{45.9} & \textbf{47.1} & \vline & \textbf{60.9} & \textbf{67.1} & \textbf{68.9} & \vline & \textbf{49.9}\\ \hline \end{tabular}} \vspace{0mm} \normalsize {\topcaption[Recall@K Model comparison with state-of-the-arts on the VG dataset.]{Recall@K Model comparison with state-of-the-arts on the VG dataset. We compare R@20, R@50, and R@100. For some literature work, the R@20 is not given. We used '$-$' which denotes that the result is unavailable. So, the mean is calculated using values of R@50 and R@100 to have fair comparison with state of the art. Models using the same VGG backbone are denoted with '$\star$' and the BGT-Net with ResNext-101 background is marked with '$\diamond$'.}\label{tab:comp_modelsVG}} \end{minipage} \hfill \vspace{-8mm} \end{table*} \begin{table}[h] \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llccccccc} \hline & & SGdet & & SGCls & & PredCls & & \\ \hline \textbf{Model} & \vline & $mR@100$ & \vline & $mR@100$ & \vline & $mR@100$ & \vline & Mean \\ \hline GB Net $\star$ \cite{Zareian_2020_ECCV} & \vline & 8.5 & \vline & 13.4 & \vline & \textbf{24} & \vline & 15.3 \\ IMP $\star$ \cite{DBLP:journals/corr/XuZCF17} & \vline & 4.8 & \vline & 6.0 & \vline & 10.5 & \vline & 7.1 \\ GPS-Net $\star$ \cite{lin2020gpsnet} & \vline & \textbf{9.8} & \vline & 12.6 & \vline & 22.8 & \vline & 15.1 \\ VCTREE-HL $\star$ \cite{DBLP:journals/corr/abs-1812-01880} & \vline & 8.0 & \vline & 10.8 & \vline & 19.4 & \vline & 12.8 \\ MOTIFS $\star$ \cite{zellers2018neural} & \vline & 6.6 & \vline & 8.2 & \vline & 15.3 & \vline & 10.0\\ KERN $\star$ \cite{chen2019knowledge} & \vline & 7.3 & \vline & 10 & \vline & 19.2 & \vline & 12.2\\ \hline \textbf{BGT-Net} $\star$ & \vline & 9.6 & \vline & \textbf{13.7} & \vline & 23.2 & \vline & \textbf{15.5}\\ \hline \end{tabular}} \normalsize \vspace{-2mm} \caption[Comparison on mR@100]{Comparison on mR@100 between various methods across all 50 relationship categories.} \label{tab:meanRecall} \vspace{-7mm} \end{table} \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llccccccccccc} \hline & & & SGdet & & & & SGCls & & & & PredCls & \\ \hline \textbf{Model} & \vline & $nGR@20$ & $nGR@50$ & $nGR@100$ & \vline & $nGR@20$ & $nGR@50$ & $nGR@100$ & \vline & $nGR@20$ & $nGR@50$ & $nGR@100$ \\ \hline GB Net $\star$ \cite{Zareian_2020_ECCV} & \vline & - & 29.3 & 35 & \vline & - & 46.9 & 50.3 & \vline & - & \textbf{83.5} & \textbf{90.3}\\ CMAT $\star$ \cite{chen2019counterfactual} &\vline & 23.7 & 31.6 & 36.8 & \vline & \textbf{41} & \textbf{48.6} & \textbf{52} & \vline & \textbf{68.9} & 83.2 & 90.1\\ KERN $\star$ \cite{chen2019knowledge} &\vline & - & 30.9 & 35.8 & \vline & - & 45.9 & 49 &\vline & - & 65.8 & 67.6\\ \hline \textbf{BGT-Net (no BiGRU)} $\diamond$ & \vline & 24.23 & 32.88 & 39.06 & \vline & 38.55 & 46.28 & 50.04 & \vline & 65.92 & 80.51 & 87.82 \\ \textbf{BGT-Net} $\diamond$ & \vline & \textbf{27.24} & \textbf{36.91} & \textbf{43.72} & \vline & \textbf{47.83} & \textbf{57.67} & \textbf{62.29} & \vline & \textbf{69.1} & \textbf{83.71} & \textbf{90.55} \\ \hline \hline \textbf{Model} & \vline & $mR@20$ & $mR@50$ & $mR@100$ & \vline & $mR@20$ & $mR@50$ & $mR@100$ & \vline & $mR@20$ & $mR@50$ & $mR@100$ \\ \hline GB Net $\star$ \cite{Zareian_2020_ECCV} & \vline & - & 7.1 & 8.5 & \vline & - & 12.7 & 13.4 & \vline & - & \textbf{22.1} & \textbf{24} \\ GPS-Net$\star$\cite{lin2020gpsnet} & \vline & - & - & \textbf{9.8} & \vline & - & - & 12.6 & \vline & - & - & 22.8 \\ KERN $\star$\cite{chen2019knowledge} & \vline & - & 6.4 & 7.3 & \vline & - & 9.4 & 10 & \vline & - & 17.7 & 19.2 \\ \hline \textbf{BGT-Net (no BiGRU)} $\diamond$ & \vline & 4.62 & 6.55 & 7.85 & \vline & 7.31 & 9.14 & 9.71 & \vline & 12.14 & 15.59 & 17.05 \\ \textbf{BGT-Net} $\diamond$ & \vline & \textbf{5.69} & \textbf{7.81} & 9.25 & \vline & \textbf{10.41} & \textbf{12.77} & \textbf{13.61} & \vline & \textbf{16.8} & \textbf{20.56} & \textbf{22.98} \\ \hline \hline \textbf{Model} & \vline & $zsR@20$ & $zsR@50$ & $zsR@100$ & \vline & $zsR@20$ & $zsR@50$ & $zsR@100$ & \vline & $zsR@20$ & $zsR@50$ & $zsR@100$ \\ \hline Motifs $\star$\cite{tang2020sggcode} & \vline & 0 & 0.05 & 0.11 & \vline & 0.32 & 0.91 & 1.39 & \vline & 1.35 & 3.63 & 5.36 \\ IMP $\star$\cite{DBLP:journals/corr/XuZCF17} & \vline & 0.18 & 0.38 & 0.77 & \vline & 2.01 & 3.03 & 3.92 & \vline & 12.17 & 17.66 & 20.25 \\ \hline \textbf{BGT-Net} $\diamond$& \vline & \textbf{1.22} & \textbf{2.38} & \textbf{3.42} & \vline & \textbf{4.8} & \textbf{7.37} & \textbf{8.78} & \vline & \textbf{12.23} & \textbf{18.31} & \textbf{21.51} \\ \hline \end{tabular}} \vspace{1mm} \normalsize {\topcaption[No Graph Constraint Recall Results of transformer Model]{nGR@K, mR@K and zsR@K comparison with state-of-the-art on the VG dataset. The version of the BGT-Net, i.e., the BGT-Net (no BiGRU) is also compared.}\label{tab:comp_models_ngc1}} \end{minipage} \hfill \vspace{-9mm} \end{table*} \begin{table}[h] \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llcccccccccccccc} \hline & \vline & Predicate Detection &\vline & \multicolumn{2}{c}{Relation Detection} & &\multicolumn{2}{c}{Phrase Detection} & & \\ \hline \textbf{Model} & \vline & $R@50$ & \vline & $R@50$ & $R@100$ & \vline & $R@50$ & $R@100$ & \vline & Mean \\ \hline VTransE \cite{DBLP:journals/corr/ZhangKCC17} & \vline & 44.8 & \vline & 19.4 & 22.4 & \vline & 14.1 & 15.2 & \vline & 23.2\\ ViP-CNN \cite{article} & \vline & - & \vline & 17.3 & 20.0 & \vline & 22.8 & 27.9 & \vline & 22\\ VRL \cite{DBLP:journals/corr/LiangLX17} & \vline & - & \vline & 18.2 & 20.8 & \vline & 21.4 & 22.6 & \vline & 20.8\\ KL distilation \cite{DBLP:journals/corr/YuLMD17} & \vline & 55.2 & \vline & 19.2 & 21.3 & \vline & 23.1 & 24.0 & \vline & 28.6\\ MF-URLN \cite{DBLP:journals/corr/abs-1905-01595} & \vline & 58.2 & \vline & 23.9 & 26.8 & \vline & 31.5 & 36.1 & \vline & 35.3\\ Zoom-Net $\diamond$ \cite{DBLP:journals/corr/abs-1807-04979} & \vline & 50.7 & \vline & 18.9 & 21.4 & \vline & 24.8 & 28.1 & \vline & 28.8\\ CAI + SCA-M $\diamond$ \cite{DBLP:journals/corr/abs-1807-04979} & \vline & 56.0 & \vline & 19.5 & 22.4 & \vline & 25.2 & 28.9 & \vline & 30.4\\ RelDN $\star$ \cite{DBLP:journals/corr/abs-1903-02728} & \vline & - & \vline & 25.3 & 28.6 & \vline & 31.3 & 36.4 & \vline & 30.4\\ GPS-Net $\star$ \cite{lin2020gpsnet} & \vline & 63.4 & \vline & 27.8 & 31.7 & \vline & 33.8 & 39.2 & \vline & 39.2\\ \hline BGT-Net $\star$ & \vline & \textbf{64.1} & \vline & \textbf{28.5} & \textbf{31.9} & \vline & \textbf{34.4} & \textbf{39.4} & \vline & \textbf{39.6}\\ \hline \end{tabular}} \normalsize \vspace{-1mm} \caption[Comparison on VRD]{Comparison on the VRD dataset \cite{lu2016visual}. '$\star$' and '$\diamond$' denote the models using the same object detector. The object detector with a VGG-16 backbone trained on COCO is used as in RelDN and GPS-Net to have fair comparison.} \vspace{-7mm} \label{tab:comp_vrd} \end{table} \begin{table*}[h] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llcccccccccccccc} \hline & \vline & & & & & \vline & \multicolumn{9}{c}{AP\textsubscript{rel} per class} \\ \hline \textbf{Model} & \vline & $R@50$ & $wmAP_{rel}$ & $wmAP_{phr}$ & $score_{wtd}$ & \vline & at & on & holds & plays & interacts with & wears & hits & inside of & under\\ \hline RelDN, $L_{0}$ \cite{DBLP:journals/corr/abs-1903-02728}& \vline & 74.67 & 34.63 & 37.89 & 43.94 & \vline & 32.40 & 36.51 & 41.84 & 36.04 & 40.43 & 5.70 & 55.40 & 44.17 & 25.00\\ RelDN \cite{DBLP:journals/corr/abs-1903-02728}& \vline & 74.94 & 35.54 & 38.52 & 44.61 & \vline & 32.90 & 37.00 & 43.09 & 41.04 & 44.16 & 7.83 & 51.04 & 44.72 & 50.00\\ GPS-Net \cite{lin2020gpsnet}& \vline & 77.29 & 38.78 & 40.15 & 47.03 & \vline & 35.10 & 38.90 & \textbf{51.47} & 45.66 & \textbf{44.58} & \textbf{32.35} & 71.71 & 47.21 & 57.28\\ \hline BGT-Net & \vline & \textbf{77.98} & \textbf{39.56} & \textbf{40.75} & \textbf{47.67} & \vline & \textbf{36.23} & \textbf{39.05} & 50.96 & \textbf{46.78} & 44.56 & 31.45 & \textbf{72.17} & \textbf{48.03} & \textbf{57.64}\\ \hline \end{tabular}} \normalsize \end{minipage} \hfill \vspace{-2mm} \caption[Comparison on OpenImages]{Comparison on OpenImages dataset \cite{DBLP:journals/corr/abs-1811-00982}. The BGT-Net uses a ResNext-101 backbone. Additionally, the same data processing and evaluation metrics as \cite{lin2020gpsnet, DBLP:journals/corr/abs-1903-02728} are followed to a ensure fair comparison.} \label{tab:comp_openimages} \vspace{-4mm} \end{table*} \textbf{Visual Genome:} BGT-Net outperforms all the compared previous literature work as shown in Table \ref{tab:comp_modelsVG} on R@K for all values of K . BGT-Net performs better than a recent model named GPS-net \cite{lin2020gpsnet} by 6$\%$ and by 12$\%$ on average at R@50 and R@100 over the three protocols when VGG-19 or ResNext-101 is used as the base for the Faster-RCNN, respectively. It also outperforms when an individual evaluation protocol is compared. The improvement is by 16.6$\%$ for SGDet, 17.3$\%$ for SGCls, and for 0.2$\%$ for PredCls. When compared to the classic MOTIFS \cite{zellers2018neural}, it showed an improvement of 7.3$\%$ and 14$\%$ on average at R@50 and R@100 over the three protocols when VGG-19 or ResNext-101 is used as a backbone for the Faster-RCNN, respectively. BGT-Net outperforms FREQ \cite{zellers2018neural}, VCTREE-SL \cite{DBLP:journals/corr/abs-1812-01880}, VCTREE-HL \cite{DBLP:journals/corr/abs-1812-01880}, GB-NET \cite{Zareian_2020_ECCV} , NODIS \cite{yuren2020nodis}, CMAT \cite{chen2019counterfactual}, KERN \cite{chen2019knowledge}, Graph R-CNN \cite{yang2018graph}, IMP \cite{DBLP:journals/corr/XuZCF17} by 14.9$\%$, 4.3$\%$, 3.9$\%$, 5.6$\%$, 3.2$\%$, 3.2$\%$, 6.3$\%$, 40.9$\%$, 85.4$\%$, respectively, on average at R@50 and R@100 over the three protocols when VGG-19 is used as a backbone for the Faster-RCNN and by 22.2$\%$, 11$\%$, 10.5$\%$, 12.3$\%$, 9.8$\%$, 9.8$\%$, 13.1$\%$, 49.9$\%$, 97.3$\%$, respectively, on average at R@50 and R@100 over the three protocols when ResNext-101 is used as a backbone for the Faster-RCNN. We evaluate Mean Recall of BGT-Net to understand its performance on the class imbalance problem. So, we study its performance by conducting experiments to calculate its Mean Recall \cite{chen2019knowledge,DBLP:journals/corr/abs-1812-01880, lin2020gpsnet}. We see in Figure \ref{meanrecall12} and Table \ref{tab:meanRecall} that BGT-Net performs well considering the Mean Recall evaluation metric. The mean of the Mean Recall over all the three evaluation metrics (SGDet, SGCls, PredCls) is 15.5 for BGT-Net and hence outperforms GB-Net and GPS-Net which are the best state-of-the-art on class imbalance handling having good performance on both mean R@K and R@K results. This gives a positive indication that BGT-Net can tackle the problem of class imbalance while simultaneously giving high R@K as compared to the other existing solutions to best of our knowledge. \textbf{Why BiGRU?} We investigated BGT-Net without BiGRU but BGT-Net (no BiGRU) has lower SGCls and PredCls results (see Table \ref{tab:comp_modelsVG}). The deciding factor for using BiGRU in BGT-Net is mR@K and nGR@K. Both these metrics significantly improve for all three: SGDet, SGCls, PredCls when BGT-Net is with BiGRU as shown in Table \ref{tab:comp_models_ngc1}.\\ Also shown in Table \ref{tab:comp_models_ngc1}, BGT-Net has high improvement on zsR@K as compared to \cite{DBLP:journals/corr/XuZCF17} and \cite{zellers2018neural} which shows that it is able to better detect those subject-predicate-object combinations which are not present in the training set. \begin{figure}[ht] \setlength\abovecaptionskip{0.4\baselineskip} \setlength\belowcaptionskip{-18pt} \begin{center} \includegraphics[scale=0.3]{./figures/bar_graph_MOTIFS.png}\\ \includegraphics[scale=0.3]{./figures/bar_graph_VCTREE.png} \par\nointerlineskip\vspace{-1mm} \caption{The increase in R@100 in PredCls of BGT-Net compared with the MOTIFS \cite{zellers2018neural} and VCTREE \cite{DBLP:journals/corr/abs-1812-01880}. The Top-35 relationship categories are selected according to their alphabetic occurrence.} \vspace{-2.5mm} \label{meanrecall12} \end{center} \end{figure} \vspace{-1mm} \textbf{OpenImages:} The results in Table \ref{tab:comp_openimages} show that BGT-Net performs very well on the OpenImages dataset. The overall score is 0.64 points higher than the GPS-Net model performance. This increase in performance is achieved by an overall increase in performance in all three evaluated metrics R$@$K, wmAP\textsubscript{rel}, and wmAP\textsubscript{phr}. An evaluation of the per-class AP is also shown. In this evaluation, some classes were chosen as in GPS-Net \cite{lin2020gpsnet} and RelDN \cite{DBLP:journals/corr/abs-1903-02728} to show class-specific performance. The performances of GPS-Net and the BGT-Net are quite close. For ''holds'', ''interacts with'' and ''wears'', the GPS-Net shows a higher AP while for the others the BGT-Net shows the highest AP. The overall performance of the BGT-Net outperforms the state-of-the-art performance of the GPS-Net model. \textbf{Visual Relationship Detection:} The evaluation results on VRD Dataset are illustrated in Table \ref{tab:comp_vrd}. The BGT-Net uses the same Detector as RelDN and GPS-Net. The BGT-Net outperforms the state-of-the-art models in all three evaluation metrics. So, BGT-Net shows the best to the date performance on the VRD dataset as well to the best of our knowledge, and which is better than GPS-Net and RelDN (previous best performing networks). \vspace{-2mm} \subsection{Ablation Studies} \vspace{-1mm} To evaluate and analyze our proposed BGT-Net, we conducted a number of ablations as shown in Table \ref{tab:ablation1}, Table \ref{tab:ablation2}, and Table \ref{tab:ablation3}. \textbf{Network Performance with a different combination of Modules.} In this study, we evaluate the effectiveness of the network in the presence of the three modules, i.e., Transformer, BiGRU, and FS, individually and collectively. The performance of the network increases with the presence of all three modules. Firstly, we evaluated for an individual module and then permutated the modules with each other to make a combination to evaluate the performance of different resulting configurations. As illustrated in Table \ref{tab:ablation1}, for all the three evaluation protocols, i.e., SGDet, SGCls, and PredCls, our proposed network with all the three modules outperforms the other network configurations with individual modules. When modules are used together, the network performance improves which shows that each individual module plays a significant role in predicting objects and their relationships. The FS and BA were adapted from [20]. In \cite{lin2020gpsnet}, they performed ablation study with and without FS and BA. It was shown that these modules improve the PredCls for all three R@20, R@50, and R@100. We included in our ablation the effect of using FS which showed that zsR@20, zs@50, and zsR@100 improved drastically for all three: SGDet, SGCls, PredCl, when using FS as shown in Table \ref{tab:ablation1}. \textbf{Performance with different number of Transformer Heads.} We performed this ablation to validate the optimized number of transformer heads in the network. As illustrated in Table \ref{tab:ablation2}, we can see that when 1, 2, or 6 number of transformer heads are used, the network with 6 transformer heads performs better in all the experiments than others for all the three evaluation protocols. This ablation shows that the number of transformer heads also effect the performance of the model and hence this factor is critical while designing the network for the SGG. This study motivated us to use six transformer heads in the novel BGT-Net. \textbf{Performance with different number of Bidirectional GRU Layers.} We compare networks with different number of BiGRU layers. To keep the comparison fair, we use all other same parameters in the experiments except the number of BiGRU layers. As shown in Table \ref{tab:ablation2}, it is evident that increasing the number of BiGRU layers does not significantly improve the performance, but it does increase the computational power and training time. Hence, in the BGT-Net, we only use one BiGRU layer. \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llllllccccccccccccccc} \hline & \vline &\textbf{Transformer} & \textbf{GRU} & \textbf{FS} & \vline & \textbf{R @ 20} & \textbf{R @ 50} & \textbf{R @ 100} & \vline & \textbf{nG R @ 20} & \textbf{nG R @ 50} & \textbf{nG R @ 100} & \vline & \textbf{zs R @ 20} & \textbf{zs R @ 50} & \textbf{zs R @ 100} & \vline & \textbf{mR @ 20} & \textbf{mR @ 50} & \textbf{m R @ 100}\\ \hline & \vline & x & - & - & \vline & 23.61 & 30.4 & 34.81 & \vline & 24.23 & 32.88 & 39.06 & \vline & 0 & 0 & 0 & \vline & 4.62 & 6.55 & 7.85\\ & \vline &- & x & - & \vline & 24.1 & 31.2 & 35.5 & \vline & 25.37 & 34.59 & 41.14 & \vline & 0 & 0 & 0.03 & \vline& 4.07 & 5.49 & 6.51 \\ SGDet& \vline& - & - & x & \vline & 22.3 & 28.17 & 32.56 & \vline & 25.04 & 34.58 & 41.23 & \vline & 0.95 & 1.27 & 2.21 & \vline & 4.47 & 5.98 & 7.65\\ & \vline &x & x & x & \vline & 24.68 & 31.87 & 36.18 & \vline & 26.23 & 35.87 & 42.46 & \vline & 1.22 & 2.38 & 3.42 & \vline& 5.69 & 7.81 & 9.25\\ \hline \hline & \vline & x & - & - & \vline & 33.81 & 37.22 & 38.12 & \vline & 38.55 & 46.28 & 50.04 & \vline & 0.15 & 0.45 & 0.7 & \vline & 7.31 & 9.14 & 9.71 \\ & \vline& - & x & - & \vline & 40.03 & 44 & 45.02 & \vline & 45.61 & 54.82 & 59.26 & \vline & 0.19 & 0.69 & 0.99 & \vline & 7.92 & 9.85 & 10.55 \\ SGCls & \vline& - & - & x & \vline & 35.63 & 38.92 & 39.77 & \vline & 39.41 & 47.92 & 55.56 & \vline & 3.25 & 4.99 & 5.78 & \vline & 8.2 & 10.65 & 11.34\\ & \vline& x & x & x & \vline & 41.72 & 45.69 & 46.74 & \vline & 47.96 & 57.42 & 61.92 & \vline & 4.12 & 6.72 & 8.06 & \vline & 10.41 & 12.77 & 13.61\\ \hline \hline & \vline& x & - & - & \vline & 57.98 & 64.75 & 66.63 & \vline & 65.92 & 80.51 & 87.82 & \vline & 0.64 & 2.06 & 3.69 & \vline & 12.14 & 15.59 & 17.05 \\ & \vline& - & x & - & \vline & 58.52 & 65.19 & 67.08 & \vline & 65.76 & 80.38 & 87.83 & \vline & 0.68 & 2.52 & 4.46 & \vline & 12.33 & 15.79 & 17.16 \\ PredCls & \vline& - & - & x & \vline & 56.73 & 63.48 & 65.53 & \vline & 64.87 & 79.56 & 87.2 & \vline & 11.9 & 17.78 & 20.97 & \vline & 12.05 & 15.22 & 16.46\\ & \vline & x & x & x & \vline & 58.71 & 65.25 & 67.1 & \vline & 67.27 & 82.05 & 89.29 & \vline & 12.06 & 18.22 & 21.49 & \vline & 14.36 & 17.88 & 19.44 \\ \hline \end{tabular}} \vspace{1mm} \normalsize {\topcaption[Recall@K comparison of BGT-Net with Model Performance of different Modules.]{Ablation study performed on evaluation of three models. All the experimental factors are kept same except the ones which are being evaluated to have fair comparison. The evaluation is conducted using Recall@K, nGR@K, zsR@K, and mR@K. } \label{tab:ablation1}} \end{minipage} \hfill \vspace{-5mm} \end{table*} \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llllccccccccccccccc} \hline & \vline &\textbf{Transformer Heads} & \vline & \textbf{R @ 20} & \textbf{R @ 50} & \textbf{R @ 100} & \vline & \textbf{nG R @ 20} & \textbf{nG R @ 50} & \textbf{nG R @ 100} & \vline & \textbf{zs R @ 20} & \textbf{zs Recall @ 50} & \textbf{zs R @ 100} & \vline & \textbf{mR @ 20} & \textbf{mR @ 50} & \textbf{m R @ 100}\\ \hline & \vline & 1 & \vline & 23.78 & 31.15 & 35.4 & \vline & 25.76 & 34.8 & 41.78 & \vline & 0.99 & 2.11 & 2.67 & \vline & 4.75 & 7.32 & 7.96\\ SGDet & \vline & 2 & \vline & 24.54 & 31.77 & 36.11 & \vline & 26.05 & 35.64 & 42.39 & \vline & 1.07 & 2.18 & 3.37 & \vline & 5.57 & 7.52 & 8.8\\ & \vline & 6 & \vline & \textbf{24.68} & \textbf{31.87 }& \textbf{36.18} & \vline & \textbf{26.23} & \textbf{35.87 }& \textbf{42.46} & \vline & \textbf{1.22} & \textbf{2.38} & \textbf{3.42 }& \vline &\textbf{ 5.69} & \textbf{7.81} & \textbf{9.25}\\ \hline \hline & \vline & 1 & \vline & 38.62 & 42.54 & 43.66 & \vline & 45.01 & 52.1 & 58.78 & \vline & 2.67 & 4.31 & 4.89 & \vline & 8.21 & 9.98 & 10.32 \\ SGCls & \vline & 2 & \vline & 39.37 & 43.42 & 44.51& \vline & 45.25 & 54.51 & 59.17 & \vline& 3.32 & 5.37 & 6.48 & \vline & 9.01 & 11.14 & 11.89 \\ & \vline& 6 & \vline &\textbf{ 41.72 } & \textbf{45.69} & \textbf{46.74} & \vline & \textbf{47.96 }& \textbf{57.42} & \textbf{61.92} & \vline & \textbf{4.12} & \textbf{6.72} & \textbf{8.06} & \vline & \textbf{10.41} & \textbf{12.77} & \textbf{13.61 }\\ \hline \hline & \vline & 1 & \vline &58.03 & 64.8 & 66.89 & \vline & 66.23 & 81.06 & 87.89 & \vline & 11.06 & 17.39 & 19.45 & \vline & 12.55 & 16.21 & 17.51 \\ PredCls & \vline & 2 & \vline & 58.45 & 64.98 & 67.03 & \vline & 66.89 & 81.66 & 88.34 & \vline & 11.9 & 18.11 & 21.34 & \vline & 12.91 & 16.75 & 18.92 \\ & \vline& 6 & \vline & \textbf{58.71} & \textbf{65.25} & \textbf{67.1 }& \vline & \textbf{67.27} & \textbf{82.05} & \textbf{89.29} & \vline & \textbf{12.06} & \textbf{18.22} &\textbf{ 21.49 }& \vline & \textbf{14.36} & \textbf{17.88} & \textbf{19.44} \\ \hline \end{tabular}} \vspace{1mm} \normalsize {\topcaption[Model Performance for different Transformer Heads.]{Various R@K performance for the different numbers of Transformer Heads in BGT-Net using VG dataset. } \label{tab:ablation2}} \end{minipage} \hfill \vspace{-5mm} \end{table*} \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llllccccccccccccccc} \hline & \vline &\textbf{Bi-GRU} & \vline & \textbf{R @ 20} & \textbf{R @ 50} & \textbf{R @ 100} & \vline & \textbf{nG R @ 20} & \textbf{nG R @ 50} & \textbf{nG R @ 100} & \vline & \textbf{zs R @ 20} & \textbf{zs Recall @ 50} & \textbf{zs R @ 100} & \vline & \textbf{mR @ 20} & \textbf{mR @ 50} & \textbf{m R @ 100}\\ \hline & \vline & 1 & \vline& \textbf{25.54} & \textbf{32.87} & \textbf{37.3 } & \vline & \textbf{27.24} & \textbf{36.91} & \textbf{43.72} & \vline & \textbf{4.8} & \textbf{7.37} & \textbf{8.78} & \vline & \textbf{10.41 }& \textbf{12.77} & \textbf{13.61}\\ SGDet & \vline & 2 & \vline & 24.54 & 31.77 & 36.11 & \vline & 26.05 & 35.64 & 42.39 & \vline & 1.07 & 2.18 & 3.37 & \vline & 9.91 & 12.28 & 13.12 \\ & \vline & 6 & \vline & 23.93 & 31.01 & 35.37 & \vline & 25.47 & 35.02 & 41.63 & \vline & 1.12 & 2.11 & 3.1 & \vline & 5.49 & 7.53 & 8.86 \\ \hline \hline & \vline & 1 & \vline & 41.69 & \textbf{45.96} & \textbf{47.06} & \vline & 47.83 & \textbf{57.67} & \textbf{62.29 }& \vline & 2.67 & 4.31 & 4.89 & \vline & 8.21 & 9.98 & 10.32 \\ SGCls & \vline & 2 & \vline & \textbf{41.72} & 45.69 & 46.74 & \vline & \textbf{47.96} & 57.42 & 61.92 & \vline&\textbf{ 4.12} & \textbf{6.72} & \textbf{8.06} & \vline & \textbf{9.01} & \textbf{11.14} & \textbf{11.89} \\ & \vline& 6 & \vline & 41.08 & 45.57 & 46.23& \vline & 46.98 & 57.12 & 61.3 & \vline & 4.02 & 6.56 & 7.79 & \vline & 8.54 & 11.81 & 13.01 \\ \hline \hline & \vline & 1 & \vline &\textbf{ 59.21} & \textbf{65.68} & \textbf{67.45} & \vline & \textbf{67.69} &\textbf{ 82.42} & \textbf{89.45} & \vline & \textbf{ 12.23} & \textbf{18.31} & \textbf{21.51} & \vline & \textbf{14.7} & \textbf{18.46} & \textbf{20.08 } \\ PredCls & \vline & 2 & \vline & 58.71 & 65.25 & 67.1 & \vline & 67.27 & 82.05 & 89.29 & \vline & 12.06 & 18.22 & 21.49 & \vline & 14.36 & 17.88 & 19.44 \\ & \vline& 6 & \vline & 58.22 & 65.45 & 66.74 & \vline & 66.91 & 81.87 & 88.69 & \vline & 11.83 & 18.07 & 21.1 & \vline & 14.22 & 17.59 & 19.21\\ \hline \end{tabular}} \vspace{1mm} \normalsize {\topcaption[Model Performance for different Numbers of Bidirectional GRU Layers.]{Various R@K performance comparison in relation to the number of BiGRU layers present in network when trained on VG dataset.} \label{tab:ablation3} } \end{minipage} \hfill \vspace{-5mm} \end{table*} \begin{figure*}[!htb] \vspace{-2mm} \centering \includegraphics[width=1\linewidth, height=1.9cm]{figures/ill_ex.png} \vspace{-0.15cm} \caption{Qualitative results showing scene graphs generated by the BGT-Net. For both examples, (a) shows the scene graph generated in the SGDet protocol, and (b) the one generated in SGCls. The green arrow denotes that the detection object or relationship corresponding to the ground-truth. Orange arrows denote the detections that are not available in ground-truth but do represent the image properly. Red marks errors that are used for undetected relationships or wrongly detected objects.} \vspace{-6mm} \label{fig:5} \end{figure*} \textbf{Qualitative Results.} In Figure~\ref{fig:5}, Left: shows the qualitative results. In SGCls, the bounding boxes are given and the model has to predict the object class and the relationships. In SGDet, no information is given. In SGDet up to 160 objects in an image can be detected but to keep the illustrations clean not every object detection is shown. It detected relationships present in the ground truth along with the additional feasible relationships. Figure~\ref{fig:5} Top: in SGCls the predicted scene graph fully corresponds to the ground truth scene graph for this image. There is no additional relationship predicted between other objects. Looking at the scene graph for SGDet, the difference between these two protocols can be seen very well. Also, the performance of the model is really good in this case. Additionally to the ground truth objects, the object ''motorcycle'' and ''person'' are detected. These two detections are correct and feasible. While the only ground truth relation (woman - wearing - shirt) is still being detected, three other relationships that are totally feasible are detected (woman - on - motorcycle), (person - on - motorcycle) and (wheel - on - motorcycle). The performance of the BGT-Net on this image is outstanding. No problems or specialties in the SGDet can be found. In Figure~\ref{fig:5} Right: In SGDet, the model even fails to give the correct relationship (car - on - track). But, it correctly detects the whole train, which was not specified in the ground truth and the correct relationship (train - on - track). It is special in this case and it might also be in a lot of other images that the model detects many objects that were not shown in the ground truth. It also shows a lot of relationships between these additionally shown objects. But, most likely with a higher amount of detected objects in an image, these triplets, that are not in the ground truth, leads the model to miss some of the relationships that would also be found in the ground truth. \vspace{-3.5mm} \section{Conclusion} \vspace{-3mm} We proposed a novel method BGT-Net to address the main challenges in SGG. BGT-Net solves the problems by 1) using the object-object communication by employing Bi-directional GRUs; 2) using transformer encoder with scaled-dot-product attention for predicting object classes after they have received feature information from other objects; 3) getting edge feature from second transformer encoder; 4) Utilising Frequency Softening and Bias Adaptation for dealing the with bias in the SGG. We validated the effectiveness of the proposed BGT-Net using extensive experiments and conducting elaborative ablation studies using three open-source datasets. \enlargethispage{\baselineskip} {\small \bibliographystyle{ieee_fullname} \section{BGT-Net without Bi-directional GRU} BGT-Net (no BiGRU) is the BGT-Net with no BiGRU in it. We experimented with it to see how Bi-directional GRU effects the performance of the network. The performance of the BGT-Net (no BiGRU) for PredCls is lower than the other models. Even when compared to the MOTIFS, a performance decrease can be seen. In SGCls, there is slight improvements compared to the other models. Most important factor is that the performance increase compared to MOTIFS (baseline) is seen. Therefore, the effectiveness of the BGT-Net (no BiGRU) is shown in Table 5 in paper. In SGDet protocol, the BGT-Net (no BiGRU) can show an impressive performance. It outperforms every other model. The performance difference is also quite significant. The Recall@K is improved by over 1 point and reaches up to an increase of more than 3 points over the next best model. The results in mean Recall@K are worse than others. The short-comings of this BGT-Net (no BiGRU) is removed and improved by changing the model structure to BGT-Net by adding a Bi-GRU. \section{Ablation Study} As mentioned in the paper, we performed ablation study on several factors. We provide additional results on those experiments. They are discussed below: \subsection{Different Combination of Modules} \label{subsubsec:model_building_blocks} Figure \ref{fig:abls1}, Figure \ref{fig:abls2}, Figure \ref{fig:abls3}, and Figure \ref{fig:abls4} illustrate the graphical representation of the performance achieved using different modules by evaluating them on different performance recall metric. \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/AblS1.png} \caption[Recall Results]{Graphical representation of Recall Results for SGDet (left), SGCls (middle), PredCls (right) comparing the effects of different modules of the BGT-Net made during ablation studies on the effectiveness of different modules.} \label{fig:abls1} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/AblS2.png} \caption[No Graph Constraint Recall Results]{Graphical representation of no graph constraint Recall Results for SGDet (left), SGCls (middle), PredCls (right) comparing the effects of different modules of the BGT-Net made during ablation studies on the effectiveness of different modules.} \label{fig:abls2} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/AblS3.png} \caption[Zero Shot Recall Results]{Graphical representation of zero shot Recall Results for SGDet (left), SGCls (middle), PredCls (right) comparing the effects of different modules of the BGT-Net made during ablation studies on the effectiveness of different modules.} \label{fig:abls3} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/AblS4.png} \caption[Mean Recall Results]{Graphical representation of mean Recall Results for SGDet (left), SGCls (middle), PredCls (right) comparing the effects of different modules of the BGT-Net made during ablation studies on the effectiveness of different modules.} \label{fig:abls4} \end{figure*} \subsection{Number of Transformer Heads} Figure \ref{fig:abls-th1}, Figure \ref{fig:abls-th2}, Figure \ref{fig:abls-th3}, and Figure \ref{fig:abls-th4} show the graphical representation of the performance achieved by using different number of transformer heads and by varying the performance recall metric. \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-th1.png} \caption[Recall Results]{Graphical representation of Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluating the performance changes evoked by changing the number of Transformer heads of Transformer Encoders for object and edge information.} \label{fig:abls-th1} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-th2.png} \caption[No Graph Constraint Recall Results]{Graphical representation of no graph constraint Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluating the performance changes evoked by changing the number of Transformer heads of Transformer Encoders for object and edge information.} \label{fig:abls-th2} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-th3.png} \caption[Zero Shot Recall Results]{Graphical representation of zero shot Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluating the performance change evoked by changing the number of Transformer heads of Transformer Encoders for object and edge information.} \label{fig:abls-th3} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-th4.png} \caption[Mean Recall Results]{Graphical representation of mean Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluating the performance change evoked by changing the number of Transformer heads of Transformer Encoders for object and edge information.} \label{fig:abls-th4} \end{figure*} \subsection{Number of Bidirectional GRU Layers} Figure \ref{fig:abls-gru1}, Figure \ref{fig:abls-gru2}, Figure \ref{fig:abls-gru3}, and Figure \ref{fig:abls-gru4} show the graphical representation of the performance achieved by using different number of BiGRU layers and by varying the performance recall metric. \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-gru1.png} \caption[Recall Results]{Graphical representation of Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluation of performance change influenced by using 1, 2 or 6 layers of bidirectional GRUs in the BGT-Net model.} \label{fig:abls-gru1} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-gru2.png} \caption[No Graph Constraint Recall Results]{Graphical representation of no graph constraint Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluation of performance change influenced by using 1, 2, or 6 layers of bidirectional GRUs in the BGT-Net model.} \label{fig:abls-gru2} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-gru3.png} \caption[Zero Shot Recall Results]{Graphical representation of zero shot Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluation of performance change influenced by using 1, 2, or 6 layers of bidirectional GRUs in the BGT-Net model.} \label{fig:abls-gru3} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-gru4.png} \caption[Mean Recall Results]{Graphical representation of mean Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluation of performance change influenced by using 1, 2, or 6 layers of bidirectional GRUs in the BGT-Net model.} \label{fig:abls-gru4} \end{figure*} \section{Hyper-parameter Study} The influence of the most important hyper-parameters on the model performance were tested. Batch size, learning rate, and number of solver iterations were varied for multiple experiments. PredCls was the main protocol on which the performance was compared. One hyper-parameter at a time was varied to understand its influence. The effect of changing parameters and therefore showing which parameter set performs the best can be seen below. \textbf{Leraning Rate.} Batch size was fixed at 24 and number of solver iterations at 24000. Learning rates 0.0001, 0.0005, 0.001 and 0.002 were tested. As \figref{fig:gru_tf-hyp1}, shows the best performance learning rate when evaluated using Recall@K. Evaluating on no graph constraint Recall@K illustrates no significant difference by the influence of learning rate. Similarly, in \figref{fig:gru_tf-hyp2}, the influence of the learning rate for evaluation on zero shot and mean Recall@K can not clearly be seen. Performance of learning rates 0.002, 0.001 and 0.00005 are almost the same. But learning rate 0.002 seems to have a slight edge on the other two. But this difference is marginal. Only the smallest learning rate 0.0001 seems to be under-performing. \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp1.png} \caption[PredCls Results for different Learning Rates 1]{Recall@K (left) and no graph constraint Recall@K (right) for Predicate Classification using different learning rates} \label{fig:gru_tf-hyp1} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp2.png} \caption[PredCls Results for different Learning Rates 2]{Zero shot Recall@K (left) and mean Recall@K (right) for Predicate Classification using different learning rates} \label{fig:gru_tf-hyp2} \end{figure} \newpage \textbf{Batch Size.} The non-changed hyper-parameters are set to 0.002 for the learning rate and 24000 to solver iterations. The examined batch sizes are 6, 12, 18 and 24. Only the smallest batch size 6 shows the lower performance in Recall@K as it can be seen in \figref{fig:gru_tf-hyp3}. This difference disappears for the no graph constraint Recall@K (visible in \figref{fig:gru_tf-hyp3} on the right) and for the zero shot Recall@K (shown in \figref{fig:gru_tf-hyp4} on the left). Significant and most evident difference in performance can be seen in the mean Recall@K in \figref{fig:gru_tf-hyp4}. Clearly, the largest batch size is performing better in this metric. Also in the other metrics, batch size 24 has the highest values. \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp3.png} \caption[PredCls Results for different Batch Sizes 1]{Recall@K (left) and no graph constraint Recall@K (right) for Predicate Classification using different batch sizes} \label{fig:gru_tf-hyp3} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp4.png} \caption[PredCls Results for different Batch Sizes 2]{Zero shot Recall@K (left) and mean Recall@K (right) for Predicate Classification using different batch sizes} \label{fig:gru_tf-hyp4} \end{figure} \newpage \textbf{Solver Iterations.} Keeping the learning rate at 0.002 and the batch size at 24, while changing the solver iterations to 6000, 12000, 18000 and 24000 shows the following influence of the solver iterations on the model performance. Throughout all the results in \figref{fig:gru_tf-hyp5} and \figref{fig:gru_tf-hyp6}, 6000 solver iterations under-perform significantly. Having only 6000 iterations does not allow the model to converge. As before with batch size, the difference in performance while changing the solver iterations is really small. Only for mean Recall@K the highest solver iteration does improve the results by almost 1 point. \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp5.png} \caption[PredCls Results for different Solver Iterations 1]{Recall@K (left) and no graph constraint Recall@K (right) for Predicate Classification compared to different solver iterations} \label{fig:gru_tf-hyp5} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp6.png} \caption[PredCls Results for different Solver Iterations 2]{Zero shot Recall@K (left) and mean Recall@K (right) for Predicate Classification compared to different solver iterations} \label{fig:gru_tf-hyp6} \end{figure} After these results, the best performing set of hyper-parameters can be found. Combining the results for batch size, learning rate and solver iterations leads to the choice of a learning rate of 0.002 a batch size of 24 and a solver iteration of 24000. Possibly, the least important of these would be the solver iterations since only the smallest difference going from 18000 to 24000 was detected. \section{Qualitative Results: BGT-Net} \begin{figure*}[!htb] \centering \includegraphics[width=1\linewidth]{./figures_supp/Picture-2col.pdf} \vspace{-0.15cm} \caption{Qualitative results of BGT-Model generated scene graphs. Two protocols are shown. left: Scene Graph Detection (SGDet), right: Scene Graph Classification (SGCls). BGT-Net is qualitatively compared to the MOTIFS model \cite{zellers2018neural}. Three colours are used to specify properties of detections. `Green' show detections that also perfectly correspond with ground-truth. `Red' is used for wrong detections and `orange' for detections not available in ground-truth but when checking with visual scene still represent the situation correctly.} \vspace{-3mm} \label{fig:qual_res} \end{figure*} The qualitative results in Figure \ref{fig:qual_res} show generated scene graphs on images of the Visaul Genome dataset. The examples are compared to the scene graphs generated by the MOTIFS model \cite{zellers2018neural}. For illustration purpose, the objects and relationships are coloured to represent properties of these detection. Object or relationship coloured ”green” are detected properly and correspond to the ground-truth. `Red' shows wrongly detected entities. For objects this can be either due to incorrect class prediction or due to not detection of the object during detection step with the Faster R-CNN. `Orange' denotes detections which do not correspond with the ground-truth annotations but can be validated by human inspection which means that the prediction generally corresponds with the visual scene. In Figure \ref{fig:qual_res}, the scene graphs generated with the Scene Graph Detection (SGDet) protocol are shown on the left and the ones generated with the Scene Graph Classification (SGCls) protocol are shown on the right. In SGDet, in many images, a large amount of objects are being detected. To increase readability, the object connected to the ground-truth objects are additionally inserted into the scene graph (with the colour `orange'). In many images, lots of $<$ subject- object-relationship$>$ triplets get correctly predicted but these cannot be found in the ground-truth triplets. This can effect the the performance of the model since these maybe correctly detected but not annotated in ground-truth and influence the prediction of other relationships. Both of the compared models in Figure \ref{fig:qual_res}, show errors in their predictions. But while detecting an object wrongly happens quite rarely, the relationship prediction is still much more prone to errors. This can be just the problem of the model but it is much more likely that many of the predictions made are not essentially wrong. This can be illustrated with the example of the object pair `person' and `pants'. Most often a person `wears' their pants. Relationships like `has', `in' and `on' do not contradict the reality. Added difficulty lays in the fact that throughout the dataset, these mentioned relationships do recently also appear. But there cannot be an evidence in the image what the relationship in this case can be because the difference between $<$person-pants-wears$>$ and $<$person-pants-has$>$ will not be visible in the image. This leads to worse model performance directly induced by the characteristics of the dataset. As shown in \ref{fig:qual_res}, errors in object prediction in SGCls do not happen very often. This may be the result of the highly improved performance of the BGT-Net in this protocol when measured in all evaluated metrics. Compared to the other protocols, the gained performance in SGCls is proportionally higher. {\small \bibliographystyle{ieee_fullname} \section{Introduction} \vspace{-1mm} Visual understanding of scenes are broadly covered by object detection \cite{szegedy2013deep,papageorgiou2000trainable} and localization \cite{sullivan2001bayesian, conaire2007improved} for single or multiple objects. Evolved from detection of various objects, image segmentation \cite{cooper1998tractability, alvarez2012road} is another research topic which helps to understand the attributes of the scene. While these techniques supply some useful information of the image, but a scene also largely depends on the interactions or relations between objects. This idea led to scene graphs which describe the scene by incorporating the objects and their pairwise relations. This relation is represented by a directed edge pointing from the subject to the object. Evaluating a scene by detecting the objects and the relationships between them allows building a graph consisting of nodes representing the objects and the edges representing the relations. It consists of number of triplets represented in $<$subject-relationship-object$>$ form. They help in aiding deep understanding of the scene for various vision tasks such as visual reasoning \cite{shi2019explainable}, image captioning \cite{yang2019auto, li2019know}, image retrieval \cite{johnson2015image, schuster2015generating, schroeder2020structured} and visual question answering \cite{zhang2019empirical,ghosh2019generating,teney2017graph}. To improve these applications and their benefits, it is crucial to have a well performing model which generates scene graphs that corresponds to the actual visual scene. The directional nature of a triplet in scene graph defines the subject and object in a triplet. Scene graph generation (SGG) is considered a complex problem in computer vision because of the imbalanced nature of the datasets and intricate relationship information. As stated in MOTIFS \cite{zellers2018neural}, combinations of at least two triplets appear in many images. So, the presence of some objects highly increase the probability of the presence of other objects. Communication i.e. information flow between the detected objects has been shown to be beneficial for improving the performance of scene graph generation models \cite{zellers2018neural, chen2019counterfactual}. \begin{figure} \includegraphics[scale=0.33]{./figures/sgg1.png} \caption{Two different scene graphs of the same given image on the left. Top: The ground-truth scene graph as annotated in the Visual Genome dataset. Below: A generated scene graph. As in many cases, the generated scene graph does capture the visual scene correctly, since the scene graph generation model only predicts frequently appearing relationships.} \vspace{-7mm} \label{sgg_1} \end{figure} The frequency distribution of the relationship within the Visual Genome dataset is long-tailed \cite{KrishnaZGJHKCKL16}. Due to this, scene graph detection models can already achieve good performance by only predicting the most frequent relationship for the respective subject-object pair. Figure \ref{sgg_1} illustrates the problem almost every SGG model faces. In many object pairings, the relationship is trivial and mostly possessive or geometric (e.g. \textit{on}, \textit{under}, or \textit{next to}). The detailed descriptive and semantic relationships such as \textit{jumping over} as shown in Figure \ref{sgg_1} (given in the ground-truth) will not often be predicted since it rarely occurs. For creating models that represent less frequent relationships more precisely, an approach to handle dataset bias must be found. Since the bias in the dataset can also be beneficial, e.g. the probability for the relationship \textit{reading} will be much higher than for \textit{eating} if the subject-object pair given is person and book \cite{tang2020unbiased}, traditional debiasing methods will most likely strongly harm the performance of the model. For this reason, the handling of the bias in the dataset is one of the most under-explored properties of the scene graph generation task. In this paper, we propose a novel model for SGG. The objects present in an image are highly dependent on the presence of other objects, for instance, if there is a bike in the scene, then there will be two tyres in the same scene with a very high probability. This model uses a bidirectional GRU (BiGRU) layer to send information from every object to every other. This allows benefiting from the fact that some objects will increase the possibility for specific other objects to be present. Subsequently to this layer that covers the object-object communication, a transformer encoder layer is used to predict the object classes. Objects and their preferred or observed relations are closely connected. To extract the information for the edge, a similar approach as in \cite{zellers2018neural} is followed to specify the edge context for every detected object. We use an additional transformer encoder layer for this task of extracting the edge context features. Using the object representations, their respective edge context is then used for the relationship prediction. In this procedure, a log-softmax function is applied to the subject-object pairwise relationship distribution. Following this Frequency Softening (FS), a Bias Adaptation (BA) approach \cite{lin2020gpsnet} is used. The bias for every subject-object is controlled by the bias adaptation term which takes scene-specific inputs to vary the amount of added bias. The contribution summary of the proposed BGT-Net is given in four modules to improve scene graph generation performance: (1) Object-object communication is performed using the BiGRU's. (2) A transformer encoder with scaled-dot-product attention is used to predict object classes after they have received information about the other objects present in the scene. (3) For every object, a second transformer encoder is used to gather information for the edges. (4) To tackle the bias in the relationship distribution, FS and BA \cite{lin2020gpsnet} is adopted. The evaluation efficacy of the proposed BGT-Net is performed on three SGG datasets: Visual Genome (VG) \cite{KrishnaZGJHKCKL16}, OpenImages (OI) \cite{abs-1811-00982}, and Visual Relationship Detection (VRD) \cite{lu2016visual}. We perform extensive experiments and ablation study to demonstrate the effectiveness of BGT-Net. Experimental results illustrate that the proposed BGT-Net outperforms the state of the art SGG results on a common metric Recall@K and on different datasets to the best of our knowledge. \vspace{-2.5mm} \begin{figure*}[tbp] \setlength\abovecaptionskip{-1.8\baselineskip} \setlength\belowcaptionskip{2pt} \begin{center} \vspace{-3mm} \includegraphics[height=5cm, width=17.5cm]{./figures/BGT-Net.png} \vspace{0mm} \topcaption{The framework of BGT-Net uses Faster R-CNN (with VGG-16 or ResNext-101 as the backbone) to get the visual features and spatial locations of object proposals. It includes various sub-modules for the task of SGG: (1) New technique of using BiGRU for object-object communication, (2) Novel method of using a transformer encoder with scaled-dot-product attention for predicting object classes after they have received information of the other objects present in the scene, (3) Additional transformer encoder is used to get the edge features, (4) FS and BA are used for dealing with the bias in the dataset. } \vspace{-1mm} \label{BGT-Model} \end{center} \end{figure*} \vspace{-0.075mm} \section{Related Work} \vspace{-1.5mm} From the ongoing research in scene graph generation, two different approaches for scene graph construction have developed. In the less common two-stage approach \cite{DBLP:journals/corr/abs-1812-01880, herzig2018mapping, chen2019counterfactual, DBLP:journals/corr/abs-1812-01880}, attributes of the scene graph are used in the second training step to refine the results produced by the first stage. Much more common are the one-stage approaches \cite{chen2019counterfactual,zellers2018neural,chen2019knowledge,DBLP:journals/corr/XuZCF17, yang2018graph, lin2020gpsnet,li2017scene,lu2016visual,li2018factorizable, qi2019attentive} which focus only on object detection and relationship classification, while almost neglecting intrinsic features. The proposed BGT-Net follows a one step approach and has the following advantages as compared to the literature work: (1) It uses object-object communication which improves the performance in SGG; (2) It deploys transformer encoder for object and edge context prediction which has shown to be highly beneficial in optimizing the parameters of SGG; (3) It is easy to train. The MOTIFS \cite{zellers2018neural} stated in the early days of scene graph generation, that there are different combinations of triplets that appear in a lot of images. Therefore, a dependency between object appearances is present in the datasets. To leverage this information object communication has been examined in the CMAT model \cite{chen2019counterfactual} and improved the performance of the model. All of the published works show difficulties with the bias present in the Visual Genome dataset, which is widely used in the scene graph generation task. This bias arrives from the long-tailed relationship distribution. The GPS-Net \cite{lin2020gpsnet} tackled this problem with FS and BA which worked well compared to the previous works. The overall performance of the model could be improved as well as improvements in mean Recall@K were achieved, which gives reasoning about the positive effect of their approach in handling the dataset bias. So, motivated from GPS-Net, BGT-Net uses FS and BA. \break While the GPS-Net changed the way the model was built, another recent work \cite{tang2020unbiased} developed a Scene Graph Diagnosis toolkit that can be used on a casually built scene graph. This tool kit is based on casual inference. Drawing the counterfactual causality to the proposed graph allows inferring with the bad bias. This approach did largely improve the mean Recall@K but decreased the other metrics significantly. Similarly \cite{yan2020pcpl}, adaptively changed the weights of the loss by using the correlation between the relationship classes. This work improved mean Recall@K but had overall quite low Recall@K results. \vspace{-1mm} \section{Approach} \label{chp:GRU-Transformer} The illustration of the BGT-Model can be found in Figure \ref{BGT-Model}. The regions of interest and object proposals are obtained by employing a Faster R-CNN object detector \cite{ren2015faster}. Following the VG-split \cite{DBLP:journals/corr/XuZCF17}, there are 151 object categories (including 'background') and 50 relationship categories (including 'no relation'). For every proposal $i$, the visual feature $\boldsymbol{\hat{x_{i}}}$ is formed by concatenating the ROI (region of interest) feature $\boldsymbol{f_{i}} \in \mathbb{R}^{2048}$, the class confidence scores $\boldsymbol{s_{i}} \in \mathbb{R}^{151}$, and the spatial feature of the proposal bounding box $\boldsymbol{s_{i}} \in \mathbb{R}^{4}$. For the next step, the $\boldsymbol{x_{i}} \in \mathbb{R}^{512}$ gets transformed by the projection of $\boldsymbol{\hat{x_{i}}}$ into a 512-dimensional subspace. For the relationship classification, the union feature $\boldsymbol{u_{i,j}} \in \mathbb{R}^{2048}$ for every pair of objects $i$ and $j$ is extracted in the object detection stage. These feature vectors representing the scene are used in the following modules of the BGT-Model. In Section \ref{subsec:obj_com}, the object communication step implemented with a BiGRU is explained in detail. Section \ref{chp:transformer}, introduces the object classification and edge information generation step using transformers. In Section \ref{chp:soft_adapt}, the FS of the long-tailed relationship distribution and the BA as a pre-processing for the relationship classification is described. \subsection{Object Communication} \label{subsec:obj_com} The object communication module takes the visual features $\boldsymbol{x_{i}}$ as input. The communication between the objects is implemented by a BiGRU. Due to the architecture of BiGRU, information from every object can flow to every other object. This information flow can be regulated by the BiGRU by learning which information shall be passed and which information shall be blocked. The output of the object communication step is therefore given by: \begin{equation} \hat{O} = BiGRU([x_{i}]_{i=1,2,...,n}) \end{equation} Where $\hat{O} = \{\hat{o}_{1}, \hat{o}_{2}, ... , \hat{o}_{n} \}$ are the object features after the communication step. The $\hat{o}_{i} \in \mathbb{R}^{1028}$ is obtained by concatenating the outputs $\overrightarrow{\hat{o}}_{i}$ (left to right in BiGRU) and $\overleftarrow{\hat{o}}_{i}$ (right to left in BiGRU), such that: \vspace{-2mm} \begin{equation} \hat{o}_{i} = [\overrightarrow{\hat{o}}_{i}, \overleftarrow{\hat{o}}_{i}] \in \mathbb{R}^{1028} \end{equation} \vspace{-5mm} \subsection{Object and Edge Transformers} \label{chp:transformer} The output $\hat{O}$ is projected to a 512-dimensional subspace to be fed into the Object transformer encoder. This transformer encoder follows the model architecture proposed by \cite{DBLP:journals/corr/VaswaniSPUJGKP17}, and takes the encoder block of the complete transformer model. This transformer encoder is built up by a Multi-Head attention layer, an Add \& Norm layer, a Feed Forward layer, and another Add \& Norm layer. The three inputs to the Multi-Head Attention layer are the values $V$, the keys $K$ and the queries $Q$. According to \cite{DBLP:journals/corr/VaswaniSPUJGKP17}, these three inputs are obtained from a single input. Using three different feed-forward fully-connected layers, yields the queries, keys, and values. For every attention head $i$ (here i=1,2,..,8) these values are calculated by: \vspace{-2mm} \begin{equation} Q_{i} = \hat{O} * W^{Q}_{i} \end{equation} \vspace{-5mm} \begin{equation} K_{i} = \hat{O} * W^{K}_{i} \end{equation} \vspace{-4mm} \begin{equation} V_{i} = \hat{O} * W^{V}_{i} \end{equation} \vspace{-1mm} Where $W^{Q}_{i} \in \mathbb{R}^{512 \times d_{k}}$, $W^{K}_{i} \in \mathbb{R}^{512 \times d_{k}}$ and $W^{V}_{i} \in \mathbb{R}^{512 \times d_{v}}$ are learnable parameter matrices. Also, $d_{k} = d_{v} = 64$ are the same for this application. From these values, the Scaled Dot-Product attention is calculated, such that the output of each attention head is given by: \vspace{-3mm} \begin{equation} Z_{i} = softmax(\frac{Q_{i} * K_{i}^{T}}{\sqrt{d_{k}}}) * V_{i} \end{equation} \vspace{-1mm} Concatenating $Z_{i}$'s give the output of the Multi-Head Scaled Dot-Product layer as $Z$. This is then fed through another fully-connected layer to bring it back to the dimension of the input matrix $\hat{O}$. \vspace{-3mm} \begin{equation} Z = concatenate(Z_{1}, Z_{2}, ... , Z_{n_{heads}}) \end{equation} \vspace{-1mm} The Add \& Norm layer adds the input of the previous Multi-Head Attention layer as a residual connection to the output of the attention layer. The normalization applied is a normalization layer following the approach of \cite{ba2016layer}. Here, it is suggested that the `covariate shift' problem can be reduced by changing the mean and the variance of the summed inputs in every layer. This is followed by a Feed Forward layer with two linear transformations and a ReLU activation followed by another Add \& Norm layer. This transformer encoder block gets repeated 6 times. The output $Z_{6}$ of the last repetition is then used to predict the object labels: \vspace{-3mm} \begin{equation} O = softmax(W_{o} * Z_{6}') \end{equation} \vspace{-1mm} Where $W_{o} \in \mathbb{R}^{512 \times 151}$ predicts the object class distribution for each detected object. Repeating this procedure but using the output $Z_{6}$ of the Object transformer as input to the Edge transformer yields feature vectors having information about the edges for every object. Similarly to \cite{zellers2018neural}, this information then can be used in the relationship prediction step. This edge information is given formally by: \vspace{-3mm} \begin{equation} E = TransformerEncoder(Z_{6}) \end{equation} \vspace{-1mm} Where $E = \{e_{1}, e_{2},..., e_{n}\}$ contains the edge information for every object. \subsection{Frequency Softening(FS), Bias Adaptation(BA)} \label{chp:soft_adapt} To handle the long-tailed relationship distribution present in the Visual Genome dataset, the procedure of softening this distribution and adapting the bias term for every subject-object pair form \cite{lin2020gpsnet} is adopted. The used features in this step is different than in the GPS-Net \cite{lin2020gpsnet} , but the principle stays the same. The softening of the relationship distribution is done by applying a log-softmax function to the original distribution. The softened frequency distribution is therefore given by Eq. \ref{eq:10}. The probability distribution $p_{i \rightarrow j}$ of every object pair $i$ and $j$ must be softened separately. Based on this definition, softening does not take any information of the respective visual scene into account. \vspace{-3mm} \begin{equation} \label{eq:10} \tilde{p}_{i \rightarrow j} = log\ softmax(p_{i \rightarrow j}) \end{equation} \vspace{-4mm} BA is used to get a case-specific adaptation of the above term. BA allows us to adjust the bias in the relationship prediction step. This adaptation term takes the appearance of the subject-object pair $i$, $j$ into account, by using their union feature $u_{i,j}$. The BA term $d$ can be calculated by: \vspace{-3mm} \begin{equation} d = W_{p} * u_{i,j} \end{equation} \vspace{-1mm} Where $W_{p} \in \mathbb{R}^{2048}$ is the transformation matrix and $u_{i,j}$ is the union feature of the subject-object pair. In the relationship prediction step, this bias term can be used as follows: \vspace{-3mm} \begin{equation} p_{i,j} = softmax( W_{r}(o'_{i} * o'_{j} * u_{i,j}) + d \odot \tilde{p}_{i \rightarrow j} ) \end{equation} \vspace{-0.5mm} In this equation, the bias $d \odot \tilde{p}_{i \rightarrow j}$ can be adjusted by changing $d$ accordingly. Here, $o'_{i} = [o_{i}, e_{i}]$ (same for $o'_{j}$) with '[-,-]' denotes the concatenation function representing the object features obtained in earlier steps. $W_{r}$ is the classifier that projects the features to the relationship class dimension. $ \odot $ denotes the Hadamard Product and $ * $ the fusion function. The fusion function for $ (x * y)$ is given by: \vspace{-3mm} \begin{equation} (x*y) = (W_{x}x + W_{y}y) - (W_{x}x - W_{y}y) \odot (W_{x}x - W_{y}y) \end{equation} \vspace{-1mm} With the parameter matrices $W_{x}$ and $W_{y}$, the fusion function is proposed to learn to count objects in images. \cite{DBLP:journals/corr/abs-1802-05766}. The predicted relationship between objects $i$ and $j$ is given by: \begin{equation} r_{i,j} = argmax(p_{i,j}(r)) \end{equation} Where $r$ lies in the set of relationship classes including background BG. \vspace{-1mm} \section{Experiments} \vspace{-1mm} We performed experiments using three different datasets, i.e., Visual Genome (VG) \cite{KrishnaZGJHKCKL16}, Visual Relationship Detection (VRD) \cite{lu2016visual}, and OpenImages (OI) \cite{abs-1811-00982}. \vspace{-1mm} \subsection{Visual Genome} \vspace{-1mm} Visual Genome dataset \cite{KrishnaZGJHKCKL16} is the most frequently used dataset for the SGG task. We use the same data statistics and evaluation metrics as widely used by the state of the art in this field, i.e., 150 object categories and 50 relationship categories are used. 70\% of the dataset is used for training and 30\% for testing. An additional 5000 images are taken from the training set and are used for validation. As used by the state of the art, we also employed Faster R-CNN \cite{ren2015faster} with VGG-16 or ResNext-101 as a backbone to get the characteristics of object proposals. To keep the fairness in the comparison with state-of-the-art, we chose same experimental factors as chosen by \cite{lin2020gpsnet}. \textbf{Performance Diagnosis:} The scene graph generation model is evaluated in three different sub-tasks: (1) Predicate classification, (2) Scene graph classification, and (3) Scene graph generation. These are the three protocols for which the model's performance is evaluated separately. Predicate Detection is used to specify the relation of given objects. This protocol evaluates the set of possible relations between a pair of given objects. The prediction of relationships without the effect of object detection is examined. In Phrase Detection, the input is an image and the outputs are triplets of subject-predicate-object. Additionally, one bounding box must have an overlap of at least 0.5 with the corresponding ground truth. For Relation Detection, the same input and output as in Phrase Detection is used. In this case, not only one but two bounding boxes of the pair of objects must have at least 0.5 overlap with the ground truth. \textbf{Metrics.} The evaluated metrics for the diagnosis of the model performance is Recall at K (R@K), no graph constraint Recall at K (nGR@K), zero-shot Recall at K (zsR@K), and mean Recall (mR@K), where $K$=20, 50, and 100, respectively. \textbf{Object Detector:} A pretrained Faster R-CNN object detector with a VGG-16 net \cite{han2015learning} or ResNeXt-101-FPN \cite{xie2017aggregated} as a backbone is used which is taken from \cite{lin2020gpsnet}. This detector was trained on the VG dataset, with batch size 8 and initial learning rate $8*10^{-3}$ which is decayed at the $30k^{th}$ and $40k^{th}$ iteration by the factor of 10. After training this detector on 4 2080Ti GPU, 28.14 mAP (with 0.5 IoU) was achieved. \textbf{Scene Graph Generation:} The scene graph generation is trained with an SGD optimizer \cite{bottou2012stochastic}. The learning rate is set at $10^{-3}$ for all three protocols. This learning rate was decayed by a factor of 10 twice after hitting a validation performance plateau. Per-Class non-maximal suppression (NMS) was applied with 0.5 IoU. 160 RoIs for each image were sampled. In contrast to previous works, we also considered non-overlapping regions for relationship prediction. To generalize the scene graph generation task, we used similar settings as used in literature \cite{lin2020gpsnet}. For model training, an RTX Titan was used. The batch size was set to 12 and the learning rate started at $10^{-3}$ and was reduced two times by a factor of 10 after hitting a validation performance plateau. The number of solver iterations was set to 18000. \vspace{-3mm} \subsection{OpenImages} \vspace{-1mm} The training and validation sets of the OpenImages dataset contain 53,953 and 3,234 images. For comparison, we use the same Faster R-CNN detector with a pre-trained ResNeXt- 101-FPN backbone as used by \cite{lin2020gpsnet,zhang2019graphical}. Also, the same data processing and evaluation metrics are used as in these previous works \cite{lin2020gpsnet,zhang2019graphical}. The evaluation metrics are Recall$@$50, weighted mean average precision (AP) of relationships wmAP\textsubscript{rel}, and weighted mean AP of phrase wmAP\textsubscript{phr}. The final score is given by $0.2*R@50 + 0.4*wmAP_{rel} + 0.4*wmAP_{phr}$, which was adopted from the OpenImages challenge formula \cite{DBLP:journals/corr/abs-1903-02728}, where the mAP was replaced by its weighted counterpart. The replacement of the mAP with the wmAP was done \cite{DBLP:journals/corr/abs-1903-02728} due to the extreme predicate class imbalance. The wmAP is achieved by scaling each predicate category by their relative ratios in the val set from the mAP. Important to note is that the wmAP\textsubscript{rel} evaluates the AP of the predicted triplet where both the subject and object boxes have an IoU of at least 0.5 with ground truth. The wmAP\textsubscript{phr} is quite similar but is utilized for the union box of the subject and the object. \vspace{-2mm} \subsection{Visual Relation Detection} \vspace{-1mm} The Visual Relation Detection (VRD) dataset was introduced by \cite{lu2016visual}. We adopt the same detectors as \cite{DBLP:journals/corr/abs-1903-02728}. Specifically, we use a pre-trained Faster R-CNN detector with VGG-16 backbone trained on the COCO dataset \cite{lin2014microsoft}. The evaluation process is given by \cite{lu2016visual} and the metrics used are R$@$50 and R$@$100. \subsection{Implementation Details} We follow the same implementation parameters as used by \cite{lin2020gpsnet}. To ensure a fair comparison with state of the art, we used VGG-16 and ResNext-101 as backbone. We use the 10$^{-3}$ as the learning rate and 6 as the batch-size which is the same as used by \cite{lin2020gpsnet}. We use SGD with momentum as the optimizer for the training process. We use the relationship between overlapped bounding boxes and subject-object pairs for the SGDet process. NMS with an IoU of 0.3 is used and the topmost 64 object proposals are chosen. The ratio of 3:1 is maintained during training between the subject-object pairs with and without any relationship. \subsection{Comparisons with State-of-the-Art Methods} \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llccccccccccccc} \hline & & & SGdet & & & & SGCls & & & & PredCls & & \\ \hline \textbf{Model} & \vline & $R@20$ & $R@50$ & $R@100$ & \vline & $R@20$ & $R@50$ & $R@100$ & \vline & $R@20$ & $R@50$ & $R@100$& \vline & Mean \\ \hline MOTIFS $\star$ \cite{zellers2018neural} & \vline & 21.4 & 27.2 & 30.3 & \vline & 32.9 & 35.8 & 36.5 & \vline & 58.5 & 65.2 & 67.1 & \vline & 43.7\\ FREQ $\star$ \cite{zellers2018neural} & \vline & 20.1 & 26.2 & 30.1 & \vline & 29.3 & 32.3 & 32.9 & \vline & 53.6 & 60.6 & 62.2 & \vline & 40.7\\ VCTREE-SL $\star$ \cite{DBLP:journals/corr/abs-1812-01880} & \vline & 21.7 & 27.7 & 31.1 & \vline & 35.0 & 37.9 & 38.6 & \vline & 59.8 & 66.2 & 67.9 & \vline & 44.9\\ VCTREE-HL $\star$ \cite{DBLP:journals/corr/abs-1812-01880} & \vline & 22.0 & 27.9 & 31.3 & \vline & 35.2 & 38.1 & 38.8 & \vline & 60.1 & 66.4 & 68.1 & \vline & 45.1\\ GB Net $\star$ \cite{Zareian_2020_ECCV} & \vline & - & 26.3 & 29.9 & \vline & - & 37.3 & 38 & \vline & - & 66.6 & 68.2 & \vline & 44.4\\ NODIS $\star$ \cite{yuren2020nodis} & \vline & 21.5 & 27.4 & 30.7 & \vline & 36 & 39.8 & 40.7 & \vline & 58.9 & 66 & 67.9 & \vline & 45.4\\ GPS-Net $\star$ \cite{lin2020gpsnet} & \vline & 22.6 & 28.4 & 31.7 & \vline & 36.1 & 39.2 & 40.1 & \vline & 60.7 & 66.9 & 68.8 & \vline & 45.9\\ CMAT $\star$ \cite{chen2019counterfactual} & \vline & 22.1 & 27.9 & 31.2 & \vline & 35.9 & 39 & 39.8 & \vline & 60.2 & 66.4 & 68.1 & \vline & 45.4\\ KERN $\star$ \cite{chen2019knowledge} & \vline & - & 27.1 & 29.8 & \vline & - & 36.7 & 37.4 & \vline & - & 65.8 & 67.6 & \vline & 44.1 \\ Graph R-CNN $\star$ \cite{yang2018graph} & \vline & - & 11.4 & 13.7 & \vline & - & 29.6 & 31.6 & \vline & - & 54.2 & 59.1 & \vline & 33.3\\ IMP $\star$ \cite{DBLP:journals/corr/XuZCF17} & \vline & - & 3.44 & 4 .24 & \vline & - & 21.72 & 24.38 & \vline & - & 44.75 & 53.08 & \vline & 25.3\\ \hline \textbf{BGT-Net (no BiGRU)} $\star$ & \vline & \textbf{23.61} & \textbf{ 30.4} & \textbf{ 34.81} & \vline & \textbf{ 33.81} & \textbf{ 37.22} & \textbf{ 38.12} & \vline & \textbf{ 57.98} & \textbf{ 64.75} & \textbf{ 66.63} & \vline & \textbf{46.9}\\ \hline \textbf{BGT-Net} $\star$ & \vline & \textbf{23.1} & \textbf{28.6} & \textbf{32.2} & \vline & \textbf{38.0} & \textbf{40.9} & \textbf{43.2} & \vline & \textbf{60.9} & \textbf{67.3} & \textbf{68.9} & \vline & \textbf{46.9}\\ \textbf{BGT-Net} $\diamond$ & \vline & \textbf{25.5} & \textbf{32.8} & \textbf{37.3} & \vline & \textbf{41.7} & \textbf{45.9} & \textbf{47.1} & \vline & \textbf{60.9} & \textbf{67.1} & \textbf{68.9} & \vline & \textbf{49.9}\\ \hline \end{tabular}} \vspace{0mm} \normalsize {\topcaption[Recall@K Model comparison with state-of-the-arts on the VG dataset.]{Recall@K Model comparison with state-of-the-arts on the VG dataset. We compare R@20, R@50, and R@100. For some literature work, the R@20 is not given. We used '$-$' which denotes that the result is unavailable. So, the mean is calculated using values of R@50 and R@100 to have fair comparison with state of the art. Models using the same VGG backbone are denoted with '$\star$' and the BGT-Net with ResNext-101 background is marked with '$\diamond$'.}\label{tab:comp_modelsVG}} \end{minipage} \hfill \vspace{-8mm} \end{table*} \begin{table}[h] \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llccccccc} \hline & & SGdet & & SGCls & & PredCls & & \\ \hline \textbf{Model} & \vline & $mR@100$ & \vline & $mR@100$ & \vline & $mR@100$ & \vline & Mean \\ \hline GB Net $\star$ \cite{Zareian_2020_ECCV} & \vline & 8.5 & \vline & 13.4 & \vline & \textbf{24} & \vline & 15.3 \\ IMP $\star$ \cite{DBLP:journals/corr/XuZCF17} & \vline & 4.8 & \vline & 6.0 & \vline & 10.5 & \vline & 7.1 \\ GPS-Net $\star$ \cite{lin2020gpsnet} & \vline & \textbf{9.8} & \vline & 12.6 & \vline & 22.8 & \vline & 15.1 \\ VCTREE-HL $\star$ \cite{DBLP:journals/corr/abs-1812-01880} & \vline & 8.0 & \vline & 10.8 & \vline & 19.4 & \vline & 12.8 \\ MOTIFS $\star$ \cite{zellers2018neural} & \vline & 6.6 & \vline & 8.2 & \vline & 15.3 & \vline & 10.0\\ KERN $\star$ \cite{chen2019knowledge} & \vline & 7.3 & \vline & 10 & \vline & 19.2 & \vline & 12.2\\ \hline \textbf{BGT-Net} $\star$ & \vline & 9.6 & \vline & \textbf{13.7} & \vline & 23.2 & \vline & \textbf{15.5}\\ \hline \end{tabular}} \normalsize \vspace{-2mm} \caption[Comparison on mR@100]{Comparison on mR@100 between various methods across all 50 relationship categories.} \label{tab:meanRecall} \vspace{-7mm} \end{table} \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llccccccccccc} \hline & & & SGdet & & & & SGCls & & & & PredCls & \\ \hline \textbf{Model} & \vline & $nGR@20$ & $nGR@50$ & $nGR@100$ & \vline & $nGR@20$ & $nGR@50$ & $nGR@100$ & \vline & $nGR@20$ & $nGR@50$ & $nGR@100$ \\ \hline GB Net $\star$ \cite{Zareian_2020_ECCV} & \vline & - & 29.3 & 35 & \vline & - & 46.9 & 50.3 & \vline & - & \textbf{83.5} & \textbf{90.3}\\ CMAT $\star$ \cite{chen2019counterfactual} &\vline & 23.7 & 31.6 & 36.8 & \vline & \textbf{41} & \textbf{48.6} & \textbf{52} & \vline & \textbf{68.9} & 83.2 & 90.1\\ KERN $\star$ \cite{chen2019knowledge} &\vline & - & 30.9 & 35.8 & \vline & - & 45.9 & 49 &\vline & - & 65.8 & 67.6\\ \hline \textbf{BGT-Net (no BiGRU)} $\diamond$ & \vline & 24.23 & 32.88 & 39.06 & \vline & 38.55 & 46.28 & 50.04 & \vline & 65.92 & 80.51 & 87.82 \\ \textbf{BGT-Net} $\diamond$ & \vline & \textbf{27.24} & \textbf{36.91} & \textbf{43.72} & \vline & \textbf{47.83} & \textbf{57.67} & \textbf{62.29} & \vline & \textbf{69.1} & \textbf{83.71} & \textbf{90.55} \\ \hline \hline \textbf{Model} & \vline & $mR@20$ & $mR@50$ & $mR@100$ & \vline & $mR@20$ & $mR@50$ & $mR@100$ & \vline & $mR@20$ & $mR@50$ & $mR@100$ \\ \hline GB Net $\star$ \cite{Zareian_2020_ECCV} & \vline & - & 7.1 & 8.5 & \vline & - & 12.7 & 13.4 & \vline & - & \textbf{22.1} & \textbf{24} \\ GPS-Net$\star$\cite{lin2020gpsnet} & \vline & - & - & \textbf{9.8} & \vline & - & - & 12.6 & \vline & - & - & 22.8 \\ KERN $\star$\cite{chen2019knowledge} & \vline & - & 6.4 & 7.3 & \vline & - & 9.4 & 10 & \vline & - & 17.7 & 19.2 \\ \hline \textbf{BGT-Net (no BiGRU)} $\diamond$ & \vline & 4.62 & 6.55 & 7.85 & \vline & 7.31 & 9.14 & 9.71 & \vline & 12.14 & 15.59 & 17.05 \\ \textbf{BGT-Net} $\diamond$ & \vline & \textbf{5.69} & \textbf{7.81} & 9.25 & \vline & \textbf{10.41} & \textbf{12.77} & \textbf{13.61} & \vline & \textbf{16.8} & \textbf{20.56} & \textbf{22.98} \\ \hline \hline \textbf{Model} & \vline & $zsR@20$ & $zsR@50$ & $zsR@100$ & \vline & $zsR@20$ & $zsR@50$ & $zsR@100$ & \vline & $zsR@20$ & $zsR@50$ & $zsR@100$ \\ \hline Motifs $\star$\cite{tang2020sggcode} & \vline & 0 & 0.05 & 0.11 & \vline & 0.32 & 0.91 & 1.39 & \vline & 1.35 & 3.63 & 5.36 \\ IMP $\star$\cite{DBLP:journals/corr/XuZCF17} & \vline & 0.18 & 0.38 & 0.77 & \vline & 2.01 & 3.03 & 3.92 & \vline & 12.17 & 17.66 & 20.25 \\ \hline \textbf{BGT-Net} $\diamond$& \vline & \textbf{1.22} & \textbf{2.38} & \textbf{3.42} & \vline & \textbf{4.8} & \textbf{7.37} & \textbf{8.78} & \vline & \textbf{12.23} & \textbf{18.31} & \textbf{21.51} \\ \hline \end{tabular}} \vspace{1mm} \normalsize {\topcaption[No Graph Constraint Recall Results of transformer Model]{nGR@K, mR@K and zsR@K comparison with state-of-the-art on the VG dataset. The version of the BGT-Net, i.e., the BGT-Net (no BiGRU) is also compared.}\label{tab:comp_models_ngc1}} \end{minipage} \hfill \vspace{-9mm} \end{table*} \begin{table}[h] \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llcccccccccccccc} \hline & \vline & Predicate Detection &\vline & \multicolumn{2}{c}{Relation Detection} & &\multicolumn{2}{c}{Phrase Detection} & & \\ \hline \textbf{Model} & \vline & $R@50$ & \vline & $R@50$ & $R@100$ & \vline & $R@50$ & $R@100$ & \vline & Mean \\ \hline VTransE \cite{DBLP:journals/corr/ZhangKCC17} & \vline & 44.8 & \vline & 19.4 & 22.4 & \vline & 14.1 & 15.2 & \vline & 23.2\\ ViP-CNN \cite{article} & \vline & - & \vline & 17.3 & 20.0 & \vline & 22.8 & 27.9 & \vline & 22\\ VRL \cite{DBLP:journals/corr/LiangLX17} & \vline & - & \vline & 18.2 & 20.8 & \vline & 21.4 & 22.6 & \vline & 20.8\\ KL distilation \cite{DBLP:journals/corr/YuLMD17} & \vline & 55.2 & \vline & 19.2 & 21.3 & \vline & 23.1 & 24.0 & \vline & 28.6\\ MF-URLN \cite{DBLP:journals/corr/abs-1905-01595} & \vline & 58.2 & \vline & 23.9 & 26.8 & \vline & 31.5 & 36.1 & \vline & 35.3\\ Zoom-Net $\diamond$ \cite{DBLP:journals/corr/abs-1807-04979} & \vline & 50.7 & \vline & 18.9 & 21.4 & \vline & 24.8 & 28.1 & \vline & 28.8\\ CAI + SCA-M $\diamond$ \cite{DBLP:journals/corr/abs-1807-04979} & \vline & 56.0 & \vline & 19.5 & 22.4 & \vline & 25.2 & 28.9 & \vline & 30.4\\ RelDN $\star$ \cite{DBLP:journals/corr/abs-1903-02728} & \vline & - & \vline & 25.3 & 28.6 & \vline & 31.3 & 36.4 & \vline & 30.4\\ GPS-Net $\star$ \cite{lin2020gpsnet} & \vline & 63.4 & \vline & 27.8 & 31.7 & \vline & 33.8 & 39.2 & \vline & 39.2\\ \hline BGT-Net $\star$ & \vline & \textbf{64.1} & \vline & \textbf{28.5} & \textbf{31.9} & \vline & \textbf{34.4} & \textbf{39.4} & \vline & \textbf{39.6}\\ \hline \end{tabular}} \normalsize \vspace{-1mm} \caption[Comparison on VRD]{Comparison on the VRD dataset \cite{lu2016visual}. '$\star$' and '$\diamond$' denote the models using the same object detector. The object detector with a VGG-16 backbone trained on COCO is used as in RelDN and GPS-Net to have fair comparison.} \vspace{-7mm} \label{tab:comp_vrd} \end{table} \begin{table*}[h] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llcccccccccccccc} \hline & \vline & & & & & \vline & \multicolumn{9}{c}{AP\textsubscript{rel} per class} \\ \hline \textbf{Model} & \vline & $R@50$ & $wmAP_{rel}$ & $wmAP_{phr}$ & $score_{wtd}$ & \vline & at & on & holds & plays & interacts with & wears & hits & inside of & under\\ \hline RelDN, $L_{0}$ \cite{DBLP:journals/corr/abs-1903-02728}& \vline & 74.67 & 34.63 & 37.89 & 43.94 & \vline & 32.40 & 36.51 & 41.84 & 36.04 & 40.43 & 5.70 & 55.40 & 44.17 & 25.00\\ RelDN \cite{DBLP:journals/corr/abs-1903-02728}& \vline & 74.94 & 35.54 & 38.52 & 44.61 & \vline & 32.90 & 37.00 & 43.09 & 41.04 & 44.16 & 7.83 & 51.04 & 44.72 & 50.00\\ GPS-Net \cite{lin2020gpsnet}& \vline & 77.29 & 38.78 & 40.15 & 47.03 & \vline & 35.10 & 38.90 & \textbf{51.47} & 45.66 & \textbf{44.58} & \textbf{32.35} & 71.71 & 47.21 & 57.28\\ \hline BGT-Net & \vline & \textbf{77.98} & \textbf{39.56} & \textbf{40.75} & \textbf{47.67} & \vline & \textbf{36.23} & \textbf{39.05} & 50.96 & \textbf{46.78} & 44.56 & 31.45 & \textbf{72.17} & \textbf{48.03} & \textbf{57.64}\\ \hline \end{tabular}} \normalsize \end{minipage} \hfill \vspace{-2mm} \caption[Comparison on OpenImages]{Comparison on OpenImages dataset \cite{DBLP:journals/corr/abs-1811-00982}. The BGT-Net uses a ResNext-101 backbone. Additionally, the same data processing and evaluation metrics as \cite{lin2020gpsnet, DBLP:journals/corr/abs-1903-02728} are followed to a ensure fair comparison.} \label{tab:comp_openimages} \vspace{-4mm} \end{table*} \textbf{Visual Genome:} BGT-Net outperforms all the compared previous literature work as shown in Table \ref{tab:comp_modelsVG} on R@K for all values of K . BGT-Net performs better than a recent model named GPS-net \cite{lin2020gpsnet} by 6$\%$ and by 12$\%$ on average at R@50 and R@100 over the three protocols when VGG-19 or ResNext-101 is used as the base for the Faster-RCNN, respectively. It also outperforms when an individual evaluation protocol is compared. The improvement is by 16.6$\%$ for SGDet, 17.3$\%$ for SGCls, and for 0.2$\%$ for PredCls. When compared to the classic MOTIFS \cite{zellers2018neural}, it showed an improvement of 7.3$\%$ and 14$\%$ on average at R@50 and R@100 over the three protocols when VGG-19 or ResNext-101 is used as a backbone for the Faster-RCNN, respectively. BGT-Net outperforms FREQ \cite{zellers2018neural}, VCTREE-SL \cite{DBLP:journals/corr/abs-1812-01880}, VCTREE-HL \cite{DBLP:journals/corr/abs-1812-01880}, GB-NET \cite{Zareian_2020_ECCV} , NODIS \cite{yuren2020nodis}, CMAT \cite{chen2019counterfactual}, KERN \cite{chen2019knowledge}, Graph R-CNN \cite{yang2018graph}, IMP \cite{DBLP:journals/corr/XuZCF17} by 14.9$\%$, 4.3$\%$, 3.9$\%$, 5.6$\%$, 3.2$\%$, 3.2$\%$, 6.3$\%$, 40.9$\%$, 85.4$\%$, respectively, on average at R@50 and R@100 over the three protocols when VGG-19 is used as a backbone for the Faster-RCNN and by 22.2$\%$, 11$\%$, 10.5$\%$, 12.3$\%$, 9.8$\%$, 9.8$\%$, 13.1$\%$, 49.9$\%$, 97.3$\%$, respectively, on average at R@50 and R@100 over the three protocols when ResNext-101 is used as a backbone for the Faster-RCNN. We evaluate Mean Recall of BGT-Net to understand its performance on the class imbalance problem. So, we study its performance by conducting experiments to calculate its Mean Recall \cite{chen2019knowledge,DBLP:journals/corr/abs-1812-01880, lin2020gpsnet}. We see in Figure \ref{meanrecall12} and Table \ref{tab:meanRecall} that BGT-Net performs well considering the Mean Recall evaluation metric. The mean of the Mean Recall over all the three evaluation metrics (SGDet, SGCls, PredCls) is 15.5 for BGT-Net and hence outperforms GB-Net and GPS-Net which are the best state-of-the-art on class imbalance handling having good performance on both mean R@K and R@K results. This gives a positive indication that BGT-Net can tackle the problem of class imbalance while simultaneously giving high R@K as compared to the other existing solutions to best of our knowledge. \textbf{Why BiGRU?} We investigated BGT-Net without BiGRU but BGT-Net (no BiGRU) has lower SGCls and PredCls results (see Table \ref{tab:comp_modelsVG}). The deciding factor for using BiGRU in BGT-Net is mR@K and nGR@K. Both these metrics significantly improve for all three: SGDet, SGCls, PredCls when BGT-Net is with BiGRU as shown in Table \ref{tab:comp_models_ngc1}.\\ Also shown in Table \ref{tab:comp_models_ngc1}, BGT-Net has high improvement on zsR@K as compared to \cite{DBLP:journals/corr/XuZCF17} and \cite{zellers2018neural} which shows that it is able to better detect those subject-predicate-object combinations which are not present in the training set. \begin{figure}[ht] \setlength\abovecaptionskip{0.4\baselineskip} \setlength\belowcaptionskip{-18pt} \begin{center} \includegraphics[scale=0.3]{./figures/bar_graph_MOTIFS.png}\\ \includegraphics[scale=0.3]{./figures/bar_graph_VCTREE.png} \par\nointerlineskip\vspace{-1mm} \caption{The increase in R@100 in PredCls of BGT-Net compared with the MOTIFS \cite{zellers2018neural} and VCTREE \cite{DBLP:journals/corr/abs-1812-01880}. The Top-35 relationship categories are selected according to their alphabetic occurrence.} \vspace{-2.5mm} \label{meanrecall12} \end{center} \end{figure} \vspace{-1mm} \textbf{OpenImages:} The results in Table \ref{tab:comp_openimages} show that BGT-Net performs very well on the OpenImages dataset. The overall score is 0.64 points higher than the GPS-Net model performance. This increase in performance is achieved by an overall increase in performance in all three evaluated metrics R$@$K, wmAP\textsubscript{rel}, and wmAP\textsubscript{phr}. An evaluation of the per-class AP is also shown. In this evaluation, some classes were chosen as in GPS-Net \cite{lin2020gpsnet} and RelDN \cite{DBLP:journals/corr/abs-1903-02728} to show class-specific performance. The performances of GPS-Net and the BGT-Net are quite close. For ''holds'', ''interacts with'' and ''wears'', the GPS-Net shows a higher AP while for the others the BGT-Net shows the highest AP. The overall performance of the BGT-Net outperforms the state-of-the-art performance of the GPS-Net model. \textbf{Visual Relationship Detection:} The evaluation results on VRD Dataset are illustrated in Table \ref{tab:comp_vrd}. The BGT-Net uses the same Detector as RelDN and GPS-Net. The BGT-Net outperforms the state-of-the-art models in all three evaluation metrics. So, BGT-Net shows the best to the date performance on the VRD dataset as well to the best of our knowledge, and which is better than GPS-Net and RelDN (previous best performing networks). \vspace{-2mm} \subsection{Ablation Studies} \vspace{-1mm} To evaluate and analyze our proposed BGT-Net, we conducted a number of ablations as shown in Table \ref{tab:ablation1}, Table \ref{tab:ablation2}, and Table \ref{tab:ablation3}. \textbf{Network Performance with a different combination of Modules.} In this study, we evaluate the effectiveness of the network in the presence of the three modules, i.e., Transformer, BiGRU, and FS, individually and collectively. The performance of the network increases with the presence of all three modules. Firstly, we evaluated for an individual module and then permutated the modules with each other to make a combination to evaluate the performance of different resulting configurations. As illustrated in Table \ref{tab:ablation1}, for all the three evaluation protocols, i.e., SGDet, SGCls, and PredCls, our proposed network with all the three modules outperforms the other network configurations with individual modules. When modules are used together, the network performance improves which shows that each individual module plays a significant role in predicting objects and their relationships. The FS and BA were adapted from [20]. In \cite{lin2020gpsnet}, they performed ablation study with and without FS and BA. It was shown that these modules improve the PredCls for all three R@20, R@50, and R@100. We included in our ablation the effect of using FS which showed that zsR@20, zs@50, and zsR@100 improved drastically for all three: SGDet, SGCls, PredCl, when using FS as shown in Table \ref{tab:ablation1}. \textbf{Performance with different number of Transformer Heads.} We performed this ablation to validate the optimized number of transformer heads in the network. As illustrated in Table \ref{tab:ablation2}, we can see that when 1, 2, or 6 number of transformer heads are used, the network with 6 transformer heads performs better in all the experiments than others for all the three evaluation protocols. This ablation shows that the number of transformer heads also effect the performance of the model and hence this factor is critical while designing the network for the SGG. This study motivated us to use six transformer heads in the novel BGT-Net. \textbf{Performance with different number of Bidirectional GRU Layers.} We compare networks with different number of BiGRU layers. To keep the comparison fair, we use all other same parameters in the experiments except the number of BiGRU layers. As shown in Table \ref{tab:ablation2}, it is evident that increasing the number of BiGRU layers does not significantly improve the performance, but it does increase the computational power and training time. Hence, in the BGT-Net, we only use one BiGRU layer. \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llllllccccccccccccccc} \hline & \vline &\textbf{Transformer} & \textbf{GRU} & \textbf{FS} & \vline & \textbf{R @ 20} & \textbf{R @ 50} & \textbf{R @ 100} & \vline & \textbf{nG R @ 20} & \textbf{nG R @ 50} & \textbf{nG R @ 100} & \vline & \textbf{zs R @ 20} & \textbf{zs R @ 50} & \textbf{zs R @ 100} & \vline & \textbf{mR @ 20} & \textbf{mR @ 50} & \textbf{m R @ 100}\\ \hline & \vline & x & - & - & \vline & 23.61 & 30.4 & 34.81 & \vline & 24.23 & 32.88 & 39.06 & \vline & 0 & 0 & 0 & \vline & 4.62 & 6.55 & 7.85\\ & \vline &- & x & - & \vline & 24.1 & 31.2 & 35.5 & \vline & 25.37 & 34.59 & 41.14 & \vline & 0 & 0 & 0.03 & \vline& 4.07 & 5.49 & 6.51 \\ SGDet& \vline& - & - & x & \vline & 22.3 & 28.17 & 32.56 & \vline & 25.04 & 34.58 & 41.23 & \vline & 0.95 & 1.27 & 2.21 & \vline & 4.47 & 5.98 & 7.65\\ & \vline &x & x & x & \vline & 24.68 & 31.87 & 36.18 & \vline & 26.23 & 35.87 & 42.46 & \vline & 1.22 & 2.38 & 3.42 & \vline& 5.69 & 7.81 & 9.25\\ \hline \hline & \vline & x & - & - & \vline & 33.81 & 37.22 & 38.12 & \vline & 38.55 & 46.28 & 50.04 & \vline & 0.15 & 0.45 & 0.7 & \vline & 7.31 & 9.14 & 9.71 \\ & \vline& - & x & - & \vline & 40.03 & 44 & 45.02 & \vline & 45.61 & 54.82 & 59.26 & \vline & 0.19 & 0.69 & 0.99 & \vline & 7.92 & 9.85 & 10.55 \\ SGCls & \vline& - & - & x & \vline & 35.63 & 38.92 & 39.77 & \vline & 39.41 & 47.92 & 55.56 & \vline & 3.25 & 4.99 & 5.78 & \vline & 8.2 & 10.65 & 11.34\\ & \vline& x & x & x & \vline & 41.72 & 45.69 & 46.74 & \vline & 47.96 & 57.42 & 61.92 & \vline & 4.12 & 6.72 & 8.06 & \vline & 10.41 & 12.77 & 13.61\\ \hline \hline & \vline& x & - & - & \vline & 57.98 & 64.75 & 66.63 & \vline & 65.92 & 80.51 & 87.82 & \vline & 0.64 & 2.06 & 3.69 & \vline & 12.14 & 15.59 & 17.05 \\ & \vline& - & x & - & \vline & 58.52 & 65.19 & 67.08 & \vline & 65.76 & 80.38 & 87.83 & \vline & 0.68 & 2.52 & 4.46 & \vline & 12.33 & 15.79 & 17.16 \\ PredCls & \vline& - & - & x & \vline & 56.73 & 63.48 & 65.53 & \vline & 64.87 & 79.56 & 87.2 & \vline & 11.9 & 17.78 & 20.97 & \vline & 12.05 & 15.22 & 16.46\\ & \vline & x & x & x & \vline & 58.71 & 65.25 & 67.1 & \vline & 67.27 & 82.05 & 89.29 & \vline & 12.06 & 18.22 & 21.49 & \vline & 14.36 & 17.88 & 19.44 \\ \hline \end{tabular}} \vspace{1mm} \normalsize {\topcaption[Recall@K comparison of BGT-Net with Model Performance of different Modules.]{Ablation study performed on evaluation of three models. All the experimental factors are kept same except the ones which are being evaluated to have fair comparison. The evaluation is conducted using Recall@K, nGR@K, zsR@K, and mR@K. } \label{tab:ablation1}} \end{minipage} \hfill \vspace{-5mm} \end{table*} \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llllccccccccccccccc} \hline & \vline &\textbf{Transformer Heads} & \vline & \textbf{R @ 20} & \textbf{R @ 50} & \textbf{R @ 100} & \vline & \textbf{nG R @ 20} & \textbf{nG R @ 50} & \textbf{nG R @ 100} & \vline & \textbf{zs R @ 20} & \textbf{zs Recall @ 50} & \textbf{zs R @ 100} & \vline & \textbf{mR @ 20} & \textbf{mR @ 50} & \textbf{m R @ 100}\\ \hline & \vline & 1 & \vline & 23.78 & 31.15 & 35.4 & \vline & 25.76 & 34.8 & 41.78 & \vline & 0.99 & 2.11 & 2.67 & \vline & 4.75 & 7.32 & 7.96\\ SGDet & \vline & 2 & \vline & 24.54 & 31.77 & 36.11 & \vline & 26.05 & 35.64 & 42.39 & \vline & 1.07 & 2.18 & 3.37 & \vline & 5.57 & 7.52 & 8.8\\ & \vline & 6 & \vline & \textbf{24.68} & \textbf{31.87 }& \textbf{36.18} & \vline & \textbf{26.23} & \textbf{35.87 }& \textbf{42.46} & \vline & \textbf{1.22} & \textbf{2.38} & \textbf{3.42 }& \vline &\textbf{ 5.69} & \textbf{7.81} & \textbf{9.25}\\ \hline \hline & \vline & 1 & \vline & 38.62 & 42.54 & 43.66 & \vline & 45.01 & 52.1 & 58.78 & \vline & 2.67 & 4.31 & 4.89 & \vline & 8.21 & 9.98 & 10.32 \\ SGCls & \vline & 2 & \vline & 39.37 & 43.42 & 44.51& \vline & 45.25 & 54.51 & 59.17 & \vline& 3.32 & 5.37 & 6.48 & \vline & 9.01 & 11.14 & 11.89 \\ & \vline& 6 & \vline &\textbf{ 41.72 } & \textbf{45.69} & \textbf{46.74} & \vline & \textbf{47.96 }& \textbf{57.42} & \textbf{61.92} & \vline & \textbf{4.12} & \textbf{6.72} & \textbf{8.06} & \vline & \textbf{10.41} & \textbf{12.77} & \textbf{13.61 }\\ \hline \hline & \vline & 1 & \vline &58.03 & 64.8 & 66.89 & \vline & 66.23 & 81.06 & 87.89 & \vline & 11.06 & 17.39 & 19.45 & \vline & 12.55 & 16.21 & 17.51 \\ PredCls & \vline & 2 & \vline & 58.45 & 64.98 & 67.03 & \vline & 66.89 & 81.66 & 88.34 & \vline & 11.9 & 18.11 & 21.34 & \vline & 12.91 & 16.75 & 18.92 \\ & \vline& 6 & \vline & \textbf{58.71} & \textbf{65.25} & \textbf{67.1 }& \vline & \textbf{67.27} & \textbf{82.05} & \textbf{89.29} & \vline & \textbf{12.06} & \textbf{18.22} &\textbf{ 21.49 }& \vline & \textbf{14.36} & \textbf{17.88} & \textbf{19.44} \\ \hline \end{tabular}} \vspace{1mm} \normalsize {\topcaption[Model Performance for different Transformer Heads.]{Various R@K performance for the different numbers of Transformer Heads in BGT-Net using VG dataset. } \label{tab:ablation2}} \end{minipage} \hfill \vspace{-5mm} \end{table*} \begin{table*}[!htb] \begin{minipage}{\textwidth} \centering \footnotesize \resizebox{\columnwidth}{!}{% \begin{tabular}{llllccccccccccccccc} \hline & \vline &\textbf{Bi-GRU} & \vline & \textbf{R @ 20} & \textbf{R @ 50} & \textbf{R @ 100} & \vline & \textbf{nG R @ 20} & \textbf{nG R @ 50} & \textbf{nG R @ 100} & \vline & \textbf{zs R @ 20} & \textbf{zs Recall @ 50} & \textbf{zs R @ 100} & \vline & \textbf{mR @ 20} & \textbf{mR @ 50} & \textbf{m R @ 100}\\ \hline & \vline & 1 & \vline& \textbf{25.54} & \textbf{32.87} & \textbf{37.3 } & \vline & \textbf{27.24} & \textbf{36.91} & \textbf{43.72} & \vline & \textbf{4.8} & \textbf{7.37} & \textbf{8.78} & \vline & \textbf{10.41 }& \textbf{12.77} & \textbf{13.61}\\ SGDet & \vline & 2 & \vline & 24.54 & 31.77 & 36.11 & \vline & 26.05 & 35.64 & 42.39 & \vline & 1.07 & 2.18 & 3.37 & \vline & 9.91 & 12.28 & 13.12 \\ & \vline & 6 & \vline & 23.93 & 31.01 & 35.37 & \vline & 25.47 & 35.02 & 41.63 & \vline & 1.12 & 2.11 & 3.1 & \vline & 5.49 & 7.53 & 8.86 \\ \hline \hline & \vline & 1 & \vline & 41.69 & \textbf{45.96} & \textbf{47.06} & \vline & 47.83 & \textbf{57.67} & \textbf{62.29 }& \vline & 2.67 & 4.31 & 4.89 & \vline & 8.21 & 9.98 & 10.32 \\ SGCls & \vline & 2 & \vline & \textbf{41.72} & 45.69 & 46.74 & \vline & \textbf{47.96} & 57.42 & 61.92 & \vline&\textbf{ 4.12} & \textbf{6.72} & \textbf{8.06} & \vline & \textbf{9.01} & \textbf{11.14} & \textbf{11.89} \\ & \vline& 6 & \vline & 41.08 & 45.57 & 46.23& \vline & 46.98 & 57.12 & 61.3 & \vline & 4.02 & 6.56 & 7.79 & \vline & 8.54 & 11.81 & 13.01 \\ \hline \hline & \vline & 1 & \vline &\textbf{ 59.21} & \textbf{65.68} & \textbf{67.45} & \vline & \textbf{67.69} &\textbf{ 82.42} & \textbf{89.45} & \vline & \textbf{ 12.23} & \textbf{18.31} & \textbf{21.51} & \vline & \textbf{14.7} & \textbf{18.46} & \textbf{20.08 } \\ PredCls & \vline & 2 & \vline & 58.71 & 65.25 & 67.1 & \vline & 67.27 & 82.05 & 89.29 & \vline & 12.06 & 18.22 & 21.49 & \vline & 14.36 & 17.88 & 19.44 \\ & \vline& 6 & \vline & 58.22 & 65.45 & 66.74 & \vline & 66.91 & 81.87 & 88.69 & \vline & 11.83 & 18.07 & 21.1 & \vline & 14.22 & 17.59 & 19.21\\ \hline \end{tabular}} \vspace{1mm} \normalsize {\topcaption[Model Performance for different Numbers of Bidirectional GRU Layers.]{Various R@K performance comparison in relation to the number of BiGRU layers present in network when trained on VG dataset.} \label{tab:ablation3} } \end{minipage} \hfill \vspace{-5mm} \end{table*} \begin{figure*}[!htb] \vspace{-2mm} \centering \includegraphics[width=1\linewidth, height=1.9cm]{figures/ill_ex.png} \vspace{-0.15cm} \caption{Qualitative results showing scene graphs generated by the BGT-Net. For both examples, (a) shows the scene graph generated in the SGDet protocol, and (b) the one generated in SGCls. The green arrow denotes that the detection object or relationship corresponding to the ground-truth. Orange arrows denote the detections that are not available in ground-truth but do represent the image properly. Red marks errors that are used for undetected relationships or wrongly detected objects.} \vspace{-6mm} \label{fig:5} \end{figure*} \textbf{Qualitative Results.} In Figure~\ref{fig:5}, Left: shows the qualitative results. In SGCls, the bounding boxes are given and the model has to predict the object class and the relationships. In SGDet, no information is given. In SGDet up to 160 objects in an image can be detected but to keep the illustrations clean not every object detection is shown. It detected relationships present in the ground truth along with the additional feasible relationships. Figure~\ref{fig:5} Top: in SGCls the predicted scene graph fully corresponds to the ground truth scene graph for this image. There is no additional relationship predicted between other objects. Looking at the scene graph for SGDet, the difference between these two protocols can be seen very well. Also, the performance of the model is really good in this case. Additionally to the ground truth objects, the object ''motorcycle'' and ''person'' are detected. These two detections are correct and feasible. While the only ground truth relation (woman - wearing - shirt) is still being detected, three other relationships that are totally feasible are detected (woman - on - motorcycle), (person - on - motorcycle) and (wheel - on - motorcycle). The performance of the BGT-Net on this image is outstanding. No problems or specialties in the SGDet can be found. In Figure~\ref{fig:5} Right: In SGDet, the model even fails to give the correct relationship (car - on - track). But, it correctly detects the whole train, which was not specified in the ground truth and the correct relationship (train - on - track). It is special in this case and it might also be in a lot of other images that the model detects many objects that were not shown in the ground truth. It also shows a lot of relationships between these additionally shown objects. But, most likely with a higher amount of detected objects in an image, these triplets, that are not in the ground truth, leads the model to miss some of the relationships that would also be found in the ground truth. \vspace{-3.5mm} \section{Conclusion} \vspace{-3mm} We proposed a novel method BGT-Net to address the main challenges in SGG. BGT-Net solves the problems by 1) using the object-object communication by employing Bi-directional GRUs; 2) using transformer encoder with scaled-dot-product attention for predicting object classes after they have received feature information from other objects; 3) getting edge feature from second transformer encoder; 4) Utilising Frequency Softening and Bias Adaptation for dealing the with bias in the SGG. We validated the effectiveness of the proposed BGT-Net using extensive experiments and conducting elaborative ablation studies using three open-source datasets. \enlargethispage{\baselineskip} {\small \bibliographystyle{ieee_fullname} \section{BGT-Net without Bi-directional GRU} BGT-Net (no BiGRU) is the BGT-Net with no BiGRU in it. We experimented with it to see how Bi-directional GRU effects the performance of the network. The performance of the BGT-Net (no BiGRU) for PredCls is lower than the other models. Even when compared to the MOTIFS, a performance decrease can be seen. In SGCls, there is slight improvements compared to the other models. Most important factor is that the performance increase compared to MOTIFS (baseline) is seen. Therefore, the effectiveness of the BGT-Net (no BiGRU) is shown in Table 5 in paper. In SGDet protocol, the BGT-Net (no BiGRU) can show an impressive performance. It outperforms every other model. The performance difference is also quite significant. The Recall@K is improved by over 1 point and reaches up to an increase of more than 3 points over the next best model. The results in mean Recall@K are worse than others. The short-comings of this BGT-Net (no BiGRU) is removed and improved by changing the model structure to BGT-Net by adding a Bi-GRU. \section{Ablation Study} As mentioned in the paper, we performed ablation study on several factors. We provide additional results on those experiments. They are discussed below: \subsection{Different Combination of Modules} \label{subsubsec:model_building_blocks} Figure \ref{fig:abls1}, Figure \ref{fig:abls2}, Figure \ref{fig:abls3}, and Figure \ref{fig:abls4} illustrate the graphical representation of the performance achieved using different modules by evaluating them on different performance recall metric. \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/AblS1.png} \caption[Recall Results]{Graphical representation of Recall Results for SGDet (left), SGCls (middle), PredCls (right) comparing the effects of different modules of the BGT-Net made during ablation studies on the effectiveness of different modules.} \label{fig:abls1} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/AblS2.png} \caption[No Graph Constraint Recall Results]{Graphical representation of no graph constraint Recall Results for SGDet (left), SGCls (middle), PredCls (right) comparing the effects of different modules of the BGT-Net made during ablation studies on the effectiveness of different modules.} \label{fig:abls2} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/AblS3.png} \caption[Zero Shot Recall Results]{Graphical representation of zero shot Recall Results for SGDet (left), SGCls (middle), PredCls (right) comparing the effects of different modules of the BGT-Net made during ablation studies on the effectiveness of different modules.} \label{fig:abls3} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/AblS4.png} \caption[Mean Recall Results]{Graphical representation of mean Recall Results for SGDet (left), SGCls (middle), PredCls (right) comparing the effects of different modules of the BGT-Net made during ablation studies on the effectiveness of different modules.} \label{fig:abls4} \end{figure*} \subsection{Number of Transformer Heads} Figure \ref{fig:abls-th1}, Figure \ref{fig:abls-th2}, Figure \ref{fig:abls-th3}, and Figure \ref{fig:abls-th4} show the graphical representation of the performance achieved by using different number of transformer heads and by varying the performance recall metric. \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-th1.png} \caption[Recall Results]{Graphical representation of Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluating the performance changes evoked by changing the number of Transformer heads of Transformer Encoders for object and edge information.} \label{fig:abls-th1} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-th2.png} \caption[No Graph Constraint Recall Results]{Graphical representation of no graph constraint Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluating the performance changes evoked by changing the number of Transformer heads of Transformer Encoders for object and edge information.} \label{fig:abls-th2} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-th3.png} \caption[Zero Shot Recall Results]{Graphical representation of zero shot Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluating the performance change evoked by changing the number of Transformer heads of Transformer Encoders for object and edge information.} \label{fig:abls-th3} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-th4.png} \caption[Mean Recall Results]{Graphical representation of mean Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluating the performance change evoked by changing the number of Transformer heads of Transformer Encoders for object and edge information.} \label{fig:abls-th4} \end{figure*} \subsection{Number of Bidirectional GRU Layers} Figure \ref{fig:abls-gru1}, Figure \ref{fig:abls-gru2}, Figure \ref{fig:abls-gru3}, and Figure \ref{fig:abls-gru4} show the graphical representation of the performance achieved by using different number of BiGRU layers and by varying the performance recall metric. \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-gru1.png} \caption[Recall Results]{Graphical representation of Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluation of performance change influenced by using 1, 2 or 6 layers of bidirectional GRUs in the BGT-Net model.} \label{fig:abls-gru1} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-gru2.png} \caption[No Graph Constraint Recall Results]{Graphical representation of no graph constraint Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluation of performance change influenced by using 1, 2, or 6 layers of bidirectional GRUs in the BGT-Net model.} \label{fig:abls-gru2} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-gru3.png} \caption[Zero Shot Recall Results]{Graphical representation of zero shot Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluation of performance change influenced by using 1, 2, or 6 layers of bidirectional GRUs in the BGT-Net model.} \label{fig:abls-gru3} \end{figure*} \begin{figure*}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/abl-gru4.png} \caption[Mean Recall Results]{Graphical representation of mean Recall Results for SGDet (left), SGCls (middle), PredCls (right). Evaluation of performance change influenced by using 1, 2, or 6 layers of bidirectional GRUs in the BGT-Net model.} \label{fig:abls-gru4} \end{figure*} \section{Hyper-parameter Study} The influence of the most important hyper-parameters on the model performance were tested. Batch size, learning rate, and number of solver iterations were varied for multiple experiments. PredCls was the main protocol on which the performance was compared. One hyper-parameter at a time was varied to understand its influence. The effect of changing parameters and therefore showing which parameter set performs the best can be seen below. \textbf{Leraning Rate.} Batch size was fixed at 24 and number of solver iterations at 24000. Learning rates 0.0001, 0.0005, 0.001 and 0.002 were tested. As \figref{fig:gru_tf-hyp1}, shows the best performance learning rate when evaluated using Recall@K. Evaluating on no graph constraint Recall@K illustrates no significant difference by the influence of learning rate. Similarly, in \figref{fig:gru_tf-hyp2}, the influence of the learning rate for evaluation on zero shot and mean Recall@K can not clearly be seen. Performance of learning rates 0.002, 0.001 and 0.00005 are almost the same. But learning rate 0.002 seems to have a slight edge on the other two. But this difference is marginal. Only the smallest learning rate 0.0001 seems to be under-performing. \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp1.png} \caption[PredCls Results for different Learning Rates 1]{Recall@K (left) and no graph constraint Recall@K (right) for Predicate Classification using different learning rates} \label{fig:gru_tf-hyp1} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp2.png} \caption[PredCls Results for different Learning Rates 2]{Zero shot Recall@K (left) and mean Recall@K (right) for Predicate Classification using different learning rates} \label{fig:gru_tf-hyp2} \end{figure} \newpage \textbf{Batch Size.} The non-changed hyper-parameters are set to 0.002 for the learning rate and 24000 to solver iterations. The examined batch sizes are 6, 12, 18 and 24. Only the smallest batch size 6 shows the lower performance in Recall@K as it can be seen in \figref{fig:gru_tf-hyp3}. This difference disappears for the no graph constraint Recall@K (visible in \figref{fig:gru_tf-hyp3} on the right) and for the zero shot Recall@K (shown in \figref{fig:gru_tf-hyp4} on the left). Significant and most evident difference in performance can be seen in the mean Recall@K in \figref{fig:gru_tf-hyp4}. Clearly, the largest batch size is performing better in this metric. Also in the other metrics, batch size 24 has the highest values. \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp3.png} \caption[PredCls Results for different Batch Sizes 1]{Recall@K (left) and no graph constraint Recall@K (right) for Predicate Classification using different batch sizes} \label{fig:gru_tf-hyp3} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp4.png} \caption[PredCls Results for different Batch Sizes 2]{Zero shot Recall@K (left) and mean Recall@K (right) for Predicate Classification using different batch sizes} \label{fig:gru_tf-hyp4} \end{figure} \newpage \textbf{Solver Iterations.} Keeping the learning rate at 0.002 and the batch size at 24, while changing the solver iterations to 6000, 12000, 18000 and 24000 shows the following influence of the solver iterations on the model performance. Throughout all the results in \figref{fig:gru_tf-hyp5} and \figref{fig:gru_tf-hyp6}, 6000 solver iterations under-perform significantly. Having only 6000 iterations does not allow the model to converge. As before with batch size, the difference in performance while changing the solver iterations is really small. Only for mean Recall@K the highest solver iteration does improve the results by almost 1 point. \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp5.png} \caption[PredCls Results for different Solver Iterations 1]{Recall@K (left) and no graph constraint Recall@K (right) for Predicate Classification compared to different solver iterations} \label{fig:gru_tf-hyp5} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures_supp/GRU-TF-hyp6.png} \caption[PredCls Results for different Solver Iterations 2]{Zero shot Recall@K (left) and mean Recall@K (right) for Predicate Classification compared to different solver iterations} \label{fig:gru_tf-hyp6} \end{figure} After these results, the best performing set of hyper-parameters can be found. Combining the results for batch size, learning rate and solver iterations leads to the choice of a learning rate of 0.002 a batch size of 24 and a solver iteration of 24000. Possibly, the least important of these would be the solver iterations since only the smallest difference going from 18000 to 24000 was detected. \section{Qualitative Results: BGT-Net} \begin{figure*}[!htb] \centering \includegraphics[width=1\linewidth]{./figures_supp/Picture-2col.pdf} \vspace{-0.15cm} \caption{Qualitative results of BGT-Model generated scene graphs. Two protocols are shown. left: Scene Graph Detection (SGDet), right: Scene Graph Classification (SGCls). BGT-Net is qualitatively compared to the MOTIFS model \cite{zellers2018neural}. Three colours are used to specify properties of detections. `Green' show detections that also perfectly correspond with ground-truth. `Red' is used for wrong detections and `orange' for detections not available in ground-truth but when checking with visual scene still represent the situation correctly.} \vspace{-3mm} \label{fig:qual_res} \end{figure*} The qualitative results in Figure \ref{fig:qual_res} show generated scene graphs on images of the Visaul Genome dataset. The examples are compared to the scene graphs generated by the MOTIFS model \cite{zellers2018neural}. For illustration purpose, the objects and relationships are coloured to represent properties of these detection. Object or relationship coloured ”green” are detected properly and correspond to the ground-truth. `Red' shows wrongly detected entities. For objects this can be either due to incorrect class prediction or due to not detection of the object during detection step with the Faster R-CNN. `Orange' denotes detections which do not correspond with the ground-truth annotations but can be validated by human inspection which means that the prediction generally corresponds with the visual scene. In Figure \ref{fig:qual_res}, the scene graphs generated with the Scene Graph Detection (SGDet) protocol are shown on the left and the ones generated with the Scene Graph Classification (SGCls) protocol are shown on the right. In SGDet, in many images, a large amount of objects are being detected. To increase readability, the object connected to the ground-truth objects are additionally inserted into the scene graph (with the colour `orange'). In many images, lots of $<$ subject- object-relationship$>$ triplets get correctly predicted but these cannot be found in the ground-truth triplets. This can effect the the performance of the model since these maybe correctly detected but not annotated in ground-truth and influence the prediction of other relationships. Both of the compared models in Figure \ref{fig:qual_res}, show errors in their predictions. But while detecting an object wrongly happens quite rarely, the relationship prediction is still much more prone to errors. This can be just the problem of the model but it is much more likely that many of the predictions made are not essentially wrong. This can be illustrated with the example of the object pair `person' and `pants'. Most often a person `wears' their pants. Relationships like `has', `in' and `on' do not contradict the reality. Added difficulty lays in the fact that throughout the dataset, these mentioned relationships do recently also appear. But there cannot be an evidence in the image what the relationship in this case can be because the difference between $<$person-pants-wears$>$ and $<$person-pants-has$>$ will not be visible in the image. This leads to worse model performance directly induced by the characteristics of the dataset. As shown in \ref{fig:qual_res}, errors in object prediction in SGCls do not happen very often. This may be the result of the highly improved performance of the BGT-Net in this protocol when measured in all evaluated metrics. Compared to the other protocols, the gained performance in SGCls is proportionally higher. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2021-09-14T02:15:56', 'yymm': '2109', 'arxiv_id': '2109.05346', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05346'}
arxiv
\section{Introduction} \input{sec1_intro} \section{Related Prior Work} \label{sec2_related} \input{sec2_related} \section{Background and Problem Setup} \label{sec3_problem} \input{sec3_problem} \section{Understanding the Impact of Stochastic Noise} \label{sec4_stochastic} \input{sec4_stochastic} \section{ReSNA: Hardware-Aware Training Approach} \label{sec5_training} \input{sec5_training} \section{CF-MESMO: Efficient MOO Algorithm} \label{sec6_moo} \input{sec6_moo} \section{Experiments and Results} \label{sec7_experiment} \input{sec7_1_setup} \input{sec7_2_result} \section{Conclusions} \input{sec8_conclusion} \label{sec8_conclusion} \footnotesize \bibliographystyle{ieeetr} \subsection{DNN Inferencing on ReRAM Crossbars} Fig.~\ref{fig:map} illustrates the overall flow of deploying a trained DNN model on ReRAM crossbars for inferencing. There are four main steps, as explained below. Table~\ref{table:parameter} summarizes the notation associated with the relevant parameters. \begin{figure}[t] \vspace{-12pt} \centering \includegraphics[width= 0.97\linewidth]{fig/fig_map.png} \vspace{-6pt} \caption{DNN inferencing process on ReRAM crossbars.} \label{fig:map} \end{figure} \begin{table}[t] \centering \vspace{-6pt} \caption{Parameters for inferencing on ReRAM crossbars.} \label{table:parameter} \vspace{-3pt} \footnotesize \begin{tabular}{|c||c|} \hline {\bf Notation} & {\bf Meaning} \\ \hline $W$ & DNN weight matrix \\ $A$ & Activations \\ \hline $Bit_{quan}$ & Bit number for quantization \\ $R_{on},R_{off}$ & Low resistance and high resistance \\ $Res_{cell}$ & ReRAM cell resolution \\ $Res_{DAC},Res_{ADC}$ & DAC and ADC resolution \\ $V_{r}$ & ReRAM read voltage \\ $T$ & Temperature \\ $Freq$ & Operational frequency \\ $\sigma_{prog}$ & Programming noise standard deviation \\ $Xbar_{size}$ & Crossbar size \\ \hline \end{tabular} \vspace{-12pt} \end{table} \noindent\ding{172}~\textit{Software training.} For a given DNN architecture and training dataset, we first perform the training in software. The quantization-aware training technique~\cite{han2015deep_compression,zhou2016dorefa,yang2021bsq} can be used to quantize the activations and weights. \vspace{0.25ex} \noindent\ding{173}~\textit{Deterministic mapping.} The objective of this step is to map the weight matrix of DNN $W$ and the set of activations $A$ to the conductance of the ReRAM cells $G_{quan}$ and crossbar input voltages $V_{quan}$, according to the resolutions of ReRAM devices and DACs, respectively. When the ReRAM cell resolution is less than the number of bits used in quantization, i.e., $Res_{cell} < Bit_{quan}$, $\lceil{Bit_{quan}}/{Res_{cell}} \rceil$ cells are used to represent one weight. A kernel in a convolutional (Conv) layer needs to be first unrolled and mapped to a matrix. As kernels are reused many times during convolution, the kernel in a Conv layer is typically duplicated and deployed on multiple crossbars. Therefore, multiple inputs can be processed simultaneously, increasing parallelism and improving throughput~\cite{song2017pipelayer}. For a fully-connected (FC) layer, each weight is associated with only one input neuron. Hence, duplication is not necessary. \vspace{0.25ex} \noindent\ding{174}~\textit{Stochastic noise injection.} This step mimics the influence of stochastic noise on the conductance values. The noise is modeled using probability distributions~\cite{feinberg2018making,he2019noise}. Here $G_{noisy}$ denotes the cell conductance in the presence of thermal noise, shot noise, RTN, and programming noise together. Section~\ref{sec:noise} provides more details. \vspace{0.25ex} \noindent\ding{175}~\textit{ReRAM-based computation.} This process accumulates the results obtained from ReRAM crossbars and employs ADCs to generate outputs. Here $Y_{noisy}$ denotes the final output of DNN inferencing. \vspace{0.25ex} \noindent Note that the last three steps together emulate the deployment of DNN inferencing on ReRAM-based hardware. The deterministic mapping needs to be carried out only once. Typically, we need to perform the third and fourth steps multiple times (e.g., ten times) to mimic multiple independent ReRAM deployments on the same device. Based on the multiple runs, we obtain an estimate of DNN inferencing accuracy. \subsection{MOO problem for ReRAM-based Designs} Our goal is to find ReRAM-based designs with suitable DNN weights to optimize multiple objectives, including inferencing accuracy, hardware area, execution time, and energy consumption. \noindent {\bf ReRAM design space.} The ReRAM design configuration influences the output objectives. For example, the parameters $Bit_{quan}$,~$Res_{DAC}$,~$Res_{ADC}$ listed in Table~\ref{table:parameter} influence the data precision and overall inferencing accuracy. For area overhead, $\lceil{Bit_{quan}}/{Res_{cell}} \rceil$ is proportional to the number of cells used in the ReRAM-based design to represent the weights, and $Xbar_{size}$ determines the subarray unit size. For execution time, note that $Freq$ is inversely proportional to the clock cycle. The read voltage $V_r$ and the ReRAM cell resistance range~[$R_{on}$,$R_{off}$] affect the ReRAM crossbar energy consumption. \noindent {\bf MOO formulation.} We formulate the MOO problem for robust inferencing on hardware-efficient ReRAM crossbars with stochastic noise as follows. Our input space consists of two parts: the ReRAM design space and the DNN weights. Let $\mathcal{X}\subseteq \mathcal{R}^{d}$ be the ReRAM design configuration space, which includes the design variables as explained above and also shown in Fig.~\ref{fig:map}. Each design variable can take values from a bounded candidate set. We need a candidate pair consisting of ReRAM design configuration($\mathbf{x} \in \mathcal{X}$) and DNN weights to be able to evaluate all the output objectives. Without loss of generality, we consider maximizing four objective functions: DNN inferencing accuracy, hardware area, execution time, and energy consumption denoted by $f_1(\mathbf{x}), f_2(\mathbf{x}), f_3(\mathbf{x}), f_4(\mathbf{x})$, respectively. For each candidate ReRAM design, we execute ReSNA to obtain the DNN weights that give rise to maximum accuracy. Subsequently, we evaluate the objective functions $f_{1}(\mathbf{x})$, $f_{2}(\mathbf{x})$, $f_{3}(\mathbf{x})$, $f_{4}(\mathbf{x})$. A design configuration $\mathbf{x}$ is determined to \textit{Pareto dominate} another design $\mathbf{x'}$ if $f_{i}(\mathbf{x}) \geq f_{i}(\mathbf{x'})\ \forall i$ and there exists some $j \in \{1,2,3,4\}$ such that $f_{j}(\mathbf{x}) > f_{j}(\mathbf{x'})$. An optimal solution of a MOO problem is a set of designs $\mathcal{X}^*$ such that no design $\mathbf{x'}\in \mathcal{X}\setminus \mathcal{X}^*$ pareto-dominates a design $\mathbf{x}\in \mathcal{X}^*$. The solution set $\mathcal{X}^*$ is called the \textit{Pareto set}, and the corresponding set of objective function values is called the \textit{Pareto front}. Our goal is to achieve a high-quality Pareto front for hardware design while minimizing the total computation cost of function evaluations. \subsection{Modeling of ReRAM Stochastic Noise} \label{sec:noise} {\em Thermal noise} is generated due to the thermal agitation of the charged carriers inside the conductor~\cite{johnson1928thermal}. {\em Shot noise} is an electronic noise that originates from the discrete electrons in the current flow. The thermal and shot noise directly affect the current through a device. We convert the change in current to the equivalent conductance change and model these two noise sources using Gaussian distributions~\cite{feinberg2018making}: $\Delta G_{thermal}=\mathcal{N}(0, {\sqrt{4G\cdot Freq\cdot K_B\cdot T}}/{V})$ and $\Delta G_{shot}=\mathcal{N}(0, {\sqrt{2G\cdot Freq\cdot q\cdot V}}/{V})$, where $G$ and $V$ denote the conductance and terminal voltage respectively. As shown in Table~\ref{table:parameter}, $Freq$ denotes the operational frequency, and $T$ denotes the temperature. $K_B$ denotes the Boltzmann constant, and $q$ denotes the electron charge. {\em Random telegraph noise (RTN)} is generated in semiconductors and ultra-thin oxide films. It can be modeled as a Poisson process~\cite{ielmini2010resistance}, with the parameters for RTN amplitude~($\Delta G_{rtn}$) reported in~\cite{he2019noise}. {\em Programming noise} is introduced by the programming variation when values are written to a ReRAM device. The programming noise can be estimated using a Gaussian distribution with $\Delta G_{prog}=\mathcal{N}(0, \sigma_{prog}G)$ with standard deviation $\sigma_{prog}=0.0658$, according to the experimental study reported in~\cite{lin2019performance}. \subsection{Impact of ReRAM Stochastic Noise} \begin{figure}[t] \centering \vspace{-6pt} \includegraphics[width=0.95\linewidth]{fig/fig_noise_combine.png} \vspace{-6pt} \caption{The distributions of stochastic noise for 8-bit ReRAM cells under $Freq=500\,\mathrm{MHz}$ and $T=350\,\mathrm{K}$: (a) in a relative scale, (b) with absolute values, (c) zoomed-in version for relative noise, (d) an example of nonzero weight distribution.} \label{fig:noise} \vspace{-18pt} \end{figure} Fig.~\ref{fig:noise} (a)-(b) show the relative and absolute distributions of four kinds of stochastic noise for 8-bit ReRAM cells with $Freq= 500\,\mathrm{MHz}$ and $T=350\, \mathrm{K}$. Besides, Fig.~\ref{fig:noise}(c) presents the relative noise for the first 16 levels among the 256 conductance levels. Relative noise ($\Delta G/G$) measures the noise amplitude divided by the absolute conductance. Thermal and shot noise have similar patterns: the relative noise is the largest at the smallest conductance level; it then decreases steadily as $G$ increases. The relative RTN presents a sharp peak at the first conductance level, while other conductance levels have much smaller relative RTN. The programming noise increases with the conductance level in the absolute value. We observe from Fig.~\ref{fig:noise}(c) that the overall amplitude is much higher than each individual case, especially when $G$ is small. Moreover, it is well known that the trained weights of DNNs are concentrated at small values \cite{seo2019efficient}. Fig.~\ref{fig:noise}(d) shows an example distribution of nonzero weights, which is extracted from the $\mathrm{19^{th}}$ layer of ResNet20 with 8-bit quantization. A large number of the weights in this layer are zero; these are not included in the figure. Note that at small values of $G$, the first three types of stochastic noise dominate. Specifically, the thermal and shot noise are sensitive to the operational frequency. Hence, it is challenging to incorporate high-frequency noise into training. Lowering the operational frequency and reducing noise amplitude could be an option, as suggested in previous work~\cite{he2019noise}. However, such an approach will seriously constrain the use and potential of ReRAM-based hardware due to the exclusion of high operational frequency and short execution time for DNN inferencing. Utilizing high-resolution cells is another challenge. For example, increasing the cell resolution from 2 to 8 bits can reduce the number of crossbar arrays by $75\%$ (assuming all other settings are the same), leading to a smaller area and lower latency. However, the noise margin drops by $64\times$ as the cell noise margin is inversely proportional to the number of conductance levels~(i.e., $2^{Res_{cell}}$). \subsection{Performance of Existing Training Approaches} \begin{figure}[t] \vspace{-18pt} \includegraphics[width=0.9\linewidth]{fig/fig_compare.png} \vspace{-6pt} \caption{Results for DNN inferencing on ReRAM crossbars with stochastic noise under different training methods: Baseline, RGN, \textsc{Prog}, and ReSNA training. $Freq=500\,\mathrm{MHz}$, $T=350\,\mathrm{K}$, 128$\times$128 crossbars. (a) ResNet20, (b) VGG13.} \vspace{-18pt} \label{fig:compare} \end{figure} We next evaluate the DNN inferencing accuracy of several previously proposed ReRAM hardware-aware training methods with ResNet20 and VGG13 and show the results in Fig.~\ref{fig:compare}. Weights and activations are quantized to 8 bits. We consider two different ReRAM cell resolutions, 2 bits and 8 bits. Models are tested by including the stochastic noise in ReRAM-based hardware. The baseline configuration considers training with no noise. RGN denotes a na\"{\i}ve noise-aware approach, which injects random Gaussian noise into the system during training. The noise standard deviation is related to the maximum absolute weight value, more specifically, $\Delta G_{RGN}=\mathcal{N}(0,\,0.01\cdot \max(G))$. \textsc{Prog} considers only the programming noise $\Delta G_{prog}$ with $\sigma_{prog}=0.0658$~\cite{lin2019performance} for training. We make the following observations from the results shown in Fig.~\ref{fig:compare}. {\bf 1)} The baseline system suffers from stochastic noise, resulting in poor inferencing accuracy. {\bf 2)} Previous training methods, such as RGN and \textsc{Prog}, cannot guarantee the mitigation of DNN inferencing accuracy degradation due to stochastic noise. This result is mainly due to the mismatch between Gaussian noise and the actual device stochastic noise, as shown in Fig.~\ref{fig:noise}(a). {\bf 3)} Increasing the cell resolution from 2 to 8 bits exacerbates the degradation in DNN inferencing accuracy due to the reduced noise margin of the ReRAM devices. \subsection{MOO Formulation with Continuous-Fidelity Evaluations} For each candidate ReRAM design $x \in \mathcal{X}$, we need to execute the ReSNA method to obtain the DNN weights. Subsequently, we evaluate the objective functions $f_{1}(\mathbf{x})\,$(inferencing accuracy), $f_{2}(\mathbf{x})\,$(hardware area), $f_{3}(\mathbf{x})\,$(execution time), $f_{4}(\mathbf{x})\,$(energy consumption). The cost of evaluation of each ReRAM design configuration can be reduced by making an approximation of the objective function(s). We propose to vary the number of training epochs in ReSNA to trade-off computation cost and accuracy of objective function evaluations (i.e., continuous-fidelity evaluation): small training epochs correspond to lower-fidelity evaluation and vice versa. Therefore, we formulate this problem as a continuous-fidelity MOO problem where we have access to an alternative function $g_j(\vec{x},z_j)$ for all $j\in\{1,2,3,4\}$. Function $g_j(\vec{x},z_j)$ can make cheaper approximations of $f_j(\vec{x})$ by varying the fidelity variable $z_j \in \mathcal{Z}$. Without loss of generality, let $\mathcal{Z}=[0, 1]$ be the fidelity space. Fidelities for each function vary in the amount of computational resources consumed and the accuracy of evaluation, where $z_j=0$ and $z_j^*=1$ refer to the lowest and highest fidelity, respectively. At the highest fidelity $z_j^*$, $g_j(\vec{x},z_j^{*})=f_j(\vec{x})$. Let $\mathcal{C}_j(\vec{x},z_j)$ be the cost of evaluating $g_j(\vec{x},z_j)$, i.e., runtime to perform training using ReSNA for the selected number of training epochs. Evaluation of each ReRAM design configuration $\vec{x}\in \mathcal{X}$ with fidelity vector $\vec{z}=[z_1, z_2, z_3, z_4]$ generates the evaluation vector $\vec{y}\equiv [y_1, y_2, y_3, y_4]$, where $y_j = g_j(\vec{x},z_j)$, and the normalized cost of evaluation is $\mathcal{C}(\vec{x},\vec{z}) = \sum_{j=1}^{4} \left( {\mathcal{C}_j(\vec{x},z_j)}/{\mathcal{C}_j(\vec{x},z_j^*)}\right)$. Our goal is to approximate the Pareto set $\mathcal{X}^*$ by minimizing the overall cost of evaluating candidate ReRAM designs. \subsection{Overview of CF-MESMO} CF-MESMO learns a surrogate model using data obtained from past ReRAM design evaluations and then intelligently selects the next candidate ReRAM design and the fidelity of ReSNA pair for evaluation by trading-off exploration with exploitation to quickly direct the search towards Pareto-optimal solutions. We perform the following steps in each iteration of CF-MESMO as shown in Algorithm 1: {\bf 1)} Select the ReRAM design and fidelity of ReSNA for evaluation that maximizes the information gain per unit cost about the optimal Pareto front based on the current surrogate model. {\bf 2)} Execute the hardware-aware training approach ReSNA to evaluate objective functions with the selected ReRAM design and fidelity pair. {\bf 3)} Employ the new training example in the form of ReRAM design configurations (i.e., input) and four objective function evaluations (i.e., output) to update the surrogate model. After convergence is achieved (i.e., Pareto front solution doesn't change in several consecutive iterations), we compute the Pareto front from the aggregate set of objective evaluations and obtain the ReRAM design configurations and DNN weights corresponding to the Pareto front as the resulting solution. \vspace{-6pt} \begin{algorithm}[H] \centering \scriptsize \caption{CF-MESMO Algorithm} \textbf{Input}: ReRAM design space $\mathcal{X}$; DNN $\pi$; four objective functions $f_j$ and their continuous approximations $g_j$ using ReSNA training; total cost budget $\mathcal{C}_{total}$. \vspace{-2ex} \begin{algorithmic}[1] \STATE Initialize GP models $\mathcal{GP}_1, \cdots, \mathcal{GP}_4$ via ReRAM design evaluations $D$ \STATE \textbf{While} {$\mathcal{C}_{t} \leq \mathcal{C}_{total} $} \textbf{and} not converged \textbf{do} \STATE \quad for each sample $s \in {1,\cdots,S}$: \STATE \quad \quad Sample highest-fidelity functions $\Tilde{f}_j \sim \mathcal{GP}_j(.,z_j^*) $ \STATE \quad \quad $\mathcal{F}_s^{*} \leftarrow$ Solve {\em cheap} MOO over $(\Tilde{f}_1, \cdots, \Tilde{f}_K)$ \STATE \quad Select ReRAM design and fidelity pair: \\ \quad $(\vec{x}_{t},\vec{z}_t) \leftarrow \arg max_{\vec{x}\in \mathcal{X},\vec{z}\in \mathcal{Z}} \hspace{2 mm} \alpha_t(\vec{x},\vec{z},\mathcal{F}^{*})$ Equation (\ref{Tappriximation}) \STATE \quad Perform ReSNA training of DNN $\pi$ with ReRAM design and fidelity pair $(\vec{x}_{t},\vec{z}_t)$ \STATE \quad Evaluate objectives $f_1, f_2, f_3, f_4$ for trained DNN on ReRAM design $\vec{x}_{t}$ \STATE \quad Update the total cost: $\mathcal{C}_t \leftarrow \mathcal{C}_t + \mathcal{C}(\vec{x}_t,\vec{z}_t)$ \STATE \quad Aggregate training data: $\mathcal{D} \leftarrow \mathcal{D} \cup \{(\vec{x}_{t}, \vec{y}_{t},\vec{z}_t)\}$ \STATE \quad Update surrogate statistical models $\mathcal{GP}_1,\cdots, \mathcal{GP}_4$ \STATE \quad $t \leftarrow t+1$ \STATE \textbf{end} \STATE \textbf{return} Pareto set and Pareto front of objective functions $f_1(x), \cdots,f_4(x)$ \end{algorithmic} \label{alg:CFMESMO} \end{algorithm} \vspace{-12pt} \noindent {\bf Surrogate models for continuous-fidelity.} Surrogate models guide the selection of candidate ReRAM designs to quickly uncover high-quality Pareto fronts. Our training data $\mathcal{D}$ for surrogate models after $t$ iterations consists of $t$ training examples of input-output pairs. We employ Gaussian processes (GPs)~\cite{williams2006gaussian} as our choice of the statistical model due to their superior uncertainty quantification ability. We learn four surrogate statistical models $\mathcal{GP}_1,\cdots,\mathcal{GP}_4$ from $\mathcal{D}$, where each model $\mathcal{GP}_j$ corresponds to the $j$th function $g_j$. Continuous-fidelity GPs (CF-GPs) are capable of modeling functions with continuous fidelities within a single model. Hence, we employ CF-GPs to build surrogate statistical models for each function \cite{kandasamy2017multi}. A CF-GP is a random process defined over the input space and the fidelity space, characterized by a mean function $\mu: \mathcal{X} \times \mathcal{Z} \rightarrow \mathbb{R} $ and a covariance or kernel function $\kappa: (\mathcal{X} \times \mathcal{Z})^2 \rightarrow \mathbb{R} $. We denote the posterior mean and standard deviation of $g_j$ by $\mu_{g_j}(\vec{x},z_j)$ and $\sigma_{g_j}(\vec{x},z_j)$. We denote the posterior mean and standard deviation of the highest fidelity functions $f_j(\vec{x})=g_j(\vec{x},z_j^*)$ by $\mu_{f_j}(\vec{x})=\mu_{g_j}(\vec{x},z_j^*)$ and $\sigma_{f_j}(\vec{x})=\sigma_{g_j}(\vec{x},z_j^*)$, respectively. \subsection{Selecting ReRAM Design to Evaluate via Information Gain} The effectiveness of CF-MESMO critically depends on the reasoning mechanism to select the candidate ReRAM design and fidelity of ReSNA pair for evaluation in each iteration. Therefore, we propose an information-theoretic approach to perform this selection. {\em The key idea is to find the ReRAM design and fidelity pair $\{\vec{x}_t, \vec{z}_t\}$ that maximizes the information gain ($I$) per unit cost about the Pareto front of the highest fidelities} (denoted by $\mathcal{F}^*$), where $\{\vec{x}_t, \vec{z}_t\}$ represents a candidate ReRAM design configuration $\vec{x}_t$ evaluated at fidelities $\vec{z}_t$ at iteration $t$. CF-MESMO performs the joint search over the input space $\mathcal{X}$ and the fidelity space $\mathcal{Z}$: \begin{align} (\vec{x}_{t},\vec{z}_t) \leftarrow \argmax_{\vec{x}\in \mathcal{X},\vec{z}\in \mathcal{Z}}\hspace{2 mm}\alpha_t(\vec{x},\vec{z}), ~ \end{align} \begin{align} \text{where} \quad \alpha_t(\vec{x},\vec{z}) &= I(\{\vec{x}, \vec{y},\vec{z}\}, \mathcal{F}^* | \mathcal{D}) / \mathcal{C}(\vec{x},\vec{z}). \label{af:def} \end{align} In this joint search, the computation cost~$\mathcal{C}(\vec{x},\vec{z})$ is considered in Equation~(\ref{af:def}). The information gain in Equation (\ref{af:def}) is the expected reduction in entropy $H(.)$ of the posterior distribution $P(\mathcal{F}^* | \mathcal{D})$ due to the evaluation of the ReRAM design $\vec{x}$ at fidelity vector $\vec{z}$. According to the symmetric property, the information gain can be rewritten as follows: \begin{align} I(\{\vec{x}, \vec{y},\vec{z}\}, \mathcal{F}^{*} | \mathcal{D}) &= H(\vec{y} | \mathcal{D}, \vec{x},\vec{z}) - \mathbb{E}_{\mathcal{F}^{*}} [H(\vec{y} | \mathcal{D}, \vec{x},\vec{z}, \mathcal{F}^{*})]. \numberthis \label{eqn_symmetric_ig} \end{align} The first term in Equation (\ref{eqn_symmetric_ig}) is the entropy of a four-dimensional Gaussian distribution that can be computed as follows: \begin{align} H(\vec{y} | \mathcal{D}, \vec{x},\vec{z}) = \sum_{j = 1}^4 \ln (\sqrt{2\pi e} ~ \sigma_{g_j}(\vec{x},z_j)). \numberthis \label{firstpart} \end{align} The second term in Equation (\ref{eqn_symmetric_ig}) is an expectation over $\mathcal{F}^{*}$ and can be approximated using Monte-Carlo sampling: \begin{align} \mathbb{E}_{\mathcal{F}^{*}} [H(\vec{y} | \mathcal{D}, \vec{x},\vec{z}, \mathcal{F}^{*})] \simeq \frac{1}{S} \sum_{s = 1}^S [H(\vec{y} | \mathcal{D}, \vec{x},\vec{z}, \mathcal{F}^{*}_s)], \label{eqn_summation} \end{align} where $S$ denotes the number of samples, and $\mathcal{F}^{*}_s$ denotes a sample Pareto front achieved over the highest fidelity functions sampled from the surrogate models. To solve Equation (\ref{eqn_summation}), we provide solutions to construct Pareto front samples $\mathcal{F}^{*}_s$ and to compute the entropy of a given Pareto front sample $\mathcal{F}^{*}_s$. \vspace{0.25ex} \noindent {\bf Computation of Pareto front samples:} We sample the highest fidelity functions $\Tilde{f}_1,\cdots,\Tilde{f}_4$ from the posterior CF-GP models. Then, we solve a cheap MOO problem over the sampled functions with the NSGA-II algorithm \cite{deb2002fast} and compute the sample Pareto front $\mathcal{F}^{*}_s$. \vspace{0.25ex} \noindent {\bf Entropy computation for a given Pareto front sample:} Let $\mathcal{F}^{*}_s = \{\vec{v}^1, \cdots, \vec{v}^l \}$ be the sample Pareto front, where $l$ denotes the size of the Pareto front and each element $\vec{v}^i = \{v_1^i,\cdots,v_4^i\}$ is evaluated at the sampled highest-fidelity function. The following inequality holds for each component $y_j$ of $\vec{y}$ in the entropy term $H(\vec{y} | \mathcal{D}, \vec{x},\vec{z}, \mathcal{F}^{*}_s)$: \begin{align} y_j &\leq f_s^{j*} \quad \forall j \in \{1,\cdots,4\}, \label{inequality} \end{align} where $f_s^{j*} = \max \{v_j^1, \cdots v_j^l \}$. Essentially, this inequality means that the $j^{th}$ component of $\vec{y}$ is upper-bounded by the maximum of $j^{th}$ components of sample Pareto front $\mathcal{F}^{*}_s$. The proof of Equation (\ref{inequality}) falls in two cases\footnote{For ease of notation, we drop the dependency on $\vec{x}$ and $\vec{z}$. We use $f_j$ to denote $f_j(\vec{x})=g_j(\vec{x},z_j^*)$ the evaluation of the highest fidelity $z_j^*$ and $y_j$ to denote $g_j(\vec{x},z_j)$ the evaluation of $g_j$ at a lower fidelity $z_j \neq z_j^*$.}: {\bf a)} If $y_j$ is evaluated at the highest fidelity (i.e, $z_j=z_j^*$ and $y_j=f_j$), we prove by contradiction. Suppose there exists some component $f_j$ of $\vec{f}$ such that $f_j > f_s^{j*}$. However, by definition, since no point dominates $\vec{f}$ in the $j$th dimension, $\vec{f}$ is a non-dominated point. This results in $\vec{f} \in \mathcal{F}^*_s$, which is a contradiction. Thus, Equation (\ref{inequality}) holds. {\bf b)} If $y_j$ is evaluated at one of the lower fidelities (i.e, $z_j \neq z_j^*$), we refer to the assumption that the value of an objective evaluated at lower fidelity is smaller than that evaluated at higher fidelity, i.e., $y_j \leq f_j \leq f_s^{j*}$. This assumption is true in our problem setting, where the DNN inferencing accuracy improves with more training epochs of ReSNA. Following Equation (\ref{inequality}) and the independence of CF-GP models, we further decompose the entropy of a set of independent variables according to the entropy measure property~\cite{information_theory}: \begin{align} H(\vec{y} | \mathcal{D}, \vec{x},\vec{z}, \mathcal{F}^{*}_s) \simeq \sum_{j=1}^4 H(y_j|\mathcal{D}, \vec{x},z_j,f_s^{j*}). \label{eqn_sep_ineq} \end{align} Equation (\ref{eqn_sep_ineq}) requires the entropy computation of $p(y_j|\mathcal{D}, \vec{x},z_j,f_s^{j*})$. This conditional distribution can be expressed as $H(y_j|\mathcal{D}, \vec{x},z_j,y_j\leq f_s^{j*})$. As Equation (\ref{inequality}) states that $y_j\leq f_s^{j*}$ holds under all fidelities, the entropy of $p(y_j|\mathcal{D}, \vec{x},z_j,f_s^{j*})$ can be approximated by the entropy of a truncated Gaussian distribution as: \begin{align} H(y_j|\mathcal{D}, \vec{x},z_j,y_j\leq f_s^{j*})= & \ln(\sqrt{2\pi e} ~ \sigma_{g_j}) + \ln \Phi(\gamma_s^{(g_j)}) \nonumber \\ & - \frac{\gamma_s^{(g_j)} \phi(\gamma_s^{(g_j)})}{2\Phi(\gamma_s^{(g_j)})}, \numberthis \label{entropyapprox1} \end{align} where $\gamma_s^{(g_j)} = \frac{f_s^{j*} - \mu_{g_j}}{\sigma_{g_j}}$. Functions $\phi$ and $\Phi$ are the probability density and cumulative distribution function of the standard normal distribution, respectively. From Equations (\ref{firstpart}), (\ref{eqn_summation}), and (\ref{entropyapprox1}), we get the expression as shown below: \begin{align} \alpha_t(\vec{x},\vec{z},\mathcal{F}^{*})=&\frac{1}{\mathcal{C}(\vec{x},\vec{z}) S}\sum_{j=1}^4 \sum_{s=1}^S \frac{\gamma_s^{(g_j)}\phi(\gamma_s^{(g_j)})}{2\Phi(\gamma_s^{(g_j)})} - \ln(\Phi(\gamma_s^{(g_j)})). \numberthis \label{Tappriximation} \end{align} Therefore, in Algorithm~\ref{alg:CFMESMO}, we select the next ReRAM design and the fidelity of ReSNA pair that maximizes the information gain per unit cost about the optimal Pareto front based on Equation~(\ref{Tappriximation}). \subsection{Experimental Setup} \label{sec7_1:experiments} \begin{table}[!b] \vspace{-12pt} \caption{Experiments setup details.} \label{table:configuration} \vspace{-4pt} \footnotesize \centering (a) Network configurations.\\ \vspace{2pt} \begin{tabular}{|c|c|c|c|} \hline Network & \# of channels in Conv layers & \begin{tabular}[c]{@{}c@{}}Unquantized \\Accuracy \end{tabular} &\begin{tabular}[c]{@{}c@{}}Quantized \\Accuracy \end{tabular} \\ \hline ResNet20 &\begin{tabular}[c]{@{}c@{}}16, {[}16,16{]}$\times$3, {[}32, 32{]}$\times$3,\\ {[}64, 64{]}$\times$3 \end{tabular} & 91.65\% &89.61\% \\ ResNet32 &\begin{tabular}[c]{@{}c@{}}16, {[}16,16{]}$\times$5, {[}32, 32{]}$\times$5,\\ {[}64, 64{]}$\times$5 \end{tabular} & 92.81\%& 90.06\% \\ ResNet44 & \begin{tabular}[c]{@{}c@{}}16, {[}16,16{]}$\times$7, {[}32, 32{]}$\times$7,\\ {[}64, 64{]}$\times$7 \end{tabular} & 93.24\% &91.54\% \\ VGG11& \begin{tabular}[c]{@{}c@{}}64, 128, 256, 256, 512, 512, \\512, 512 \end{tabular} & 92.18\% &88.07\% \\ VGG13 & \begin{tabular}[c]{@{}c@{}}64, 64, 128, 128, 256, 256,\\ 512, 512, 512, 512\end{tabular} & 93.64\% & 91.14\% \\ \hline \begin{tabular}[c]{@{}c@{}}{ResNet18}\\{\tiny for CIFAR-100}\end{tabular} & \begin{tabular}[c]{@{}c@{}}64, {[}64, 64{]}$\times$2, {[}128,128{]}$\times$2,\\ {[}256,256{]}$\times$2, {[}512,512{]}$\times$2 \end{tabular} &74.57\% & 71.92\%\\ \hline \end{tabular} \label{table:network} \vspace{2pt} (b) ReRAM parameters in ReSNA.\\ \vspace{2pt} \begin{tabular}{|c||c|} \hline Parameter & Value \\ \hline $Bit_{quan}$ & $8$ bit \\ $R_{on},R_{off}$ & $3.03\,\mathrm{k\Omega}$, $3.03\,\mathrm{M\Omega}$ \\ $Res_{DAC},Res_{ADC}$ & $8$ bits, $8$ bits \\ $V_{r}$ & $\mathrm{1.65V}$ \\ $\sigma_{prog}$ & $0.0658$ \\ \hline \end{tabular} \vspace{2pt}\\ (c) Design space configurations.\\ \vspace{2pt} \begin{tabular}{|c||c|} \hline Parameter & Candidate values \\ \hline $Res_{cell}$ & $8/4/3/2/1$-bit \\ $Freq$ & $10\,\mathrm{MHz}$-$1000\,\mathrm{MHz}$ \\ $T$ & $300\,\mathrm{K}$-$400\,\mathrm{K}$ \\ $Xbar_{size}$ & $32\times32$, $64\times64$, $128\times128$ \\ \hline \end{tabular} \end{table} We evaluate ReSNA with five different DNNs---ResNet20, ResNet32, ResNet44~\cite{he2016deep}, VGG11, and VGG13~\cite{simonyan2014very} on the CIFAR-10 dataset~\cite{krizhevsky2009learning}. The CIFAR-10 dataset contains $50,000$ training images and $10,000$ testing images, which belong to $10$ classes. Furthermore, to validate the scalability of our method, we also evaluate the performance of ResNet18~\cite{he2016deep} using the CIFAR-100 dataset~\cite{krizhevsky2009learning}. The number of training and testing images in CIFAR-100 is the same as in CIFAR-10, but these images belong to $100$ classes. The image size is $28\times28\times3$, and the training and testing batch size is $64$. Table~\ref{table:configuration}(a) summarizes deep neural network configurations, including the numbers of channels in Conv layers, the inferencing accuracy with unquantized weights and activations, and the inferencing accuracy for 8-bit weights and activations. Note that testing on diverse DNNs is more important to test the effectiveness of our approach. Hence, due to space constraints, we provide results on limited datasets noting that our methodology and findings are general. We implement the ReSNA method on ReRAM crossbars with stochastic noise using the PytorX simulator~\cite{he2019noise}. ReSNA uses stochastic gradient descent with a learning rate of $0.001$ and a momentum of $0.9$. The maximum number of training epochs is $100$. For ResNet18, we decay the learning rate by $0.2$ for every 20 epochs. Each inferencing test consists of $10$ independent runs with stochastic noise, and we report the average inferencing accuracy. All the training and inferencing are conducted on NVIDIA Titan RTX GPU with a memory of $24\,\mathrm{GB}$ and a memory bandwidth of $672\,\mathrm{GB/s}$. Table~\ref{table:configuration}(b) summarizes the ReRAM device parameters. The cell resolution, operational frequency, temperature, and crossbar size are inputs to the MOO framework. Table~\ref{table:configuration}(c) shows the allowable input configurations. We use NeruoSim~\cite{peng2019dnn+} along with the $32\,\mathrm{nm}$ technology node parameters to evaluate the hardware area, execution time, and energy consumption. The ReRAM crossbar and peripheral configurations are adopted from~\cite{peng2019optimizing}. For ReSNA with Voting, we duplicate the kernels of the classification layer. For the MOO problem, we run CF-MESMO for a maximum of $100$ iterations with $10$ available fidelity selections. The baselines for evaluating the efficiency of CF-MESMO are the random search and NSGA-II. We utilize the NSGA-II implementation from \textit{Platypus} python library. \subsection{ReSNA Results} \begin{figure}[t] \vspace{-12pt} \centering \includegraphics[width=\linewidth]{fig/fig_resna_acc.png} \vspace{-12pt} \caption{ReRAM inferencing accuracy under various temperature and frequency settings. 8-bit cell resolution, 64$\times$64 crossbars. ResNet20 on the CIFAR-10 dataset.} \vspace{-18pt} \label{fig:resna_acc} \end{figure} \noindent{\bf Inferencing accuracy.} We show representative results for ReSNA inferencing accuracy with multiple temperature and frequency settings with respect to the baseline. Recall that the baseline configuration considers training with no noise and performs inferencing in the presence of stochastic noise. Fig.~\ref{fig:resna_acc}(a)-(c) show the inferencing accuracy for ResNet20 with 8-bit cell resolution and 64$\times$64 crossbars. On average, ReSNA without Voting outperforms the baseline by 1.62$\%$ over all the test conditions. ReSNA with Voting increases the overall inferencing accuracy by 2.57$\%$. Considering the extreme design configuration, i.e., at 1000$\,\mathrm{MHz}$ and 400$\,\mathrm{K}$, ReSNA with Voting outperforms the baseline by 5.47$\%$. Note that this extreme case assumes that in the future, ReRAM-based hardware will run at this high frequency. We also validate the performance of the ReSNA method with the ResNet18 on the CIFAR-100. With a frequency of 500$\,\mathrm{MHz}$ and a temperature of 350$\,\mathrm{K}$, ReSNA achieves $70.80\%$ inferencing accuracy compared with the baseline inferencing accuracy of $69.37\%$. With a frequency of 1000$\,\mathrm{MHz}$ and a temperature of 350$\,\mathrm{K}$, ReSNA achieves $68.23\%$ inferencing accuracy compared with the baseline inferencing accuracy of $64.45\%$. In summary, ReSNA can achieve considerable inferencing accuracy improvement under stochastic noise with different ReRAM design configurations, DNNs, and datasets. \noindent{\bf Design trade-offs considering different objectives.} \label{sec7_2_result_acc} \begin{figure}[t] \vspace{-12pt} \centering \includegraphics[width=0.88\linewidth]{fig/fig_resna_tradeoff.png} \vspace{-6pt} \caption{ReRAM-based design trade-offs under different cell resolution and crossbar size settings. ResNet20, $Freq=500\,\mathrm{MHz}$, $T=350\,\mathrm{K}$. (a) inferencing accuracy, (b) hardware area, (c) latency, (d) energy consumption.} \vspace{-18pt} \label{fig:resna_tradeoff} \end{figure} We further explore the design trade-offs considering the inferencing accuracy, hardware area, execution time, and energy consumption. As we have explored the effects of frequency and temperature on inferencing accuracy in the previous analysis, we focus on cell resolution and crossbar size in this discussion. Fig.~\ref{fig:resna_tradeoff} shows the impact of cell resolution and the crossbar size on ResNet20 at 500$\,\mathrm{MHz}$ and 350$\,\mathrm{K}$. Fig.~\ref{fig:resna_tradeoff}(a) shows that inferencing accuracy using the ReSNA method. When other settings remain the same, the inferencing accuracy steadily increases as the cell resolution reduces due to the improved noise margin. As discussed in Section~\ref{sec3_problem}, the ReRAM crossbar array outputs are accumulated across the columns, and hence the crossbar size affects the noise accumulation. Therefore, a large crossbar with high cell resolution is not an optimal design choice with this setting from the inferencing accuracy perspective. From the area perspective, the 32$\times$32 crossbar with 8-bit cell resolution is the best, while 64$\times$64 crossbar has the least area when the cell resolution is 4-bit. The area evaluation reveals a high correlation between the cell resolution and crossbar size. Fig.~\ref{fig:resna_tradeoff}(c) shows that the minimum latency is achieved by the 64$\times$64 crossbar with the cell resolution of 2-bit, though this particular configuration incurs a relatively larger area overhead than the configuration with 4-bit cell resolution. Fig.~\ref{fig:resna_tradeoff}(d) shows that the energy consumption with large cell resolution and small crossbar size is relatively modest. \subsection{Results on Using CF-MESMO to Optimize ReRAM Crossbars} Fig.~\ref{fig:resna_tradeoff} also indicates that different objectives have different optimal design configurations, and a global optimal design configuration is not achievable. Note that the operational frequency and temperature considered above are discrete data points selected for initial performance evaluation. However, the temperature can take any value from $300\,\mathrm{K}$ to $400\,\mathrm{K}$. Assuming the temperature resolution to be $0.1\,\mathrm{K}$, we can get $1,000$ data points. Similarly, by considering other inputs, we can estimate the number of all design configurations to be $1.485\times 10^7$. While any MOO framework can search over this enormous space to achieve the Pareto front to establish the suitable design trade-offs, the computation cost associated with this search is prohibitively high (e.g., it takes nearly $30$ GPU days to run the ReSNA training on the PytorX simulator~\cite{he2019noise} for 100 configurations). In contrast, the proposed CF-MESMO framework does not traverse through all the data points but can achieve a high-quality Pareto front with significantly reduced computation cost. We use the hypervolume, which measures the volume between the Pareto front and a reference point~\cite{zitzler1999multiobjective}, to indicate the quality of the Pareto front. \noindent{\bf CF-MESMO vs. NSGA-II and random search.} \begin{figure}[t] \centering \vspace{-12pt} \includegraphics[width=0.95\linewidth]{fig/fig_moo_convergence.png} \vspace{-3pt} \caption{CF-MESMO framework results for ResNet20: (a) CF-MESMO hypervolume result compared with NSGA-II and random search, (b) CF-MESMO and MESMO hypervolume results, (c) fidelity index over the CF-MESMO iterations.} \vspace{-15pt} \label{fig:moo_convergence} \end{figure} Fig.~\ref{fig:moo_convergence}(a) illustrates the hypervolume result of CF-MESMO compared with NSGA-II and random search under the same computation cost. The unit cost is defined as the runtime for executing 10 training epochs of the ReSNA method~(e.g., $42.5$ minutes based on our setting for ResNet20). We observe that {\bf 1)} CF-MESMO can achieve a higher-quality Pareto optimal set for the same total computation cost for ReRAM design evaluation; {\bf 2)} CF-MESMO can produce higher quality Pareto front using significantly lower cost compared to NSGA-II and random search; {\bf 3)} CF-MESMO achieves $90.91\%$ and $91.21\%$ reduction in computation cost to reach the same quality Pareto front as NSGA-II and random search, respectively. \noindent{\bf Continuous fidelity vs. single maximum fidelity.} We utilize a continuous fidelity setting in CF-MESMO. As a comparison, we run our optimization method with the single maximum fidelity setting (100 training epochs of ReSNA to evaluate each ReRAM design), denoted as MESMO. Fig.~\ref{fig:moo_convergence}(b) compares the hypervolume of these two methods considering the computational cost. The continuous-fidelity setting in CF-MESMO can guarantee higher quality Pareto front with lower computation cost when compared to the single maximum fidelity algorithm MESMO. Specifically, CF-MESMO lowers the computation cost by $78.18\%$ to reach the same quality Pareto front as MESMO. Note that both CF-MESMO and MESMO can outperform NSGA-II and random search, as we observe from Fig.~\ref{fig:moo_convergence}(a)-(b). These results validate the effectiveness of the proposed CF-MESMO algorithm for ReRAM based MOO optimization. Fig.~\ref{fig:moo_convergence}(c) shows the fidelity index (small index means ReRAM design evaluation using ReSNA with a small number of training iterations) selection over iterations in CF-MESMO. The optimization starts with a large fidelity index, e.g., 7 and 9 at the $1^{st}$ and $2^{nd}$ iterations in the initialization. During the $3^{rd}$ to $25^{th}$ iterations, a small fidelity index is preferred to get a fast approximation of the Pareto front by identifying the promising areas of the ReRAM design space. After that, a larger fidelity index is selected to approach the optimal Pareto front by evaluating candidates from this set of promising ReRAM designs. By using this continuous-fidelity setting, we can exclude the non-promising configurations in an early stage. As shown in Equation~(\ref{af:def}), high fidelity is only utilized when the predicted information gain per unit cost is large. \vspace{0.25ex} \noindent{\bf Optimization results for different DNNs.} \begin{figure}[t] \centering \includegraphics[width=\linewidth]{fig/fig_result_visualization_1.png} \vspace{-15pt} \caption{CF-MESMO framework Pareto front and Pareto set for ResNet20 in a 3-dimensional plot with colorbar, the iteration number is labeled next to each data point: (a) output space, (b) input space.} \vspace{-18pt} \label{fig:result_vis_1} \end{figure} \begin{figure}[t] \vspace{-12pt} \centering \includegraphics[width=\linewidth]{fig/fig_result_visualization.png} \vspace{-15pt} \caption{CF-MESMO framework Pareto front result for ResNets and VGGs in a 3-dimensional plot: (a) ResNets, (b) VGGs.} \vspace{-18pt} \label{fig:result_vis} \end{figure} We use the proposed CF-MESMO framework to achieve robust DNN inferencing with an efficient ReRAM-based hardware platform. For the ResNet20 network, CF-MESMO obtains $11$ Pareto optimal designs over $100$ iterations. Fig.~\ref{fig:result_vis_1}(a) represents these designs in the output space, including the inferencing accuracy, latency, energy consumption, and area overhead. Each data point is labeled with the corresponding iteration number. Although all the $11$ design instances appear at the Pareto front, some of them can be excluded due to efficiency constraints. For instance, designs `56' and `58' consume $113.3\%$ and $105.2\%$ more energy compared to the average of the other designs, while design `72' requires $57.4\%$ more execution time compared to the average of the other designs. We mark the high-energy design points with red and the high-latency design point with magenta in Fig.~\ref{fig:result_vis_1}. According to the input space shown in Fig.~\ref{fig:result_vis_1}(b), a relatively low temperature~($\mathrm{300K}$-$\mathrm{350K}$) and small and medium crossbar sizes~(32$\times$32 and 64$\times$64) are recommended for ResNet20. Fig.~\ref{fig:result_vis} shows the Pareto fronts for ResNets and VGGs. Note that the area evaluation dimension is not included in the plot for ease of illustration, and latency is normalized under the same area constraint. It should be noted that ResNet32 and VGG13 achieve the best inferencing accuracy for each network class. Comparing Fig.~\ref{fig:result_vis}(a) with Fig.~\ref{fig:result_vis}(b), we see that the Pareto fronts for ResNet and VGG have different distributions, while there is a large overlap among the various clusters within the same network class. e.g., the three clusters in Fig.~\ref{fig:result_vis}(a). These results imply that the network structure is not the only factor to determine hardware efficiency. In designing ReRAM-based accelerators, we should first set the expected inferencing accuracy and hardware efficiency target and then choose the network using the Pareto front. Based on the Pareto set results from all the evaluations, we make the following observations: {\bf 1)} Designs with high temperature can appear in the Pareto front, but the number of those cases is low. {\bf 2)} For small DNN models, the channel number is relatively small. Large-sized crossbar results in a low utilization rate and thus is not an optimal choice. As the model size increases, a large-sized crossbar becomes a preferred choice. {\bf 3)} As ReSNA improves the inferencing accuracy, high ReRAM cell resolution and high frequency become the preferred candidates for robust DNN inferencing.
{'timestamp': '2021-09-14T02:19:28', 'yymm': '2109', 'arxiv_id': '2109.05437', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05437'}
arxiv
\section{Introduction}\label{sec1} Opacity is a confidentiality property, which characterizes the scenario whether some ``secret" of a system is ambiguous to a potential malicious intruder based on the evolution of the system. In other words, an opaque system always holds the plausible deniability for its ``secret" during its execution. Opacity can be adapted to capture a variety of privacy and security requirements in cyber-physical systems, including event-driven dynamic systems~\cite{Lafortune(2018),Hadjicostis(2020)} and time-driven dynamic systems~\cite{An(2020),Ramasubramanian(2020)}. The notion of opacity initially appeared in the computer science literature~\cite{Mazare(2004)} to analyze cryptographic protocols. Whereafter, various versions of opacity were characterized in the context of discrete-event systems (DESs). For instance, in automata-based models, several notions of opacity have been proposed and studied, which include current-state opacity~\cite{Saboori(2007)}, initial-state opacity~\cite{Saboori(2013)}, $K$-step opacity~\cite{Saboori(2011a)}, infinite-step opacity~\cite{Saboori(2012)}, and language-based opacity~\cite{Lin(2011),Wu(2013)}. Some more efficient algorithms to check them have also been provided in~\cite{Wu(2013),Yin(2017),Lan(2020)}. Furthermore, when a given system is not opaque, its opacity enforcement problem has been extensively investigated using a variety of techniques, including supervisory control~\cite{Dubreil(2010),Saboori(2012b),Tong(2018)}, insertion or edit functions~\cite{Ji(2018),Ji(2019a),Ji(2019b),Yin(2020)}, dynamic observers~\cite{Zhang(2015)}, etc. Recently, verification and/or enforcement of opacity have been extended to other classes of settings, including Petri nets~\cite{Bryans(2008),Tong(2017),Cong(2018)}, stochastic systems~\cite{Saboori(2014),Keroglou(2017),Yin(2019a)}, modular systems~\cite{Tong(2019)}, networked systems~\cite{Yin(2019b),Yang(2019)}, etc. In recent literature~\cite{Zhang(2019),Yin(2021)}, the authors studied opacity preserving (bi)simulation relations using an abstraction-based technique for nondeterministic transition systems and metric systems, respectively. Some applications of opacity in real-world systems have also been provided in the literature, see, e.g.,~\cite{Saboori(2011b),Wu(2014),Bourouis(2017),Lin(2020)}. In automata-based models, different notions of opacity can capture different security requirements. For example, current-state opacity (CSO) characterizes that an intruder cannot determine for sure whether a system is currently in a secret state. In Location-Based Services (LBS), a user may want to hide his/her initial location or his/her location (e.g., visiting a hospital or bank) at some specific previous instant. Such requirements can be characterized by initial-state opacity (ISO) and $K$/infinite-step opacity ($K$/Inf-SO)\footnote{For convenience, the notion originally named CSO (resp., ISO, $K$-SO, and Inf-SO) is categorized as standard CSO (resp., standard ISO, standard $K$-SO, and standard Inf-SO) in this paper.}. However, these four standard versions of opacity have some limitations in practice. Specifically, they cannot capture the situation that an intruder can never infer for sure whether the system has passed through a secret state based on his/her observation. In other words, even though a system is ``opaque" in the standard sense, the intruder may necessarily determine that a secret state must has been passed through. To this end, in~\cite{Falcone(2015)}, a strong version of opacity called \emph{strong $K$-step opacity} is proposed to capture that the visit of a secret state cannot be inferred within $K$ steps. Also, an algorithm that has complexity $O(2^{|X|+|X|^2})$ is provided to check it using so-called $K$-delay trajectory estimators and R-verifiers, where $|X|$ is the number of states of a system. Inspired by~\cite{Falcone(2015)}, in this paper we are interested in defining and verifying two other strong versions of opacity in partially-observed nondeterministic finite-state automata (NFAs), called \emph{strong current-state opacity} (SCSO) and \emph{strong initial-state opacity} (SISO), respectively. They mean that if a run passes through a secret state at the current time (resp., at the initial time), there exists another run that never passes through a secret state and has the same observation as the previous run has. Obviously, they have higher-level confidentiality than the standard versions. Note that, by the definition of strong $K$-step opacity proposed in~\cite{Falcone(2015)}, we know readily that strong $K$-step opacity reduces to standard CSO when $K=0$. Thus, we conclude that SCSO implies the strong $0$-step opacity but actually these two strong versions of opacity are incomparable when $K\geq 1$. Therefore, the proposed notions of SCSO and SISO are clearly different from all the existing ones in the literature. Further, we develop a novel method to verify SCSO and SISO from a span-new perspective. Specifically, the main contributions of this paper are summarized below. \begin{itemize} \item To overcome the inadequacy that the standard CSO and ISO cannot perfectly characterize high-level privacy requirements, we propose two stronger versions of opacity, called SCSO and SISO. They can characterize higher-level confidentiality than the standard versions. \item For SCSO, we construct an information structure using a novel concurrent-composition technique. And then, we propose a verification criterion of SCSO based on \emph{leaking secret states} defined by us in the proposed structure. This verification approach costs time $O(|X|^4|\Sigma_o||\Sigma_{uo}||\Sigma|2^{|X|})$, where $|X|$ (resp., $|\Sigma|, |\Sigma_o|, |\Sigma_{uo}|$) is the number of states (resp., events, observable events, unobservable events) of a system. \item Regarding the verification problem of SISO, using the novel concurrent-composition technique, we propose another information structure in which the information that whether a system has passed through a secret initial state can be characterized. This approach has also time complexity $O(|X|^4|\Sigma_o||\Sigma_{uo}||\Sigma|2^{|X|})$. \end{itemize} The rest of this paper is arranged as follows. Section~\ref{sec2} provides preliminaries needed in this paper, including the system model, the formal definitions of standard CSO and ISO, and their limitations on confidentiality. Section~\ref{sec3} formalizes the notion of SCSO, and proposes a novel information structure for its verification. In Section~\ref{sec4}, the notion of SISO is proposed, and its verification approach is reported. In Section~\ref{sec5}, we conclude this paper with a brief discussion on how to use the proposed concurrent-composition structure to verify \emph{strong infinite-step opacity}, which can be seen as a strong version of the standard Inf-SO. \section{Preliminaries}\label{sec2} \subsection{System model}\label{subsec2.1} A DES of interest is modeled as a \emph{nondeterministic finite-state automaton} (NFA) $G=(X,\Sigma,\delta, X_0)$, where $X$ is the finite set of states, $\Sigma$ is the finite set of events, $X_0\subseteq X$ is the set of initial states, $\delta: X\times\Sigma\rightarrow 2^{X}$ is the transition function, which depicts the system dynamics: given states $x,y\in X$ and an event $\sigma\in \Sigma$, $y\in\delta(x,\sigma)$ implies that there exists a transition labeled by $\sigma$ from $x$ to $y$. Note that for $x\in X$ and $\sigma\in\Sigma$, if there exists no $y\in X$ such that $y\in\delta(x,\sigma)$, then $\delta(x,\sigma)=\emptyset$. We can extend the transition function to $\delta :X\times\Sigma^{\ast}\rightarrow 2^{X}$ in the usual manner, where $\Sigma^{\ast}$ denotes the \emph{Kleene closure} of $\Sigma$, consisting of all finite sequences composed of the events in $\Sigma$ (including the empty sequence $\epsilon$), see, e.g., \cite{Cassandras(2008)} for more details on DESs. We use $\mathcal{L}(G,x)$ to denote the language generated by $G$ from state $x$, i.e., $\mathcal{L}(G,x)=\{s\in\Sigma^{\ast}: \delta(x,s)\neq\emptyset\}$. Therefore, the language generated by $G$ is $\mathcal{L}(G)=\cup_{x_0\in X_0}\mathcal{L}(G,x_0)$. For a sequence $s\in\mathcal{L}(G)$, we denote its prefix closure by $Pr(s)$, i.e., $Pr(s)=\{w\in\mathcal{L}(G): (\exists w^\prime\in\Sigma^{\ast})[ww^\prime=s]\}$. Further, for a prefix $w\in Pr(s)$, we use the notation $s/w$ to denote the suffix of $s$ after its prefix $w$. We without loss of generality assume that $G$ is accessible, i.e., all its states are reachable from $X_0$. As usual, we assume that the intruder can only see partially the system's behavior. To this end, $\Sigma$ is partitioned into the set $\Sigma_o$ of observable events and the set $\Sigma_{uo}$ of unobservable events, i.e., $\Sigma_o\cup\Sigma_{uo}=\Sigma$ and $\Sigma_o\cap\Sigma_{uo}=\emptyset$. The natural projection $P:\Sigma^{\ast}\rightarrow \Sigma_o^{\ast}$ is defined recursively by ($i$) $P(\epsilon)=\epsilon$, ($ii$) $P(s\sigma)=P(s)\sigma,\mbox{ if } \sigma\in \Sigma_o$, ($iii$) $P(s\sigma)=P(s),\mbox{ if } \sigma\in \Sigma_{uo}$, where $s\in\Sigma^\ast$. We extend the natural projection $P$ to $\mathcal{L}(G)$ by $P(\mathcal{L}(G))=\{P(s)\in\Sigma_{o}^{\ast}: s\in\mathcal{L}(G)\}$. We denote the inverse projection by a mapping $P^{-1}:\Sigma_o^{\ast}\rightarrow 2^{\Sigma^{\ast}}$, i.e., for any $\alpha\in\Sigma_{o}^{\ast}$, we have $P^{-1}(\alpha)=\{s\in\Sigma^{\ast}:P(s)=\alpha\}$. To study opacity of $G=(X,\Sigma,\delta,X_0)$, we assume that $G$ has a set of secret states, denoted by $X_{S}\subset X$. We use $X_{NS}$ to denote the set of non-secret initial states. Let $s=s_{1}s_{2}\ldots s_{n}\in\Sigma^{\ast}$ and $x_0\in X_0, x_i\in X$, $i=1,2,\ldots,n$. If $x_{k+1}\in\delta(x_k,s_{k+1})$, $0\leq k\leq n-1$, we call $x_0\stackrel{s_1}{\rightarrow}x_1\stackrel{s_2}{\rightarrow}x_2\stackrel{s_3}{\rightarrow}\cdots\stackrel{s_n}{\rightarrow}x_n$ a \emph{run} generated by $G$ from $x_0$ to $x_n$ under $s$. We write $x_0\stackrel{s}{\rightarrow}x_n$ (resp., $x_0\stackrel{s}{\rightarrow}$) when $x_1,x_2,\ldots,x_{n-1}$ (resp., $x_1,x_2,\ldots,x_n$) are not specified. Note that there may be more than one run under a sequence $s\in\mathcal{L}(G,x_0)$ based on nondeterminism of $G$. In other words, $x_0\stackrel{s}{\rightarrow}x_n$ may denote some runs. $x_0\stackrel{s_1}{\rightarrow}x_1\stackrel{s_2}{\rightarrow}x_2\stackrel{s_3}{\rightarrow}\cdots\stackrel{s_n}{\rightarrow}x_n$ is called \emph{a non-secret run} if $x_i\in X\backslash X_S$, $i=0,1,2,\cdots,n$. \subsection{Standard current-state opacity and initial-state opacity}\label{subsec2.2} In this subsection, we first recall the formal definitions of standard CSO and ISO in~\cite{Saboori(2007)} and~\cite{Saboori(2013),Wu(2013)}, respectively. And then, we discuss their limitations for characterizing information security. \begin{definition}[Standard CSO~\cite{Saboori(2007)}]\label{de:2.1} Given a system $G=(X,\Sigma,\delta,X_0)$, a projection map $P$ w.r.t. the set $\Sigma_o$ of observable events, and a set $X_{S}\subset X$ of secret states, $G$ is said to be current-state opaque (CSO)\footnote{For brevity, the terminology ``CSO" (resp., ISO), is used as the acronym of both ``current-state opacity" (resp., ``initial-state opacity") and ``current-state opaque" (resp., ``initial-state opaque"), adapted to the context.} (w.r.t. $\Sigma_o$ and $X_{S}$), if for all $x_0\in X_0$ and for all $s\in\mathcal L(G,x_0)$ such that $\delta(x_0,s)\cap X_S\neq\emptyset$, it holds \begin{equation}\label{eq:1} \begin{split} (\exists x^\prime_{0}\in X_0)(\exists t\in \mathcal L(G, x^\prime_0))[\delta(x^\prime_0,t)\cap (X\backslash X_S)\neq\emptyset \\ \wedge P(s)=P(t)]. \end{split} \end{equation} \end{definition} Note that, in~\cite{Saboori(2007)} the notion of standard CSO was defined for deterministic finite-state automata. Obviously, this property can be readily extended to the nondeterministic setting as in Definition~\ref{de:2.1}. \begin{definition}[Standard ISO~\cite{Saboori(2013)}]\label{de:2.2} Given a system $G=(X,\Sigma,\delta,X_0)$, a projection map $P$ w.r.t. the set $\Sigma_o$ of observable events, and a set $X_{S}\subset X$ of secret states, $G$ is said to be initial-state opaque (ISO) (w.r.t. $\Sigma_o$ and $X_{S}$), if for all $x_0\in X_0\cap X_S$ and for all $s\in \mathcal{L}(G,x_0)$, it holds \begin{equation}\label{eq:2} (\exists x^\prime_0\in X_{NS})(\exists t\in\mathcal{L}(G, x^\prime_0)) [P(s)=P(t)]. \end{equation} \end{definition} \begin{remark}\label{re:2.1} Many results on the verification and enforcement of CSO and ISO have been obtained so far. However, the aforementioned two categories of opacity may not be able to characterize higher-level privacy requirements in some practical applications. The following two examples illustrate their limitations. \end{remark} \begin{example}\label{ex:2.1} Let us consider the system $G$ shown in Fig.~\ref{Fig1}, in which the set of secret states is $X_S=\{x_4,x_5\}$. \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig1.eps} \caption{The system $G$ considered in Example~\ref{ex:2.1}, where $\Sigma_o=\{a,b\}$, $\Sigma_{uo}=\{u\}$ and $X_0=\{x_0\}$.} \label{Fig1} \end{figure} After observing the sequence $ab^k$, $k\geq 0$, $G$ can be in any state of $\{x_2, x_3, x_4, x_5\}$ (resp., $\{x_3, x_5\}$) when $k=0$ (reps., when $k\geq 1$). For the sequences $s=aab^n$ and $t=uaab^n$, $n\geq 0$, we have $\delta(x_0,s)=\{x_5\}$, $\delta(x_0,t)=\{x_6\}$ and P(s)=P(t). This means that, for each observation generated by $G$, the intruder can never infer precisely whether $G$ is currently at secret states $x_4$ and/or $x_5$. By Definition~\ref{de:2.1}, $G$ is standard CSO w.r.t. $\Sigma_o$ and $X_S$. Since an intruder has the perfect knowledge of the structure of $G$, he/she immediately concludes that $G$ must have visited secret state $x_4$ or $x_5$ after observing $aab^n$, $n\geq 0$. This leads to some limitations that the security requirement characterized Definition~\ref{de:2.1} is not sufficiently strong to forbid the secret from being revealed. \end{example} \begin{example}\label{ex:2.2} Consider the system $G$ shown in Fig.~\ref{Fig2}, where the set of secret states is $X_S=\{x_2\}$. \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig2.eps} \caption{The system $G$ considered in Example~\ref{ex:2.2}, where $\Sigma_o=\{a,b\}$, $\Sigma_{uo}=\{u\}$ and $X_0=\{x_1,x_2\}$.} \label{Fig2} \end{figure} According to Definition~\ref{de:2.2}, we conclude readily that $G$ is standard ISO. However, $G$ cannot keep the high-level secret based on the privacy condition characterized by Definition~\ref{de:2.2} since after observing the sequence $ab^n$ ($n\geq 0$) an intruder unambiguously determines that $G$ must have passed through secret initial state $x_2$. \end{example} The phenomena in Examples~\ref{ex:2.1} and~\ref{ex:2.2} indicate that the standard versions of CSO and ISO have some limitations to some extent for characterizing high-level information security of a system. In order to overcome the aforementioned limitations, in this paper we propose two strong versions of opacity, called \emph{strong current-state opacity} (SCSO) and \emph{strong initial-state opacity} (SISO). Note that these two stronger notions of opacity provide high-level confidentiality. \section{Strong current-state opacity}\label{sec3} In this section, we formally formulate the strong version of CSO for a system. And then, we propose a novel approach to verify it. \subsection{Notion of strong current-state opacity }\label{subsec3.1} \begin{definition}[SCSO]\label{de:3.1} Given a system $G=(X,\Sigma,\delta,$ $X_0)$, a projection map $P$ w.r.t. the set $\Sigma_o$ of observable events, and a set $X_{S}\subset X$ of secret states, $G$ is said to be strongly current-state opaque (SCSO)\footnote{The terminology ``SCSO" is the acronym of both ``strong current-state opacity" and ``strongly current-state opaque", which depends on the context.} (w.r.t. $\Sigma_o$ and $X_{S}$), if for all $x_0\in X_0$ and for all $s\in\mathcal L(G,x_0)$ such that $\delta(x_0,s)\cap X_S\neq\emptyset$, there exists a non-secret run $x^\prime_0\stackrel{t}{\rightarrow}x$ such that $P(t)=P(s)$, where $x^\prime_0\in X_0$, $x\in X$. \end{definition} Note that if $G$ is a deterministic finite-state automaton, SCSO in Definition~\ref{de:3.1} can be rephrased as follows: $G$ is said to be SCSO (w.r.t. $\Sigma_o$ and $X_{S}$) if \begin{equation*} \begin{split} & (\forall x_0\in X_0, \forall s\in\mathcal L(G,x_0): \delta(x_0,s)\in X_S)\\ & (\exists x^\prime_0\in X_0, \exists t\in\mathcal L(G,x^\prime_0))[(P(s)=P(t))\wedge\\ & (\forall \bar{t}\in Pr(t))[\delta(x^\prime_0,\bar{t})\notin X_S]]. \end{split} \end{equation*} Now we give a physical interpretation of Definition~\ref{de:3.1}. The notion of SCSO captures that if a sequence $s\in\mathcal L(G)$ is generated and a secret state is reached, then there exists a sequence $t\in\mathcal L(G)$ that has the same projection as $s$ and its execution generates a run that never passes through a secret state. SCSO has a higher-level confidentiality than standard CSO. In other words, SCSO implies standard CSO, but the converse implication does not hold. For instance, the system $G$ in Example~\ref{ex:2.1} is standard CSO, but not SCSO since after observing the sequence $aa$ an intruder certainly concludes that $G$ has passed secret state $x_4$ or $x_5$. This results in the following proposition for SCSO and CSO whose straightforward proof is omitted. \begin{proposition}\label{pro:3.1} If system $G$ is SCSO w.r.t. $\Sigma_o$ and $X_S$, then it is also standard CSO w.r.t. $\Sigma_o$ and $X_S$. The converse is not true. \end{proposition} \begin{remark}\label{re:3.1} In~\cite{Falcone(2015)}, the authors proposed the notion of strong $K$-step opacity for a deterministic finite-state automaton $G$. Specifically, $G$ is said to be strongly $K$-step opaque (w.r.t. $\Sigma_o$ and $X_{S}$) if for all $x_0\in X_0$ and for all $s=s_1s_2\in\mathcal{L}(G,x_0)$ such that $\delta(x_0,s_1)\cap X_S\neq\emptyset$ and $|P(s_2)|\leq K$, there exists $x^\prime_0\in X_0$ and $t\in\mathcal L(G,x^\prime_0)$ such that $P(t)=P(s)$ and for all $\bar{t}\in Pr(t)$, if $|P(t/\bar{t})|\leq K$, then $\delta(x^\prime_0,\bar{t})\in X\backslash X_S$. Now we show that SCSO and strong $K$-step opacity are incomparable when $K\geq 1$. Obviously, strong $K$-step opacity does not imply SCSO based on their definitions. Also, the converse does not hold. Let us consider the system $G$ shown in Fig.~\ref{Fig2}, we conclude readily that $G$ is SCSO, but not strongly $K$-step opaque for any $K\geq 1$. \end{remark} In the following Subsection~\ref{subsec3.2}, we study the verification of SCSO based on a novel verification approach, which has time complexity $O(|X|^4|\Sigma_o||\Sigma_{uo}||\Sigma|2^{|X|})$. \subsection{Verifying strong current-state opacity}\label{subsec3.2} In this subsection, we focus on the verification of SCSO in Definition~\ref{de:3.1}. In order to obtain the main result, we need to introduce three notions of \emph{non-secret subautomaton}, \emph{observer} and \emph{concurrent composition} for a given system. Given a system $G=(X,\Sigma,\delta,X_0)$ and a set $X_S\subset X$ of secret states, we construct a non-secret subautomaton by deleting all its secret states from $G$, which is denoted by $G_{dss}$, where ``$dss$" stands for the acronym of ``\emph{deleting secret states}". Note that when we delete a secret state $x_s\in X_S$, all transitions attached to $x_s$ are also deleted. Formally, \begin{equation}\label{eq:3} G_{dss}=(X_{dss},\Sigma_{dss},\delta_{dss},X_{dss,0}), \end{equation} where \begin{itemize} \item $X_{dss}=\{x\in X\backslash X_S: \mbox{ there is a non-secret run } x_0\stackrel{s}{\rightarrow}x\mbox{ for some }x_0\in X_{NS} \mbox{ and } s\in\Sigma^\ast\}$ stands for the set of states; \item $\Sigma_{dss}=\{\sigma\in\Sigma: \exists x,x^{\prime}\in X_{dss} \mbox{ s.t. } x^{\prime}\in\delta(x,\sigma)\}$ stands for the set of events; \item $\delta_{dss}: X_{dss}\times\Sigma_{dss}\rightarrow 2^{X_{dss}}$ stands for the transition function, i.e., for all $x,x^{\prime}\in X_{dss} \mbox{ and } \sigma\in\Sigma_{dss}, x^{\prime}\in \delta_{dss}(x,\sigma) \mbox{ if } x^{\prime}\in \delta(x,\sigma)$; \item $X_{dss,0}=X_{NS}$ stands for the set of initial states. \end{itemize} Next, we recall the \emph{observer} of $G_{dss}$ that is defined by \begin{equation}\label{eq:4} Obs(G_{dss})=(X^{obs}_{dss},\Sigma^{obs}_{dss},\delta^{obs}_{dss},X^{obs}_{dss,0}), \end{equation} where $X^{obs}_{dss}\subseteq 2^{X_{dss}}\backslash \emptyset$ stands for the set of states; $\Sigma^{obs}_{dss}$ stands for the observable event set $\Sigma_{dss,o}$ of $\Sigma_{dss}$; $\delta^{obs}_{dss}: X^{obs}_{dss}\times\Sigma^{obs}_{dss}\rightarrow X^{obs}_{dss}$ stands for the (partial) deterministic transition function defined as follows: for any $q\in X^{obs}_{dss}$ and $\sigma\in\Sigma^{obs}_{dss}$, we have $\delta^{obs}_{dss}(q,\sigma)=\{x^{\prime}\in X_{dss}: \exists x\in q, \exists w\in\Sigma_{dss,uo}^\ast \mbox{ s.t. }x^{\prime}\in\delta_{dss}(x,\sigma w)\}$ if it is nonempty, where $\Sigma_{dss,uo}=\Sigma_{dss}\backslash\Sigma_{dss,o}$; $X^{obs}_{dss,0}=\{x\in X_{dss}: \exists x_0\in X_{dss,0}, \exists w\in\Sigma_{dss,uo}^\ast \mbox{ s.t. }x\in\delta_{dss}(x_0,w)\}$ stands for the (unique) initial state. For brevity, we only consider the accessible part of observer $Obs(G_{dss})$. Note that the widely-used \emph{observer} $Obs(G_{dss})$ is an important information structure that can track all possible states of $G_{dss}$ consistent with the current observation. Specifically, $Obs(G_{dss})$ captures the observable behavior of $G_{dss}$, that is, $\mathcal{L}(Obs(G_{dss}))=P(\mathcal{L}(G_{dss}))$. The time complexity of computing observer $Obs(G_{dss})$ for $G_{dss}$ is $O(|X|^2|\Sigma_o||\Sigma_{uo}|2^{|X|})$. We refer the reader to \cite{Cassandras(2008),Shu(2007)} for more details on the notion of observer. \begin{example}\label{ex:3.1} Consider the system $G$ depicted in Fig.~\ref{Fig3}, where the set of secret states is $X_S=\{x_2,x_4\}$. The non-secret subautomaton $G_{dss}$ and the observer $Obs(G_{dss})$ for $G$ are shown in Fig.~\ref{Fig4}. \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig3.eps} \caption{The system $G$ considered in Example~\ref{ex:3.1}, where $\Sigma_o=\{a,b\}$, $\Sigma_{uo}=\{u\}$ and $X_0=\{x_0\}$.} \label{Fig3} \end{figure} \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig4.eps} \caption{The non-secret subautomaton $G_{dss}$ (left) of $G$ shown in Fig.~\ref{Fig3} and the observer $Obs(G_{dss})$ (right) of $G_{dss}$.} \label{Fig4} \end{figure} \end{example} Now we are ready to introduce a novel information structure called the \emph{concurrent composition} of system $G$ and observer $Obs(G_{dss})$, which will be used to verify SCSO in Definition~\ref{de:3.1}. \begin{definition}[Concurrent Composition]\label{de:3.2} Given a system $G=(X,\Sigma,\delta,X_0)$ and a set $X_{S}\subset X$ of secret states, the concurrent composition of $G$ and $Obs(G_{dss})$ is an NFA \begin{equation}\label{eq:5} Cc(G,Obs(G_{dss}))=(X_{cc},\Sigma_{cc},\delta_{cc},X_{cc,0}), \end{equation} where \begin{itemize} \item $X_{cc}\subseteq X\times 2^{X}$ stands for the set of states; \item $\Sigma_{cc}=\{(\sigma,\sigma): \sigma\in\Sigma_o\}\cup\{(\sigma,\epsilon): \sigma\in\Sigma_{uo}\}$ stands for the set of events; \item $\delta_{cc}: X_{cc}\times\Sigma_{cc}\rightarrow 2^{X_{cc}}$ is the transition function defined as follows: for any state $(x,q)\in X_{cc}$ and for any event $\sigma\in\Sigma$, \begin{itemize} \item [(i)] when $q\neq\emptyset$,\\ (a) if $\sigma\in\Sigma_o$, then \begin{equation*} \begin{split} & \delta_{cc}((x,q),(\sigma,\sigma))=\{(x^\prime,q^\prime)\in X_{cc}: x^\prime\in\delta(x,\sigma),\\ & q^\prime=\delta^{obs}_{dss}(q,\sigma) \mbox{ if }\delta^{obs}_{dss}(q,\sigma) \mbox{ is well-defined },q^\prime=\emptyset \\ & \mbox{otherwise}\}; \end{split} \end{equation*} (b) if $\sigma\in\Sigma_{uo}$, then \begin{equation*} \delta_{cc}((x,q),(\sigma,\epsilon))=\{(x^\prime,q)\in X_{cc}: x^\prime\in\delta(x,\sigma)\}. \end{equation*} \item [(ii)] When $q=\emptyset$,\\ (a) if $\sigma\in\Sigma_o$, then \begin{equation*} \delta_{cc}((x,\emptyset),(\sigma,\sigma))=\{(x^\prime,\emptyset)\in X_{cc}: x^\prime\in\delta(x,\sigma)\}; \end{equation*} (b) if $\sigma\in\Sigma_{uo}$, then \begin{equation*} \delta_{cc}((x,\emptyset),(\sigma,\epsilon))=\{(x^\prime,\emptyset)\in X_{cc}: x^\prime\in\delta(x,\sigma)\}. \end{equation*} \end{itemize} \item $X_{cc,0}=X_0\times\{X^{obs}_{dss,0}\}$ stands for the set of initial states. \end{itemize} \end{definition} For a sequence $e\in\mathcal{L}(Cc(G,Obs(G_{dss})))$, we utilize the notations $e(L)$ and $e(R)$ to denote its left and right components, respectively. A similar notation is employed to the language $\mathcal{L}(Cc(G,Obs(G_{dss})))$. Further, we use $P(e)$ to denote $P(e(L))$ or $P(e(R))$ since $P(e(L))=P(e(R))$ for any $e\in\mathcal{L}(Cc(G,Obs(G_{dss})))$, which depends on the context. Intuitively, $Cc(G,Obs(G_{dss}))$ characterizes the following two properties: (i) $\mathcal{L}(Cc(G,$ $Obs(G_{dss})))(L)=\mathcal{L}(G)$; and (ii) it tracks a sequence $s\in\mathcal L(G)$ from $X_0$ and an observation $\alpha\in\mathcal L(Obs(G_{dss}))$ from $X^{obs}_{dss,0}$ (if exists) such that $P(s)=\alpha$. \begin{remark}\label{re:3.2} The idea of concurrent composition was used in~\cite{Zhang(2020)} to verify the so-called eventual strong detectability for a finite-state automaton. However, there are differences between the construction proposed in~\cite{Zhang(2020)} and the above construction. First, the construction proposed in~\cite{Zhang(2020)} is based on a system $G$, while the concurrent composition defined in~\eqref{eq:5} is based on two different settings. Second, the two definitions of transition functions meet different requirements. Specifically, in~\cite{Zhang(2020)}, the concurrent composition aggregates each pair of transition sequences of $G$ generating the same projection. However, by Definition~\ref{de:3.2}, $Cc(G,Obs(G_{dss}))$ captures that for any sequence $s\in\mathcal L(G)$, whether or not there exists an observation $\alpha\in\mathcal L(Obs(G_{dss})))$ such that $P(s)=\alpha$. \end{remark} \begin{example}\label{ex:3.2} Consider again the system $G$ depicted in Fig.~\ref{Fig3}, the concurrent composition $Cc(G,Obs(G_{dss}))$ for $G$ is shown in Fig.~\ref{Fig5}, where $Obs(G_{dss})$ is shown in Fig.~\ref{Fig4}. For brevity, for each state in $Cc(G,Obs(G_{dss}))$, its first and second components are abbreviated by using their respective subscript sets. For example, state $(4,\{1,5\})$ stands for state $(x_4,\{x_1,x_5\})$. \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig5.eps} \caption{The concurrent composition $Cc(G,Obs(G_{dss}))$ of $G$ shown in Fig.~\ref{Fig3}, where $G_{dss}$ and $Obs(G_{dss})$ are shown in Fig.~\ref{Fig4}.} \label{Fig5} \end{figure} \end{example} In order to present the first main result of this paper, we classify the states whose first components belong to $X_S$ in $Cc(G,Obs(G_{dss}))$ defined in~\eqref{eq:5} into two types: \begin{itemize} \item \textbf{leaking secret states}: $(x,q)\in X_{cc}$ with $x\in X_S\wedge q=\emptyset$; \item \textbf{non-leaking secret states}: $(x,q)\in X_{cc}$ with $x\in X_S\wedge q\neq\emptyset$; \end{itemize} The leaking and non-leaking secret states are interpreted physically as follows. If $(x,q)\in X_{cc}$ is a leaking secret state, then, by Definition~\ref{de:3.2}, in $G$ there exists $x_0\in X_0$ and $s\in\mathcal{L}(G,x_0)$ such that $x\in\delta(x_0,s)$, and there exists no observation $\alpha\in\mathcal L(Obs(G_{dss}))$ such that $P(s)=\alpha$. This means that an intruder certainly concludes that $G$ has reached/passed through at least one secret state by observing $P(s)$. If $(x,q)\in X_{cc}$ is a non-leaking secret state, then there exist $x_0, x^\prime_0\in X_0$, $s\in\mathcal{L}(G,x_0)$, and $t\in\mathcal{L}(G,x^\prime_0)$ such that: (i) $x\in\delta(x_0,s)$; (ii) $s$ and $t$ have the same projection, i.e., $P(s)=P(t)$; (iii) there exists a non-secret run $x^{\prime}_0\stackrel{t}{\rightarrow}x^{\prime}$ generated by $G$ from $x^\prime_0$ to $x^\prime$ under $t$. Based on the above preparation, now we are ready to introduce the main result on verification of SCSO for a system. It reveals that a system is SCSO if and only if its concurrent-composition structure does not contain any leaking secret state. \begin{theorem}\label{th:3.1} Given a system $G=(X,\Sigma,\delta,X_0)$, a projection map $P$ w.r.t. the set $\Sigma_o$ of observable events, and a set $X_{S}\subset X$ of secret states, let $Cc(G,Obs(G_{dss}))$ be the concurrent composition of $G$ and $Obs(G_{dss})$. $G$ is SCSO w.r.t. $\Sigma_o$ and $X_S$ if and only if there exists no leaking secret state in $Cc(G,Obs(G_{dss}))$. \end{theorem} \begin{proof} $(\Rightarrow)$ By contrapositive, assume that there exists a leaking secret state $(x,\emptyset)$ in $Cc(G,Obs(G_{dss}))$. Let $e\in\mathcal{L}(Cc(G,Obs(G_{dss})))$ be a sequence that leads to $(x,\emptyset)$ from $X_{cc,0}$. Then, there exists an initial state $(x_0,X^{obs}_{dss,0})\in X_{cc,0}$ such that $(x,\emptyset)\in\delta_{cc}((x_0,X^{obs}_{dss,0}),e)$. Further, by the construction of $Cc(G,Obs(G_{dss}))$, we have that $x\in\delta(x_0,e(L))$ and $\delta^{obs}_{dss}(X^{obs}_{dss,0},e(R))$ is not well-defined. The former means $e(L)\in\mathcal{L}(G,x_0)$ and $\delta(x_0,e(L))\cap X_S\neq\emptyset$. The latter means that for all $x^\prime_0\in X_{NS}$ and for all $t\in\mathcal{L}(G_{dss},x^\prime_0)$ with $P(t)=e(R)=P(e(L))$, it holds $\delta_{dss}(x^\prime_0,t)=\emptyset$. By the construction of $G_{dss}$, we conclude that there exists no non-secret run in $G$ starting from $X_0$ with observation $P(e)$. Therefore, by Definition~\ref{de:3.1}, $G$ is not SCSO w.r.t. $\Sigma_o$ and $X_S$. $(\Leftarrow)$ Also by contrapositive, assume that $G$ is not SCSO w.r.t. $\Sigma_o$ and $X_S$. By Definition~\ref{de:3.1}, there exists a run $x_0\stackrel{s}{\rightarrow}x_s$, where $x_0\in X_0$ and $x_s\in X_S$, and there exist no $x^\prime_0\in X_{NS}$ and $t\in\mathcal L(G,x^\prime_0)$ such that $P(t)=P(s)$ and $G$ generates a non-secret run starting from $x^\prime_0$ under $t$. The former means $x_s\in\delta(x_0,s)$. By the construction of $G_{dss}$, the latter means $\delta_{dss}(x^{\prime\prime}_0,t)=\emptyset$ for all $x^{\prime\prime}_0\in X_{NS}$ and for all $t\in\mathcal L(G,x^{\prime\prime}_0)$ with $P(t)=P(s)$. This further means that $\delta^{obs}_{dss}(X_{dss,0}^{obs},P(t))$ is not well-defined. By the construction of $Cc(G,Obs(G_{dss}))$, we conclude that there is $e\in\mathcal{L}(Cc(G,Obs(G_{dss})))$ with $e(L)=s$ and $e(R)=P(t)$ such that $(x_s,\emptyset)\in\delta_{cc}((x_0,X^{obs}_{dss,0}),e)$. Therefore, $(x_s,\emptyset)$ a leaking secret state in $Cc(G,Obs(G_{dss}))$. \end{proof} \begin{example}\label{ex:3.3} (1) For the system $G$ depicted in Fig.~\ref{Fig3}, there exists no leaking state in $Cc(G,Obs(G_{dss}))$ shown in Fig.~\ref{Fig5}. By Theorem~\ref{th:3.1}, $G$ is SCSO w.r.t. $X_S$. (2) For the system $G$ depicted in Fig.~\ref{Fig1}, its concurrent composition $Cc(G,Obs(G_{dss}))$ is shown in Fig.~\ref{Fig6} in which there exists a leaking secret states $(5,\emptyset)$. By Theorem~\ref{th:3.1}, $G$ is not SCSO w.r.t. $\Sigma_o$ and $X_S$. \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig6.eps} \caption{The concurrent composition $Cc(G,Obs(G_{dss}))$ of $G$ shown in Fig.~\ref{Fig1}, where $G_{dss}$ and $Obs(G_{dss})$ are shown in Fig.~\ref{Fig7}.} \label{Fig6} \end{figure} \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig7.eps} \caption{The non-secret subautomaton $G_{dss}$ (left) of $G$ in Fig.~\ref{Fig1} and the observer $Obs(G_{dss})$ (right) of $G_{dss}$.} \label{Fig7} \end{figure} \end{example} We end this section by analyzing the time complexity of using Theorem~\ref{th:3.1} to verify SCSO. Since $G$ has the complexity of $O(|X|^2|\Sigma|)$ and computing $Obs(G_{dss})$ costs time $O(|X|^2|\Sigma_o||\Sigma_{uo}|2^{|X|})$, the time complexity of constructing $Cc(G,Obs(G_{dss}))$ is $O(|X|^4|\Sigma_o||\Sigma_{uo}||\Sigma|2^{|X|})$. Consequently, the (worst-case) time complexity of using Theorem~\ref{th:3.1} to verify SCSO is $O(|X|^4|\Sigma_o||\Sigma_{uo}||\Sigma|2^{|X|})$. \section{Strong initial-state opacity}\label{sec4} In this section, we focus on the formulation of strong ISO and its verification problem for a system. \subsection{Notion of strong initial-state opacity }\label{subsec4.1} \begin{definition}[SISO]\label{de:4.1} Given a system $G=(X,\Sigma,\delta,$ $X_0)$, a projection map $P$ w.r.t. the set $\Sigma_o$ of observable events, and a set $X_{S}\subset X$ of secret states, $G$ is said to be strongly initial-state opaque (SISO)\footnote{Similar to the terminology ``SCSO", in this paper ``SISO" is the acronym of both ``strong initial-state opacity" and ``strongly initial-state opaque", which also depends on the context.} (w.r.t. $\Sigma_o$ and $X_{S}$), if for all $x_0\in X_0\cap X_S$ and for all $s\in\mathcal{L}(G,x_0)$, there exists a non-secret run $x^\prime_0\stackrel{t}{\rightarrow}$ such that $P(t)=P(s)$, where $x^\prime_0\in X_{NS}$. \end{definition} Intuitively, SISO in Definition~\ref{de:4.1} captures that for each sequence $s\in\mathcal L(G)$ starting from any $x_0\in X_0\cap X_S$, there exists a sequence $t\in\mathcal L(G)$ starting from some $x^\prime_0\in X_{NS}$ such that $P(t)=P(s)$ and $G$ generates a non-secret run starting from $x^\prime_0$ under $t$. Note that, SISO, compared with standard ISO in Definition~\ref{de:2.2}, has a higher-level confidentiality obviously. In other words, SISO implies standard ISO, but the converse is not true. Taking the system $G$ shown in Fig.~\ref{Fig2} for example, by Definitions~\ref{de:2.2} and~\ref{de:4.1}, we conclude readily that $G$ is standard ISO, but not SISO. Next, we illustrate these two strong versions of opacity in Definitions~\ref{de:3.1} and~\ref{de:4.1} are incomparable. In other words, SCSO does not imply SISO, and vice versa. For instance, by Definitions~\ref{de:3.1} and~\ref{de:4.1}, the system $G$ depicted in Fig.~\ref{Fig2} is SCSO, but not SISO. On the other hand, let us consider the system $G$ shown in Fig.~\ref{Fig8}. We know that $G$ is SISO, but not SCSO. \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig8.eps} \caption{A system $G$ with $\Sigma=\Sigma_o=\{a,b\}$, $X_0=\{x_1,x_2\}$ and $X_{S}=\{x_2\}$.} \label{Fig8} \end{figure} \subsection{Verifying strong initial-state opacity }\label{subsec4.2} Inspired by the verification of SCSO in Section~\ref{sec3}, we, in this subsection, use a minor variant of the concurrent composition approach to verify SISO of a system. Consider a system $G=(X,\Sigma,\delta,X_0)$ in which the set of secret states is denoted by $X_S \subset X$. $G_{dss}$ stands for the non-secret subautomaton obtained by deleting all secret states in $G$, which is defined in Eq.~\eqref{eq:4}. $Obs(G_{dss})$ defined in Eq.~\eqref{eq:5} stands for the observer of $G_{dss}$. To check SISO in Definition~\ref{de:4.1}, we construct an \emph{initial-secret subautomaton} from $G$, denoted by $\hat{G}$, as follows: \begin{equation}\label{eq:6} \hat{G}=(\hat{X},\hat{\Sigma},\hat{\delta},\hat{X}_0), \end{equation} where \begin{itemize} \item $\hat{X}=\{x\in X: \exists x_0\in {X_0}\cap {X_S},\exists s\in\Sigma^\ast\mbox{ s.t. }x\in\delta(x_0,s)\}$ stands for the set of states; \item $\hat{\Sigma}=\{\sigma\in\Sigma:\exists x,x^{\prime}\in\hat{X} \mbox{ s.t. } x^{\prime}\in\delta(x,\sigma)\}$ stands for the set of events; \item $\hat{\delta}: \hat{X}\times\hat{\Sigma}\rightarrow 2^{\hat{X}}$ stands for the transition function, i.e., for all $x,x^{\prime}\in\hat{X}$ and $\sigma\in\hat{\Sigma}$, $x^{\prime}\in\hat{\delta}(x,\sigma)$ if $x^{\prime}\in\delta(x,\sigma)$; \item $\hat{X}_0={X_0}\cap {X_S}$ stands for the set of secret initial states. \end{itemize} Note that when we ``delete" a state that is inaccessible from the set $\hat{X}_0$ of secret initial states, we also delete all transitions attached to that state. Obviously, $\hat{G}$ is a subautomaton of $G$ and is obtained by deleting all its states unreachable from $\hat{X}_0$. Next, we construct the \emph{concurrent composition} of $\hat{G}$ and $Obs(G_{dss})$ for $G$, which also is an NFA, as follows. \begin{equation}\label{eq:7} Cc(\hat{G},Obs(G_{dss}))=(\hat{X}_{cc},\hat{\Sigma}_{cc},\hat{\delta}_{cc},\hat{X}_{cc,0}), \end{equation} where \begin{itemize} \item $\hat{X}_{cc}\subseteq \hat{X}\times 2^{X}$ stands for the set of states; \item $\hat{\Sigma}_{cc}=\{(\sigma,\sigma):\sigma\in\hat{\Sigma}_o\}\cup\{(\sigma,\epsilon):\sigma\in\hat{\Sigma}_{uo}\}$ stands for the set of events, where $\hat{\Sigma}_o$ (resp., $\hat{\Sigma}_{uo}$) is the set of observable (resp., unobservable) events of $\hat{\Sigma}$; \item $\hat{\delta}_{cc}: \hat{X}_{cc}\times\hat{\Sigma}_{cc}\rightarrow 2^{\hat{X}_{cc}}$ is the transition function defined as follows: for any state $(x,q)\in \hat{X}_{cc}$, and for any event $\sigma\in\hat{\Sigma}$, \begin{itemize} \item [(i)] when $q\neq\emptyset$,\\ (a) if $\sigma\in\hat{\Sigma}_o$, then \begin{equation*} \begin{split} & \hat{\delta}_{cc}((x,q),(\sigma,\sigma))=\{(x^\prime,q^\prime)\in \hat{X}_{cc}: x^\prime\in\hat{\delta}(x,\sigma),\\ & q^\prime=\delta^{obs}_{dss}(q,\sigma) \mbox{ if } \delta^{obs}_{dss}(q,\sigma) \mbox{ is well-defined, } q^\prime=\emptyset \\ & \mbox{otherwise}\}; \end{split} \end{equation*} (b) if $\sigma\in\hat{\Sigma}_{uo}$, then \begin{equation*} \hat{\delta}_{cc}((x,q),(\sigma,\epsilon))=\{(x^\prime,q)\in \hat{X}_{cc}: x^\prime\in\hat{\delta}(x,\sigma)\}. \end{equation*} \item [(ii)] when $q=\emptyset$,\\ (a) if $\sigma\in\hat{\Sigma}_o$, then \begin{equation*} \hat{\delta}_{cc}((x,\emptyset),(\sigma,\sigma))=\{(x^\prime,\emptyset)\in \hat{X}_{cc}: x^\prime\in\hat{\delta}(x,\sigma)\}; \end{equation*} (b) if $\sigma\in\hat{\Sigma}_{uo}$, then \begin{equation*} \hat{\delta}_{cc}((x,\emptyset),(\sigma,\epsilon))=\{(x^\prime,\emptyset)\in\hat{X}_{cc}: x^\prime\in\hat{\delta}(x,\sigma)\}. \end{equation*} \end{itemize} \item $\hat{X}_{cc,0}=\hat{X}_0\times\{X^{obs}_{dss,0}\}$ stands for the set of initial states. \end{itemize} In order to present the verification criterion of SISO in Definition~\ref{de:4.1}, similarly to the argument in Section~\ref{sec3}, we classify the states in $Cc(\hat{G},Obs(G_{dss}))$ defined in \eqref{eq:7} into two types: \begin{itemize} \item \textbf{leaking states}: for all $(x,q)\in\hat{X}_{cc}$ with $x\in\hat{X}\wedge q=\emptyset$; \item \textbf{non-leaking states}: for all $(x,q)\in\hat{X}_{cc}$ with $x\in\hat{X}\wedge q\neq\emptyset$; \end{itemize} We now give an interpretation of leaking and non-leaking states as follows: if $(x,q)\in\hat{X}_{cc}$ is a leaking state, by the construction of $Cc(\hat{G},Obs(G_{dss}))$, then in $G$ there exists a secret initial state $x_0\in X_0\cap X_S$ and a sequence $s\in\mathcal{L}(G,x_0)$ such that $x\in\delta(x_0,s)$, and there exists no $x^{\prime}_0\in X_{NS}$ and $t\in\mathcal{L}(G,x^{\prime}_0)$ such that $x^{\prime}_0\stackrel{t}{\rightarrow}$ is a non-secret run and $P(t)=P(s)$. If $(x,q)\in\hat{X}_{cc}$ is a non-leaking state, then in $G$ there exists $x_0\in X_0\cap X_S$, $x^\prime_0\in X_{NS}$, $s\in\mathcal{L}(G,x_0)$, and $t\in\mathcal{L}(G,x^\prime_0)$ such that: (i) $P(t)=P(s)$, and (ii) $G$ generates a non-secret run starting from $x^\prime_0$ under $t$. \begin{theorem}\label{th:4.1} Given a system $G=(X,\Sigma,\delta,X_0)$, a projection map $P$ w.r.t. the set $\Sigma_o$ of observable events, and a set $X_{S}\subset X$ of secret states, let $Cc(\hat{G},Obs(G_{dss}))$ be the concurrent composition of $\hat{G}$ and $Obs(G_{dss})$. $G$ is SISO w.r.t. $\Sigma_o$ and $X_S$ if and only if there exists no leaking state in $Cc(\hat{G},Obs(G_{dss}))$. \end{theorem} \begin{proof} This proof is analogous to that of Theorem~\ref{th:3.1} by contraposition. $(\Rightarrow)$ Assume that there exists a leaking state $(x,\emptyset)$ in $Cc(\hat{G},Obs(G_{dss}))$. Let $e\in\mathcal{L}(Cc(\hat{G},Obs(G_{dss})))$ be a sequence that leads to $(x,\emptyset)$ from $\hat{X}_{cc,0}$. Then, there exists an initial state $(x_0,X^{obs}_{dss,0})\in\hat{X}_{cc,0}$ such that $(x,\emptyset)\in\hat{\delta}_{cc}((x_0,X^{obs}_{dss,0}),e)$. By the construction of $Cc(\hat{G},Obs(G_{dss}))$, one has $x_0\in{X_0}\cap{X_S}$, $x\in\hat{\delta}(x_0,e(L))$ and $\delta^{obs}_{dss}(X^{obs}_{dss,0},e(R))$ is not well-defined. Since $\hat{G}$ is the initial-secret subautomaton of $G$, $x\in\hat{\delta}(x_0,e(L))$ means $x\in\delta(x_0,e(L))$. However, $\delta^{obs}_{dss}(X^{obs}_{dss,0},e(R))$ not well-defined implies that for all $x^\prime_0\in X_{NS}$ and for all $t\in\mathcal{L}(G_{dss},x^\prime_0)$ with $P(t)=e(R)=P(e(L))$, it holds $\delta_{dss}(x^\prime_0,t)=\emptyset$. By the construction of $G_{dss}$, we conclude that there do not exist a state $x^\prime_0\in X_{NS}$ and a sequence $t\in\mathcal{L}(G,x^\prime_0)$ with $P(t)=P(e)$ such that $G$ generates a non-secret run starting from $x^\prime_0$ under $t$. Therefore, by Definition~\ref{de:4.1}, $G$ is not SISO w.r.t. $\Sigma_o$ and $X_S$. $(\Leftarrow)$ Assume that $G$ is not SISO w.r.t. $\Sigma_o$ and $X_S$. By Definition~\ref{de:4.1}, we know that: (1) in $G$ there exists a secret initial state $x_0\in X_0\cap X_S$ and a sequence $s\in\mathcal{L}(G,x_0)$, and (2) there does not exist a sequence $t\in\mathcal L(G,x^\prime_0)$ for any $x^\prime_0\in X_{NS}$ such that $x^\prime_0\stackrel{t}{\rightarrow}$ is a non-secret run and $P(t)=P(s)$. By the construction of $\hat{G}$, the former means that there exists a state $x\in\hat{X}$ such that $x\in\hat{\delta}(x_0,s)$. By the construction of $G_{dss}$, the latter means $\delta_{dss}(x^{\prime\prime}_0,t)=\emptyset$ for all $x^{\prime\prime}_0\in X_{NS}$ and for all $t\in\mathcal L(\hat{G},x^{\prime\prime}_0)$ with $P(t)=P(s)$. This further implies that $\delta^{obs}_{dss}(X_{dss,0}^{obs},P(t))$ is not well-defined. By the construction of $Cc(\hat{G},Obs(G_{dss}))$, we conclude that there exists a sequence $e\in\mathcal{L}(Cc(\hat{G},Obs(G_{dss})))$ with $e(L)=s$ and $e(R)=P(t)$ such that $(x,\emptyset)\in\hat{\delta}_{cc}((x_0,X_{dss,0}^{obs}),e)$. Therefore, $(x,\emptyset)$ a leaking state in $Cc(\hat{G},Obs(G_{dss}))$. \end{proof} \begin{remark}\label{re:4.1} We discuss the time complexity of checking SISO for $G$ using Theorem~\ref{th:4.1}. From Subsection~\ref{subsec3.2}, $Obs(G_{dss})$ has time complexity $O(|X|^2|\Sigma_o||\Sigma_{uo}|2^{|X|})$. By Eq.~\eqref{eq:6}, the time complexity of constructing $\hat{G}$ from $G$ is $O(|X|^2|\Sigma|)$. Therefore, the time complexity of constructing $Cc(\hat{G},Obs(G_{dss}))$ is $O(|X|^4|\Sigma_o||\Sigma_{uo}||\Sigma|2^{|X|})$. This indicates that the time complexity of verifying SISO in Definition~\ref{de:4.1} is $O(|X|^4|\Sigma_o||\Sigma_{uo}||\Sigma|2^{|X|})$. \end{remark} \begin{example}\label{ex:4.1} Let us consider the system $G$ depicted in Fig.~\ref{Fig9}, where the set of secret states is $X_S=\{x_1\}$. The constructed automata $\hat{G}$, $G_{dss}$ and $Obs(G_{dss})$ for $G$ are shown in Fig.~\ref{Fig10}. Further, the concurrent composition $Cc(\hat{G},Obs(G_{dss}))$ is shown in Fig.~\ref{Fig11} in which there exist two leaking states $(4,\emptyset)$ and $(5,\emptyset)$\footnote{Note that, similar to $Cc(G,Obs(G_{dss}))$, for each state in $Cc(\hat{G},Obs(G_{dss}))$, its first and second components are also abbreviated by using their respective subscript set. For instance, $(4,\emptyset)$ is the abbreviation of state $(x_4,\emptyset)$.}. By Theorem~\ref{th:4.1}, $G$ is not SISO w.r.t. $\Sigma_o$ and $X_S$. \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig9.eps} \caption{The system $G$ considered in Example~\ref{ex:4.1}, where $\Sigma_o=\{a,b\}$, $\Sigma_{uo}=\{u\}$ and $X_0=\{x_0,x_1\}$.} \label{Fig9} \end{figure} \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig10.eps} \caption{The constructed automata: $\hat{G}$ (above), $G_{dss}$ (middle) and $Obs(G_{dss})$ (below) for the system $G$ in Fig.~\ref{Fig9}.} \label{Fig10} \end{figure} \begin{figure}[!ht] \centering \includegraphics[scale=0.75]{Fig11.eps} \caption{The concurrent composition $Cc(\hat{G},Obs(G_{dss}))$ for the system $G$ in Fig.~\ref{Fig9}.} \label{Fig11} \end{figure} \end{example} \section{Concluding remarks}\label{sec5} In this paper, we characterized two strong versions of opacity called strong current-state opacity and strong initial-state opacity, respectively. They have higher-level confidentiality than the standard versions. Further, we constructed two information structures using a novel concurrent-composition technique to verify these two strong versions of opacity, which have (worst-case) time complexity $O(|X|^4|\Sigma_o||\Sigma_{uo}||\Sigma|2^{|X|})$. Motivated by~\cite{Falcone(2015)} and our work, a strong version of standard Inf-SO, called \emph{strong infinite-step opacity} (Inf-SSO), is formally formulate in the context of nondeterministic settings as follows. \begin{definition}[Inf-SSO]\label{de:5.1} Given a system $G=(X,\Sigma,$ $\delta,X_0)$, a projection map $P$ w.r.t. the set $\Sigma_o$ of observable events, and a set $X_{S}\subset X$ of secret states, $G$ is said to be strongly infinite-step opaque (Inf-SSO) (w.r.t. $\Sigma_o$ and $X_{S}$), if for all $x_0\in X_0$ and for all $s=s_1s_2\in\mathcal{L}(G,x_0)$ such that $\delta(x_0,s_1)\cap X_S\neq\emptyset$, there exists a non-secret run $x^\prime_0\stackrel{t}{\rightarrow}$ such that $P(t)=P(s)$, where $x^\prime_0\in X_{NS}$. \end{definition} By Definition~\ref{de:5.1}, one sees that $G$ is Inf-SSO if and only if for all $x_0\in X_0$ and for all $s\in\mathcal{L}(G,x_0)$, there exists a non-secret run $x^\prime_0\stackrel{t}{\rightarrow}$ for some $x^\prime_0\in X_{NS}$ and some $t\in\mathcal{L}(G,x^\prime_0)$ such that $P(t)=P(s)$. We can use the concurrent composition $Cc(G,Obs(G_{dss}))$ of $G$ and $Obs(G_{dss})$ constructed in Definition~\ref{de:3.2} to present the result on verification of Inf-SSO, which also has time complexity $O(|X|^4|\Sigma_o||\Sigma_{uo}||\Sigma|2^{|X|})$. We here omit its proof, which is similar to that of Theorem~\ref{th:3.1}. \begin{theorem}\label{th:5.1} Given a system $G=(X,\Sigma,\delta,X_0)$, a projection map $P$ w.r.t. the set $\Sigma_o$ of observable events, and a set $X_{S}\subset X$ of secret states, let $Cc(G,Obs(G_{dss}))$ be the concurrent composition of $G$ and $Obs(G_{dss})$. $G$ is Inf-SSO w.r.t. $\Sigma_o$ and $X_S$ if and only if there exists no such a state in $Cc(G,Obs(G_{dss}))$ whose right component is $\emptyset$. \end{theorem} In the future, we plan to exploit the proposed concurrent-composition approach to design algorithms for enforcing strong current-state opacity, strong initial-state opacity and strong infinite-step opacity. \bibliographystyle{plain}
{'timestamp': '2021-09-14T02:21:06', 'yymm': '2109', 'arxiv_id': '2109.05475', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05475'}
arxiv
\section{Introduction} Owing to large amounts of conversation data and pre-training models \cite{dialogpt, blender}, generation-based chatbots have achieved significant advances and even reach human parity on specific testsets \cite{persona,wizard, bst}. However, the robustness of the pre-trained model is still low with regard to unseen entities \cite{zhang2016understanding, wizard}. In practice, users often talk with chatbots about latest news and the recently hot topics \cite{blind-users}, which may not appear in the pre-training or fine-tuning corpus. For instance, ``COVID-19'' is a new term, which does not appear in the training data of Blender \footnote{Blender uses 1.5B Reddit 2019 text data for pre-training.} \cite{blender}, leading to poor performance when a user mentions ``COVID-19''. As shown in Figure~\ref{fig:1a}, given an utterance ``I've tested positive for COVID-19'', Blender yields a bad response ``That's great news'' because it misunderstands the utterance by the word ``positive'', which poses a real challenge for building an accurate and robust generation-based chatbot. Existing methods leverage external knowledge to tackle the problem \cite{knowledge-grounded}, where chatbots retrieve relevant knowledge about the entities from a external knowledge base and use the retrieved knowledge to help generating appropriated responses. However, these methods heavily depend on the coverage of the knowledge base and the accuracy of knowledge retrieval, which may fail when the entity is not included by the knowledge base \cite{tnf} or the retrieved knowledge is inappropriate \cite{lian2019learning}. As shown in Figure~\ref{fig:1b}, the knowledge retriever fails to retrieve ``COVID-19'' from the knowledge base, yielding an incorrect response. According to our statistics, the knowledge retrieval failure is not rare in real practice. Taking Reddit as an example, we collect 407 dialogues over 40 topics on the Trendings panel and find that 24.8\% of the topic words are polysemous, indicating the probability of incorrect knowledge retrieval, and 47.9\% of topic words are not included by the Wikipedia. To date, there are few studies that have investigated how to build a dialogue generation model within which knowledge may be unavailable during inference. We solve this problem by proposing a knowledge enhanced fine-tuning method, trying to understand semantic information of entities based on the context. For example, given the sentence ``\textit{I want to submit a paper to EMNLP}", a person may not know what ``\textit{EMNLP}" is, but he/she can guess that it should be a conference or a journal, based on the context. Similarly, we aim to enhance the semantic representation of unseen entities by guiding the model to learn the meaning of the words only based on the context information. To achieve this, we take Blender~\cite{blender} as our backbone model, and propose two auxiliary training objectives (Figure~\ref{fig:1c}) in fine-tuning, dubbed as \textbf{K}nowledge \textbf{E}nhanced \textbf{Blender} (\textbf{KE-Blender}). The first objective is {\it Interpret Masked Word}, which predicts the word's definition based on the context, where the definition is obtained from a knowledge base. The second is {\it Hypernym Generation}, which predicts the corresponding hypernym of the word given by WordNet. These two introduced training objectives force the model to learn semantic information from the external knowledge base during training, guessing the meaning of the unseen entity with its context, so as to better understand the input utterance and generate relevant responses during inference. Both training objectives do not require further human labeling, which makes it possible for extending to large-scale pre-training. Results on the Wizard of Wikipedia benchmark show that the proposed model brings performance improvement. The proposed method achieves 14.9 and 18.4 PPL on Wizard Test Unseen in the knowledge available setting and unavailable setting, respectively, which outperforms the Blender baselines (16.3 and 19.9 PPL). To further verify the effectiveness of our method in real-world scenarios, we collect 407 dialogues on the Reddit \textit{Trendings} panel, demonstrating the effectiveness of the proposed method in practice. We release our code and dataset at \url{https://github.com/Nealcly/KE-Blender}. \section{Related Work} \subsection{Knowledge Enhanced Pre-training} BAIDU-ERNIE~\cite{baidu-ernie} uses entity-level masking and phrase-level masking strategy to enhance knowledge into language model. THU-ERNIE~\cite{thu-ernie} incorporates contextual representations with separate KG embeddings. LUKE~\cite{luke} proposes an entity-aware self-attention to boost the performance of entity related tasks. SenseBERT~\cite{sensebert} uses WordNet to infuse the lexical semantics knowledge into BERT. KnowBERT~\cite{KnowBert} incorporates knowledge base into BERT using the knowledge attention. TNF~\cite{tnf} accelerates pre-training by taking notes for the rare words. Compared with these methods, which enhances the pre-trained encoder by utilizing named entities or knowledge base, we inject knowledge to improve the generation ability of seq2seq models given the unseen word. \subsection{Knowledge Grounded Dialogue Generation} With advances in deep learning, pre-trained language models have shown promising results in dialogue generation \cite{bart,dialogpt, blender}. To equip the models with external knowledge, \citet{persona} first show that adding user profile information is able to produce a more consistent and engaging response. \citet{wizard} propose a Transformer memory network to retrieve knowledge from Wikipedia. \citet{itdd} use two-step decoding, which first generate a response based on context, and then take the generated response and relative knowledge as input to generate a new response. \citet{skt} focus on knowledge selection in dialogue generation by utilizing a sequential latent variable model. \citet{KDBTS} further enhance the selection module with the posterior information. \citet{knowledgeGPT} use reinforcement learning to optimize knowledge selection with unlabeled data. Different from their work, our KE-Blender does not take knowledge as input, because knowledge is only used to enhance our model during training. \section{Method} \subsection{Task} Suppose that we have a training set $\mathbb{D}^S = \{\mathbf{U}^S_i, \mathbf{K}^S_i, \mathbf{R}^S_i\}|_{i=1}^{|L|}$, where $\mathbf{U}^S_i$, $\mathbf{K}^S_i$ and $\mathbf{R}^S_i$ are the dialogue context, the external knowledge retrieved from the knowledge base and the response, respectively. In addition to $\mathbb{D}^S$, we have a test dataset $\mathbb{D}^P=\{\mathbf{U}^P,\mathbf{R}^P\}$. Unlike $\mathbb{D}^S$, $\mathbb{D}^P$ does not contain external knowledge, because associated background knowledge for unseen word is difficult to obtain in real time during inference. Our goal is to learn a dialogue generation model $P(\mathbf{R}|\mathbf{U};\theta)$ with the help of $\mathbb{K}^S$, where $\theta$ is the parameters of the model. It should be noted that, the dialogue generation model $P(\mathbf{R}|\mathbf{U};\theta)$ generates the response $\mathbf{R}$ only based on the input context $\mathbf{U}$, without using knowledge $\mathbf{K}$ as input. In the following sections, we will introduce the model structure first, and then show how to leverage the external knowledge $\mathbf{K}$ to enhance the generation model $P(\mathbf{R}|\mathbf{U};\theta)$ with our two proposed training objectives. \begin{figure*} \centering \includegraphics[width=\textwidth]{method.png} \caption{An illustration of three training objectives in KE-Blender. {\tt [START]}, {\tt [MASK]}, {\tt [DEFI]} and {\tt [HYPE]} are special tokens for KE-Blender. } \label{fig:method} \end{figure*} \subsection{Baseline} \label{sec:baseline} We consider Blender and {\bf K}nowledge {\bf G}rounded {\bf Blender} (KG-Blender) as our baselines in knowledge available and knowledge unavailable settings, respectively. \paragraph{Blender} Given a dialogue context $\mathbf{U} =\{\mathbf{u}_1,...,\mathbf{u}_{l-1}\}$, we first concatenate $\mathbf{U}$ as a sequence of sentences $\mathbf{U} = \{x_1, x_2,\dots, x_T\}$. The response is denoted as $\mathbf{R} = \{y_1, y_2,\dots, y_{T'}\}$. We train our model on the basis of Blender, which is a standard Seq2Seq Transformer architecture with pre-training. In particular, we feed the dialogue context $\mathbf{U}$ to the encoder of the transformer, and then we obtain hidden representations of the sentence \begin{equation} \mathbf{h}^{enc} = \textsc{Transformer\_Encoder}(\mathbf{U}) \label{eq:encoder} \end{equation} At the $t$ th step of the decoder, $\mathbf{h}^{enc}$ and previous output tokens $y_{1:t-1}$ are then as inputs, yielding a representation using attention \cite{transforms} \begin{equation} \mathbf{h}^{dec}_t = \textsc{Transformer\_Decoder}(\mathbf{h}^{enc}, y_{1:t-1}) \end{equation} The generative probability distribution of $y_t$ is given by \begin{equation} p(y_t|\mathbf{U},y_{1:t-1}) = softmax (\mathbf{W}^o \mathbf{h}^{dec}_t + \mathbf{b}^o) \end{equation} where $\mathbf{W}^o$ and $\mathbf{b}^o$ are trainable parameters. We use the standard Maximum Likelihood Estimation to optimize the model parameters $\theta$. Given a training pair $(\mathbf{U},\mathbf{R})$, we minimize: \begin{equation} \mathcal{L}_{dialogue} = - \sum_{t=1}^{T'} \log p(y_t|\mathbf{U},y_{1:t-1}) \label{eq:dialogue_loss} \end{equation} We adopt Blender-90M \cite{blender} to initialize our Seq2Seq Transformer model, which has been pre-trained on 1.5B training examples from Reddit 2019. \paragraph{Knowledge Grounded Blender} One intuitive baseline to use knowledge is to take both the context and the knowledge as input. In particular, the concatenation of the context $\mathbf{U}$ and the associated knowledge $\mathbf{K}$ is fed to the transformer encoder: \begin{equation} \begin{split} &\mathbf{h}^{enc'} = \textsc{Transformer\_Encoder}([\mathbf{U};\mathbf{K}]) \\ &\mathbf{h}^{dec'}_t = \textsc{Transformer\_Decoder}(\mathbf{h}^{enc'}, y_{1:t-1}) \\ & p(y_t|\mathbf{U},\mathbf{K},y_{1:t-1}) = softmax (\mathbf{W}^o \mathbf{h}^{dec'}_t + \mathbf{b}^o) \end{split} \end{equation} Similar to Eq~\ref{eq:dialogue_loss}, given a training pair $(\mathbf{U},\mathbf{K},\mathbf{R})$, the loss function is \begin{equation} \mathcal{L}_{dial\_know} = - \sum_{t=1}^{T'} \log p(y_t|\mathbf{U},\mathbf{K},y_{1:t-1}) \end{equation} Note that it is difficult to use KG-Blender directly when knowledge is unavailable, because KG-Blender relies knowledge as input. \subsection{Knowledge Enhanced Blender} To build a robust model for knowledge unavailable setting, we consider adding two auxiliary loss during fine-tuning. People try to understand an unseen word based on the context, even if a dictionary is unavailable. To simulate this behavior, we explicitly guide the Blender model to learn the meaning of words only based on the context information. \paragraph{Interpret Masked Word} The first objective is to ask the model to restore the definition of masked words. We can use different methods to select which words should be masked. For example, we could mask proper nouns in the utterance, or pre-defined topic word for specific dataset\footnote{Wizard of Wikipedia dataset have defined topic words for each dialogue.}. For example, the input text is \textit{``I submit a paper to the EMNLP''}. ``\textit{EMNLP}'' is replaced by {\tt [MASK]}, yielding \textit{``I submit a paper to the {\tt [MASK]}''}. The definition retrieved from Wikipedia is ``\textit{EMNLP is a leading conference in the area of natural language processing and artificial intelligence }''. Then, the pre-trained model is required to restore the definition by consuming the masked utterance as input. In this way, the model is explicitly guided to understand the background knowledge of the masked word given the context. Formally speaking, given a single utterance $\mathbf{u}_{l-1} = \{x_1, x_2,\dots, x_T\}$, we assume that $x_i$ is the topic word in $\mathbf{u}_{l-1}$, and its corresponding definition is denoted as $\mathbf{K}_{x_i}=\{k_1,k_2,\dots,k_{|K_{x_i}|}\}$. We use the special token {\tt [MASK]} to replace $x_i$ yielding $\mathbf{u}'_{l-1} = \{x_1,\dots,x_{i-1},${\tt [MASK]}$, x_{i+1},\dots,x_T'\}$ as the input of Eq~\ref{eq:encoder} in Section~\ref{sec:baseline}. To distinguish with the original dialogue generation task, we use a specific start token {\tt [DEFI]} to mark that the target sequence is the definition. Given a training pair $(\mathbf{u}'_{l-1},\mathbf{K}_{x_i})$, the training objective of the interpret masked word is: \begin{equation} \mathcal{L}_{interpret} = - \sum_{t=1}^{|K_{x_i}|} \log p(k_t|\mathbf{u}'_{l-1},k_{1:t-1}) \end{equation} \paragraph{Hypernym Generation} We also reconstruct the input utterance by replacing the topic words with the corresponding hypernym. Compared with topic words, the semantic field of its hypernym is more general. We use WordNet to construct our training instances. For instance, given an utterance $\mathbf{u}_{l-1}=$ \{\textit{I submit a paper to the EMNLP}\}, we use ``\textit{conference}'' to replace ``\textit{EMNLP}'', where ``\textit{conference}'' is the hypernym of ``\textit{EMNLP}'', yielding the target sequence $\mathbf{u}''_{l-1}=$ \{\textit{I submit a paper to the conference}\}. This training objective aims to guide the model to understand the semantic information of unseen words. We use a specific start token {\tt [HYPE]} to mark the target sequence is the hypernym generation. Given a training pair $(\mathbf{u}_{l-1},\mathbf{u}_{l-1}'')$, the training objective of the hypernym generation is: \begin{equation} \mathcal{L}_{hypernym} = - \sum_{t=1}^{|u''_{l-1}|} \log p(y''_t|u_{l-1},y''_{1:t-1}) \end{equation} \paragraph{Training} We optimize the dialogue generation loss with the two external loss at the same time: \begin{equation} \small \mathcal{L} = \sum_{i=1}^{|L|} \mathcal{L}^i_{dialogue} + \sum_{i=1}^{|K|} \mathcal{L}^i_{interpret} + \sum_{i=1}^{|H|} \mathcal{L}^i_{hpernym} \end{equation} where $|K|$ and $|H|$ represent the number of training instances for {\it Interpret Masked Word} and {\it Hypernym Generation}, respectively. \paragraph{Inference} During inference, we only take the context as input if the additional retrieved knowledge is unavailable. Following~\citet{knowledgeGPT}, we adopt greedy search to select the highest probability token at each time step. We denote our model as {\bf K}nowledge {\bf E}nhanced {\bf Blender} (KE-Blender) for the remaining of this paper. \section{Experiments} \subsection{Datasets} {\bf Wizard of Wikipedia} \cite{wizard} is a knowledge aware chit-chat dialogue benchmark, where each instance has an initial topic given by two annotators. The dataset contains 18,430 training dialogues with 1,365 topics, and each topic is linked to a Wikipedia article. Its test set is split into Test Seen and Test Unseen based on whether the topic is appear in the training set. We evaluate our methods with several baselines on both Test Seen and Test Unseen. There are 148,357 training instances in the Wizard of Wikipedia training set. To enhance knowledge into the model, we further construct 65,072 training pairs for interpret masked word based on Wikipeida and 86,612 training pairs for hypernym generation based on WordNet. {\bf Reddit Trendings} is a test set to simulate real-world settings, by crawling users' dialogue from its Trendings panel in 2021. Reddit Trendings panel contains the latest hot topics, and most of them are not included in the external knowledge bases. We first obtain topic words from the Reddit Trendings panel, then crawl the dialogue based on the topic words. We further filter the datasets by selecting out dialogue that includes at least 2 utterances, yielding a dataset which similar to the Wizard setting. Finally, the dataset consists of 407 utterances over 40 trending topics. \subsection{Setup} We implement KE-Blender with {\tt transformers} and choose {\tt blenderbot-90M} as the pre-trained language model. AdamW with a batch size of 128 is used to optimize parameters. The initial learning rate is set as 1e-5, which is halved in each training iteration. We set the maximum input tokens as 512. To ensure that KE-Blender also works well in knowledge available settings, we also create extra training instances by concatenating the context with the associated knowledge as input. \subsection{Baselines} We compare KE-Blender with Blender and KG-Blender, also drawing the following state-of-the-art methods as reference: {\bf Transformer} \cite{transforms} is a standard transformer model for dialogue generation. It takes the concatenation of context utterances and the associated knowledge as input. {\bf SKT} \cite{skt} uses a sequential latent variable model for knowledge selection, and then generates the response based on the context and the selected knowledge. {\bf DRD} \cite{drd} is a pre-training model designed for the low-resource dialogue generation, which decomposes the decoder into independent components. {\bf SKT + GPT-2} \cite{knowledgeGPT} feeds the knowledge selected by SKT to GPT-2 for dialogue response generation. {\bf SKT + PIPM + KDBTS} \cite{KDBTS} uses posterior information to help prior knowledge selection module, and trains the decoder with knowledge distillation. {\bf KnowledGPT} \cite{knowledgeGPT} adopts reinforcement learning to optimize the knowledge selection module, which gives state-of-the-art performance on Wizard. {\bf Blender-FT.} Blender is a large-scale dialogue pre-training model. We fine-tune the Blender on Wizard training set without utilizing external knowledge. {\bf KG-Blender.} We fine-tune Blender on the Wizard training set by concatenating the context and the associated knowledge as the input. In the setting where external knowledge is unavailable, only context is used to generate response. \begin{table*}[t!] \centering \small \begin{tabular}{c|c|c|c|c|c|c} \toprule \multirow{2}{*}{{\bf Model}} & \multicolumn{2}{c|}{{\bf Test Seen}} & \multicolumn{2}{c|}{{\bf Test Unseen}} & \multicolumn{2}{c}{{\bf Performance Gap}} \\ \cmidrule(r){2-7} & {\bf PPL} & {\bf F1} & {\bf PPL} & {\bf F1} & {\bf PPL} & {\bf F1} \\ \midrule \multicolumn{7}{c}{\bf w/ knowledge during inference} \\ \midrule Transformer MemNet \cite{wizard} & 66.5 & 15.9 & 103.6 & 14.3 & 37.1 & 1.6 \\ SKT \cite{skt} & 52.0 & 19.3 & 81.4 & 16.1 & 34.6 & 3.2 \\ DRD \cite{drd} & 19.4 & 19.3 & 23.0 & 17.9 & 3.6 & 1.4 \\ SKT + GPT-2 \cite{knowledgeGPT} & 17.6 & 20.3 & 23.7 & 17.8 & 6.1 & 2.5 \\ SKT+PIPM+KDBTS \citet{KDBTS} & 42.7 & 19.9 & 65.7 & 17.6 & 23.0 & 2.3 \\ KnowledGPT \cite{knowledgeGPT} & 19.2 & {\bf 22.0} & 22.3 & {\bf 20.5} & 3.1 & 1.5 \\ \midrule KG-Blender $\dagger$ & 13.8 & 18.4 & 16.3 & 17.8 & 2.5 & 0.6 \\ KE-Blender (Ours) & {\bf 13.4} & 18.1 & {\bf 14.9} & 17.6 & {\bf 1.5} & {\bf 0.5} \\ \midrule \multicolumn{7}{c}{\bf w/o knowledge during inference} \\ \midrule Repeat last utterance & - & 13.8 & - & 13.7 & - & - \\ \midrule Blender-FT $\dagger$ & 16.1 & 16.5 & 19.9 & 12.9 & 3.8 & 3.6\\ KG-Blender $\dagger$ & 18.6 & 15.5 & 22.7 & 14.7 & 4.1 & 0.7 \\ KE-Blender (Ours) & {\bf 15.5} & {\bf 17.0} & {\bf 18.4} & {\bf 16.7} & {\bf 2.9} & {\bf 0.3} \\ \bottomrule \end{tabular} \caption{Performance on Wizard Test Seen and Wizard Test Unseen. Note that the lower PPL and the higher F1 indicate better generation model. ``Performance Gap'' represents the performance gap between Test Seen and Test Unseen, the lower Performance Gap indicates better generalization ability. $\dagger$ indicates our baseline implementation.} \label{tab:wizard} \end{table*} \begin{table}[t!] \centering \small \begin{tabular}{c|c|c|c|c} \toprule Model & R@1 & R@5 & R@10 & R@20 \\ \midrule Human Reference & 41.59 & 60.96 & 65.95 & 70.33 \\ \midrule \multicolumn{5}{c}{w/ knowledge during inference} \\ \midrule KG-Blender & 37.41 & 57.29 & 62.48 & 66.56 \\ KE-Blender & {\bf 39.14} & {\bf 58.72} & {\bf 62.70} & {\bf 67.18} \\ \midrule \multicolumn{5}{c}{w/o knowledge during inference} \\ \midrule Blender & 31.91 & 49.34 & 56.07 & 60.75\\ KG-Blender & 31.89 & 49.21 & 56.03 & 60.78 \\ KE-Blender & {\bf 32.11} & {\bf 51.58} & {\bf 57.29} & {\bf 63.03} \\ \bottomrule \end{tabular} \caption{Knowledge performance based on BERT-large on Wizard Test Unseen.} \label{tab:wizard-knowledge} \end{table} \begin{table}[t!] \centering \small \begin{tabular}{c|c|c|c|c} \toprule Model & Fluency & Know & Coherence & Kappa \\ \midrule \multicolumn{5}{c}{w/ knowledge during inference} \\ \midrule KG-Blender & {\bf 1.94} & 1.63 & 1.70 & 0.63 \\ KE-Blender & 1.93 & {\bf 1.65} & {\bf 1.74} & 0.64 \\ \midrule \multicolumn{5}{c}{w/o knowledge during inference} \\ \midrule Blender & {\bf 1.95} & 1.37 & 1.51 & 0.68\\ KG-Blender & 1.89 & 1.43 & 1.47 & 0.59 \\ KE-Blender & 1.92 & {\bf 1.62} & {\bf 1.70} & 0.65 \\ \bottomrule \end{tabular} \caption{Human Evaluation on Wizard Test Unseen. Know-Knowledgeable.} \label{tab:wizard-human} \end{table} \subsection{Metrics} \paragraph{Automatic evaluation metrics:} Following \citet{wizard} and \citet{skt}, models are measured using the perplexity of the ground-truth response (PPL) and unigram F1-score (F1). \begin{figure}[t!] \centering \includegraphics[width=0.5\textwidth]{berteval.png} \caption{The proposed BERT evaluation method.} \label{fig:eval_bert} \end{figure} \citet{bert-evaluate} show that BERT can be used to evaluate the generated response. We employ BERT-based evaluation metrics to evaluate whether the generated response is knowledgeable as supplements to PPL and F1. As shown in Table~\ref{fig:eval_bert}, the dialogue generation model is first required to generate response $\hat{\mathbf{R}}$ based on the dialogue context $\mathbf{U}=\{\mathbf{u}_1,\dots,\mathbf{u}_{l-1}\}$. We use the special token {\tt [MASK]} to replace the topic word in the last context utterance $\mathbf{u}_{l-1}$. Then a masked language model (i.e. BERT-large) is used to predict the masked topic word using the last context utterance $\mathbf{u}_{l-1}$ and the generated response $\hat{R}$. The recall$@k$ for the masked language model is used to measure the knowledge stored in the dialogue generation model. Intuitively, if a dialogue generation model is more knowledgeable, the masked language model is stronger to predict the masked topic word based on the generated response $\hat{\mathbf{R}}$ and last context utterance $\mathbf{u}_{l-1}$. \paragraph{Human evaluation metrics:} Manual evaluations are essential for evaluating dialogue generation \cite{human-eval}. We conduct human evaluations to compare KE-Blender with our baseline Blender and KG-Blender by randomly sampling 200 instances from the Wizard Test Unseen. We define three metrics for manual evaluation, including fluency, knowledgeability and coherence. Each aspect is scored into three grades, 0, 1 and 2, representing “bad”, “normal” and “good” respectively. Following~\citet{wu2018response}, we employ three annotators to do a side-by-side human evaluation, and report the Fleiss Kappa \cite{fleiss1971mns} to show the agreement among human annotators. \subsection{Results} Table~\ref{tab:wizard} reports automatic results on the Wizard of Wikipedia dataset. \paragraph{Test Seen vs Test Unseen} Compared with Test Seen, all models perform worse on Test Unseen, especially where knowledge is unavailable. For example, the Blender-FT only achieves F1 scores of 16.5 and 12.9 on Test Seen and Test Unseen, respectively. Compared with several baselines, KE-Blender gives the lowest performance gap, suggesting that KE-Blender is more robust when it comes to Test Unseen. \paragraph{w/ Knowledge During Inference} Previous work \cite{skt, knowledgeGPT} focuses on how to better leverage knowledge for dialogue generation. Compared with these strong baselines, KE-Blender performs competitively in the knowledge-available setting, even though KE-Blender is designed for knowledge-unavailable setting. Notably, it achieves the best reported PPL on Wizard. The results are consistent with our intuition. Knowledge grounded methods perform well when knowledge is provided during inference, and our method is robust and does not degrade in the w/ knowledge setting. \begin{table}[t!] \centering \small \begin{tabular}{c|c|c} \toprule Model & PPL & F1 \\ \midrule KE-Blender & {\bf 18.36} & {\bf 16.73} \\ w/o Interpret & 18.75 & 16.29\\ w/o Hypernym & 18.95 & 16.27 \\ Blender & 19.87 & 12.91 \\ \bottomrule \end{tabular} \caption{Ablation study on the Wizard Test Unseen when knowledge unavailable.} \label{tab:ablation} \vspace{-0.5cm} \end{table} \begin{figure} \centering \includegraphics[width=0.5\textwidth]{percent.png} \caption{Model performance when part of knowledge is available during inference. 90\% indicates the 90\% of instances are knowledge available.} \label{fig:percent} \end{figure} \begin{table*}[t!] \centering \small \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c} \toprule \multirow{2}{*}{Setting} & \multirow{2}{*}{\%} & \multicolumn{3}{c|}{\bf w/ knowledge} & \multicolumn{3}{c|}{\bf w/o knowledge} & \multicolumn{3}{c}{{\bf Performance Gap}} \\ \cmidrule{3-11} && KE & KG & Blender & KE & KG & Blender & KE & KG & Blender \\ \midrule None & 47.9 & {\bf 57.5} & 62.2 & 90.3 & {\bf 57.5} & 62.2 & 90.3 & \ \ 0.0 &\ \ 0.0 & \ \ 0.0 \\ Invalid & 24.8 & {\bf 58.2} & 66.8 & 80.1 & {\bf 51.1} & 56.3 & 90.6 & -7.1 & -10.5 & -10.5 \\ Valid & 27.3 & {\bf 53.8} & 57.6 & 93.6 & {\bf 53.5} & 56.9 & 88.0 & \ \ 0.3 & \ \ 0.7 & -13.6 \\ Overall & 100 & {\bf 56.6} & 61.8 & 88.3 & {\bf 54.7} & 59.3 & 89.4 &\ \ 1.9 &\ \ 2.5 & 1.3 \\ \bottomrule \end{tabular} \caption{Model Performance (PPL) on Reddit Trendings. KE - KE-Blender, KG - KG-Blender. ``None'', ``Invalid'' and ``Valid'' are three subset of the test set, which indicates knowledge can not be retrieved, knowledge can be retrieved but it is incorrect, and gold knowledge is available, respectively. \% represents the percent of instances on test set. ``Performance Gap'' represents the performance gap between w/ knowledge and w/o knowledge. The ``Performance Gap'' close to zero indicates the model does not depend on external knowledge.} \label{tab:reddit} \end{table*} \vspace{-0.2cm} \paragraph{w/o Knowledge During Inference} When external knowledge is unavailable during the inference stage, knowledge grounded methods cannot be directly applied to this setting since it requires knowledge as an input. Hence, we compare KE-Blender with Blender and KG-Blender. As can be seen from Table~\ref{tab:wizard}, our method shows large advantages in all metrics, achieving a 16.7 F1 score. It shows that our external training objectives can help model to generalize better when meet unseen words. \paragraph{BERT Evaluation} Table~\ref{tab:wizard-knowledge} shows the recall of masked topic words predicted by a BERT model, where a higher recall score indicates the stronger correlation between the knowledge and the response. Human's response obtains a higher score, which means our evaluation metric is reasonable and there is still a gap between human's reply and machine's reply. Our method gives the best performance in both settings, demonstrating strong performance when knowledge is absent, which shows that our auxiliary training objectives is able to help model to learn a better semantic representation. Surprisingly, it also outperforms simple knowledge grounded methods when knowledge is available. \paragraph{Human Evaluation} Table~\ref{tab:wizard-human} compares KE-Blender with baselines using human evaluation. All models are able to produce fluent response due to the power of pre-training. Inference with the retrieved knowledge is particularly helpful for the model to generate a more knowledgeable and coherent response. When knowledge is unavailable, KE-Blender significantly outperforms Blender and KG-Blender ($p$\textless0.01) measured in both knowledgeable and coherent, also giving highly competitive results with the model using knowledge as input. The value of Fleiss’ Kappa \cite{fleiss1971mns} exceed 0.59 on all models, showing a high inter-rater agreement among annotators. \begin{table*}[t!] \centering \small \begin{tabular}{c|c} \toprule \multicolumn{2}{c}{\bf Dialogue Generation} \\ \midrule Speaker A & Hey! I enjoy Elvis music, do you like his music? \\ Speaker B & Yes, I love to listen his music. He was not just a singer, he was an actor too. \\ Speaker A & Oh, I didn't know that! Do you know any movies he acted in? \\ \midrule \multicolumn{2}{c}{\bf w/o knowledge during inference} \\ \midrule Blender-FT & Oh wow, that's a long time ago! I'm sure it's been around for a long while. \\ KE-Blender & I know he was in a lot of movies, he was also in a few TV shows. \\ \midrule \multicolumn{2}{c}{\bf w/ knowledge during inference} \\ \midrule \multirow{2}{*}{Knowledge} & Elvis Aaron Presley was an American singer, musician, and actor. Jailhouse Rock is a American musical \\ & drama film directed by Richard Thorpe and starring Elvis Presley, Judy Tyler, and Mickey Shaughnessy. \\ \midrule KG-Blender & He was in a movie called jailhouse rock. It was about a young man who was mentored in music by a prison cellmate. \\ KG-Blender & He was in a movie called jailhouse rock. It was a really good movie. \\ \bottomrule \end{tabular} \caption{Examples of generated responses on the Wizard of Wikipedia Test Unseen.} \label{tab:case1} \end{table*} \begin{table}[t!] \centering \small \begin{tabular}{c|c} \toprule \multicolumn{2}{c}{Interpret Masked Word} \\ \midrule \multirow{2}{*}{In} & I never realized that Instagram is \\ & owned by {\tt [MASK]}, did you? \\ \midrule \multirow{2}{*}{Out} & Facebook is an American online social media \\ & and social networking service company. \\ \midrule In & I really like {\tt [MASK]}. But blue is also a nice color. \\ Out & Purple is a color intermediate between blue and red. \\ \midrule \multicolumn{2}{c}{Hypernym Generation} \\ \midrule In & What else you know about \underline{bowling}? \\ Out & What else you know about \underline{ball game}? \\ \midrule In & I'm sorry to hear that, I have no \underline{pets}. \\ Out & I'm sorry to hear that, I have no \underline{animals}. \\ \bottomrule \end{tabular} \caption{Examples of generated definition and hypernym on the Wizard of Wikipedia Test Unseen. The knowledge does not exist in the training set. ``In'' and ``Out'' denote the input and output of KE-Blender, respectively.} \label{tab:case3} \end{table} \paragraph{Low-Knowledge-Resource Setting} To simulate a low-knowledge-resource setting, we start from using the full knowledge in Wizard Test Unseen, and gradually reduce the amount of knowledge by randomly removing some entries. Figure~\ref{fig:percent} shows the trends when different percentage of knowledge in Test Unseen is removed. As the ablation knowledge increases, the performance of the two methods significantly decreases. The F1 of KG-Blender sharply decreases from 17.8 to 16.3. Compared with KG-Blender, the rate of decrease is much smaller for KE-Blender, which shows the effectiveness of knowledge enhanced fine-tuning. \paragraph{Reddits Trendings} We train KE-Blender and KG-Blender on Wizard training set, and test on Reddits Trendings, taking off-the-shelf Blender as a reference. The results are reported in Table~\ref{tab:reddit}. Note that there is a domain gap between Wizard and Reddits, which leads to a worse performance on Reddits Trendings. KE-Blender achieves 56.6 and 54.7 PPL on w/knowledge and w/o knowledge settings, respectively, outperforming KG-Blender and off-the-shelf Blender in all settings. When invalid knowledge is used as input, KG-Blender achieves 66.8 PPL in w/knowledge setting, which underperforms w/o knowledge setting (56.3 PPL). This shows that the inappropriate knowledge selection has a destructive impact on models \cite{lian2019learning}. Integrating with valid knowledge, both models are able to generate more informative responses. Furthermore, KE-Blender gets the best performance gap, which confirms that KE-Blender does not rely on external knowledge base, demonstrating the effectiveness of the proposed auxiliary training objectives. \section{Analysis} \paragraph{Ablation Study} An interesting question is to explore the contribution of the two auxiliary losses in training. The results are shown in Table~\ref{tab:ablation}. We can see that each loss contributes a lot in automatic evaluation, with F1 increasing largely by adding each objective. When combining the two losses, there is still an improvement but marginal, which indicates the two loss may play similar roles for pre-training model. \paragraph{Case Study} Table~\ref{tab:case1} shows an example of the model responses on the Wizard of Wikipedia Test Unseen. Under the knowledge-available setting, all models generate reasonable responses with the help of relevant knowledge. Both models mention that ``Elvis'' was in ``jailhouse rock'' by consulting the external knowledge base. When knowledge is unavailable, Blender-FT gives a non-informative response because it cannot understand the word ``Elvis''. In contrast, KE-Blender shows superior performance by producing informative and knowledgeable responses, which directly points out that ``Elvis'' appears in a lot of movies and also in a few TV shows. This case shows that our model can significantly improves response quality when knowledge is absent, while sustain good performance when knowledge is available. \paragraph{Knowledge Mining} Although we add two additional tasks in training, it is unclear how well the model performs in these two tasks. Therefore, we further evaluate whether explicit knowledge can be recovered from our model given the unseen entity. First, we find that the perplexity of the ground-truth Wikipedia knowledge on Test Unseen is only 6.81. As shown in Table~\ref{tab:case3}, our model is able to produce reasonable definition based on context information and the pre-trained knowledge, and generate hypernyms for a given word associated with context. These show that rich-knowledge is stored in KE-Blender during knowledge enhanced fine-tuning, which potentially allows us to ground open domain dialogues without external knowledge. \section{Conclusion} We presented KE-Blender for better handling response generation based on unseen words, which enables a model to generate knowledgeable response without external knowledge during inference. To explicitly inject the knowledge into the model, we proposed two training objectives, including interpret masked word and hypernym generation. To simulate real-world scenario, we also released a test set on Reddit Trendings. Results on Wizard and Reddit Trendings show that KE-Blender outperforms several state-of-the-art methods and strong baselines in settings both when external knowledge is available and unavailable. \section*{Acknowledgments} We would like to thank the anonymous reviewers for their constructive comments, and Yulong Chen, Jingyi Liao and Sen Yang for insightful discussion and proofreading. Yue Zhang is the corresponding author.
{'timestamp': '2021-09-14T02:21:37', 'yymm': '2109', 'arxiv_id': '2109.05487', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05487'}
arxiv
\section*{Acknowledgements} \bibliographystyle{IEEEtran} \section{Introduction} \label{sec:introduction} In the last decade, advancement in robotic grasping has enabled robots to automatically grasp a never-before-seen range of objects. However, most of the works on grasp synthesis still assume specific object properties such as uniform friction or rigidity. These assumptions do not hold for multi-material \cite{tran_friction} or deformable objects and can lead to unsuccessful grasping in real-world scenarios. \begin{figure}[!t] \centering \subfloat[Unsuccessful grasp executed on a rigid triangular-shaped object.]{ \label{subfig:titlehard} \includegraphics[width=.9\linewidth]{figures/title_hard.png} } \\ \subfloat[Successful grasp executed on a deformable triangular-shaped object.]{ \label{subfig:titlesoft} \includegraphics[width=.9\linewidth]{figures/title_soft.png} } \caption{The robot executes the same grasp candidate on two objects with similar shapes but different stiffness. While the rigidity of the object tried to push itself out of the gripper (a), the deformation of the deformable object in (b) gently conformed to the shape of the gripper that leads to a successful grasp.} \label{fig:title} \vspace{-0.5cm} \end{figure} Grasping non-rigid objects, on the other hand, is difficult because objects deform under interaction forces meaning that the 3-D contact locations also depend on the forces exerted on the object. Furthermore, the effect of the deformation varies across deformable objects and tasks. In some scenarios, such as grasping a water bottle, it is useful to minimize the object's deformation not to dislodge the liquid. While for other objects, such as the triangular-shaped object shown in \figref{fig:title} one can take advantage of the deformation to grasp them successfully. To date, most of the existing works only focus on minimizing the object deformation \cite{alt_minimize,xu_minimalwork,pan_minimizedeform,delgado_minimize,soft_minimize}. Although there exist few works that take advantage of the deformation \cite{lin_v,lin_feel3d}, they mainly focus on proposing control strategies given an initial grasp configuration. Thus, it is still an open question of how object stiffness affects the choice of grasp configuration and how to harness object deformation to generate better grasps. To address the aforementioned open issues, we propose to incorporate stiffness as an additional input to a state-of-the-art deep grasp planning pipeline as shown in \figref{fig:pipeline}. Our system generates a grasp candidate and corresponding grasp quality for every pixel given an input depth image and a \textit{stiffness image}. The model outputs can be reprojected into 3D space when combined with depth information, allowing a robot to execute a generated grasp in the real world. We qualitatively evaluated the proposed grasp synthesis method on a Franka Emika Panda\xspace robot in simulation and the real world by comparing it to a method that ignores stiffness. In the simulator, we evaluated over 2800 grasps on a shake and twist task, measuring, respectively, the grasp's robustness to linear and angular disturbances. In the real world, we measured the grasp success rate of 420 grasps on 14 objects under three different cases: with stiffness information, assuming all objects are rigid, and assuming all objects are deformable. In both simulation and the real world, our proposed approach demonstrates an improvement in grasp success rate. Furthermore, the approach can generate different grasping strategies for different stiffness values, such as pinching for soft objects and caging for hard objects, even though no pinch grasps were included in the training data. In summary, the main contributions of this paper are: \begin{itemize} \item The first generative stiffness-aware deep grasping approach that adapts the grasp location depending on the object's stiffness. \item The first stiffness-dependent image-based grasping dataset consisting of labeled top-down grasps on objects with varying stiffnesses. \item A thorough empirical evaluation of the proposed method presenting, both in simulation and on real hardware, improvements in terms of grasp ranking and grasp success rate over a method that ignores stiffness. \end{itemize} \section{Related work} \label{sec:related_work} To put our work in context, we next review three complementary viewpoints, grasping of deformable objects, data-driven grasp synthesis, and simulation of deformable object interactions. \subsection{Grasping Deformable Objects} Most recent research on deformable object manipulation has mainly focused on manipulating cloth items \cite{cloth_emd, cloth_imi,cloth_drl} and ropes \cite{rope_zhu,rope_bohg,rope_te}. Grasping deformable objects remains a sparsely explored research area \cite{defgraspsim} with the majority of works focusing on formulating quality metrics to quantify the goodness of a grasp \cite{wakamatsu_bfc,alt_minimize,xu_minimalwork,ken_deform} or proposing control strategies \cite{delgado_minimize,soft_minimize,lin_v,lin_feel3d}. Most approaches for grasping deformable objects aim to minimize the deformation. For a particular grasp, the minimization can be performed on-line by employing a control strategy that regulates the force at each contact \cite{delgado_minimize,soft_minimize}. To plan grasps, minimum deformation can be achieved by placing fingers at locations with maximal local stiffness, determined e.g.\ using simulation \cite{alt_minimize}. The deformation can also be integrated as an additional component of a wrench-space grasp quality metric \cite{xu_minimalwork}. In contrast to minimizing deformation, some works have proposed to utilize the object deformation, similar to this paper. Analytical grasp planning approaches following this line of study include bounded force closure \cite{wakamatsu_bfc} which guarantees force closure under a bounded external force, and deform closure \cite{ken_deform} which generalizes form closure to deformable objects with frictionless contact. In the on-line case, finger displacements can be regulated in order to retain force closure, originally proposed for planar objects \cite{lin_v} and later extended to 3D \cite{lin_feel3d} by using \ac{fem} to continuously model changes in shape and contact geometry during object lifting. Although \cite{lin_v,lin_feel3d} utilized object deformations for stable grasping, they focus on regulating either force or displacement of the fingers given an initial grasp configuration. This is in contrast to our work which focuses on the choice of the grasp configuration by taking advantage of the object deformation. \subsection{Data-driven Grasp Synthesis} Rapid advances in deep learning research recently have changed the paradigm of robotic grasping from analytical methods to data-driven ones. The main reason for this paradigm shift is that data-driven methods have been proved to be able to generate grasps that typically achieve a high grasp success rate on a wide range of objects in just a matter of seconds, much faster compared to analytical methods \cite{redmon15,mahler2017dex,morrison2018closing,vishal_deep,song_graspwild,jens19}. For example, Mahler \textit{et al.} \cite{mahler2017dex} used a dataset consisting of millions of synthetic antipodal top-grasp to train a Grasp Quality Convolutional Neural Network (GQ-CNN) model that computes the probability of success of grasps from depth images. The GQ-CNN was further improved through the use of on-policy data and a \ac{fcn} structure called FC-GQ-CNN \cite{fcn-gq-cnn}. The \ac{fcn} structure has recently been found to perform well in grasp synthesis \cite{fcn-gq-cnn,morrison2018closing,zeng_fcn,edward_fcn}, having the ability to generate dense, pixel-wise predictions for an input image efficiently. Although the aforementioned works achieve impressive results on rigid objects, none of them explicitly investigate the usability on deformable objects especially 3D deformable objects. In this work, we tackle this problem by incorporating object deformation into a state-of-the-art deep data-driven grasping planning pipeline. \subsection{Soft-body Simulation} Data-driven grasping requires training data, which in this work we generate in simulation. Simulating dynamics of deformable objects relies heavily on their geometric representations, for instance, particle representation is a good choice for simulating the dynamics of fluids. Yin \textit{et al.} \cite{yin_survey} presents three primary deformable object modelling approaches, \ac{mss}, \ac{pbd}, and \ac{fem}, and their limitations. In this work, we decided to use \ac{fem} because it is often used to model 3D objects such as food \cite{heiden2021disect} and tissues \cite{fem_tissue} and, compared to other modeling approaches, offers a more physically accurate representation of a deformable object in a continuous domain at the expense of computational cost. Some robotic simulators that support \ac{fem} are PyBullet\cite{pybullet}, SOFA\cite{sofa}, and NVIDIA's recent version of the Isaac Gym simulator \cite{isaacgym_ofi}, which supports soft body simulation through the NVIDIA Flex backend. Among the aforementioned simulators, Isaac Gym is chosen as it combines the advantages of the other two. Specifically, similar to SOFA, Isaac Gym includes a co-rotational linear model for precision in modeling and simulating the object deformation under interaction. Furthermore, similar to PyBullet, the Isaac simulator also provides the capability to integrate robot-related functions, making it easier to build robotic applications. Huang \textit{et al.} \cite{defgraspsim} also provides a grasping framework to automatically perform and evaluate grasp tests on an arbitrary target object. We use this framework in our work to generate training data and to test grasps. \section{{Experiments and Results}} \label{sec:exp_and_res} \begin{table*} \centering \ra{1.3}\tbs{7} \caption{\label{tb:sim_exp_summary}Average grasp success rate (\%) on different stiffnesses for two different tasks. The higher the better.} \begin{tabular}{@{}l|cccc|cccc@{}} \toprule & \multicolumn{4}{c|}{Shake task} & \multicolumn{4}{c}{Twist task} \\ \multicolumn{1}{c}{Stiffness ($\mathbf{E}$)} & \multicolumn{2}{c}{Common} & \multicolumn{2}{c|}{EGAD!{}} & \multicolumn{2}{c}{Common} & \multicolumn{2}{c}{EGAD!{}} \\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(lr){6-7} \cmidrule(lr){8-9} & With stiffness & No stiffness & With stiffness & No stiffness & With stiffness & No stiffness & With stiffness & No stiffness\\ \midrule $2\cdot 10^4$ & 75.4 & 22.8 & 67 & 40.8 & 65.7 & 20 & 69.5 & 51.3\\ $2\cdot 10^5$ & 88.5 & 38.5 & 77.4 & 68.6 & 74.2 & 40 & 80 & 65.2\\ $2\cdot 10^6$ & 88.5 & 48.5 & 77.4 & 69.6 & 71.4 & 42.8 & 75 & 64.4\\ $2\cdot 10^9$ & 51.4 & 46.2 & 51.3 & 51.3 & 40 & 31.4 & 41.7 &41.7\\ All stiffnesses & \textbf{75.9} & 40.3 &\textbf{68}& 57.6 &\textbf{63.5} & 34 & \textbf{67.3} & 55.6 \\ \bottomrule \end{tabular} \label{tab:simresult} \vspace{-1.2em}{} \end{table*} The experiments address the following three questions: \begin{itemize} \item Can \textit{Def-GG-CNN}\xspace synthesize high-quality grasps for deformable objects and would they succeed in simulation? \item Is \textit{Def-GG-CNN}\xspace robust against errors in the stiffness input? \item Can \textit{Def-GG-CNN}\xspace, trained purely on synthetic data, generate successful grasps in the real world? \item How does the stiffness information affect the choice of the grasp configuration? \end{itemize} \subsection{Grasping in Simulation} To investigate the quality of synthesized grasps in simulation, we evaluated the approach on two sets of objects: 7 common objects shown in \figref{fig:testobj}, and 28 adversarial objects from the recent EGAD! test dataset \cite{egad}. For each object and stiffness, we evaluated the five grasps with the highest quality on a \textit{shake task}\xspace and \textit{twist task}\xspace. While the \textit{shake task}\xspace measures how easily an object slips out of the gripper under linear accelerations, the \textit{twist task}\xspace measures that under angular accelerations. A grasp is successful if the object is in the gripper during the whole procedure, the grasp can withstand the linear acceleration limit of 25 $m/s^2$, and the angular acceleration limit of 500 $rad/s^2$. By doing this, we can quantify how the generated grasps behave under different disturbances. To demonstrate the importance and the effect of stiffness input, we compared the stiffness-aware grasps against grasps generated with an identical approach without stiffness information. In total, this amounts to 1400 grasps per method. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/testobjwhite.png} \caption{The seven common objects used in the experiment. All objects are single-material except for object 7, where the stiffness of its red part can vary.} \label{fig:testobj} \vspace{-0.5cm} \end{figure} \tabref{tab:simresult} shows the simulation result of both test sets. We can see that the proposed approach that takes stiffness input into account achieves a higher grasp success rate across all object sets and disturbances. It is noteworthy , however, that although we trained the network on the quality metrics from the \textit{shake task}\xspace, the generated grasps also performed well on the \textit{twist task}\xspace. Focusing on the \textit{shake task}\xspace results, the average grasp success rate using our approach over all stiffnesses compared to the baseline is 35\% higher on the Common objects and 11\% higher on EGAD! objects. Moreover, the performance of the baseline approach deteriorates significantly when moving from a high to a low value of Young's modulus. For instance, on the Common test set, the relative performance drop for the baseline approach when changing the Young's modulus from $2\cdot 10^6$ to $2\cdot 10^5$ is 10\%, and from $2\cdot 10^6$ to $2\cdot 10^4$ the drop is 26\%. This decline is much higher compared to the 0\% and 13\% drop using our approach. Similar performance differences are also observed for the EGAD! test set. The primary reason the baseline approach witnesses a higher performance drop is because it generates the same grasps for a target object regardless of its stiffness. Although the generated grasps often picked the objects successfully, they usually slip away from the gripper during the shake or twist task. In contrast, the network that took the stiffness input into account learned to avoid areas with a high probability of slippage, resulting in a higher grasp success rate. In addition, it is noteworthy that there is also some deterioration with the highest stiffness ($2\cdot 10^9$) for both approaches. The primary reason is that some objects in both test set have very complex shape which are extremely hard to grasp when they are rigid. This observation strengthen the idea of taking advantage of object deformation to successfully grasp complex-shaped objects. We also evaluated the models on the multi-material object 7 shown in \figref{fig:testobj}, where the stiffness of the red part could differ from the blue part. The result showed that if we assumed object 7 is entirely rigid, the method could not generate any good grasps on it. However, if we assumed the red part was softer than the blue part, we could generate successful grasps that usually aimed for the softer area of the object. This simple example demonstrates the benefit of planning stiffness-aware grasps on irregular-shaped multi-material objects. \subsection{Sensitivity Analysis} \begin{figure}[t] \centering \input{figures/sensitivity_analysis.tikz} \caption{Grasp success versus error in stiffness information. Grasp success deteriorates smoothly when the stiffness information is imprecise.} \label{fig:sensitivity_exp} \vspace{-1em} \end{figure} To examine the robustness of the results of our approach in the presence of uncertainty, we conducted a sensitivity analysis where we introduce uncertainty to the input stiffness images by varying the stiffness parameter , \textit{i.e.}, Young's modulus across an error range of [-60\%, +60\%]. We then evaluated the generated grasps on the Common test set under the \textit{shake task}\xspace. \figref{fig:sensitivity_exp} shows the result of the sensitivity analysis. We can see that the grasp success rate decreases consistently with increasing error, but that small errors in the range of 5-15\% have only limited negative effect on the performance. This experiment indicates that our method is robust against some errors in expected stiffness, which suggests potential for real-world application even when the stiffness is not precisely known. \subsection{Grasp Transfer to Physical Robot} \begin{figure} \centering \includegraphics[width=.9\linewidth]{figures/testobjreal.png} \caption{The 14 individually numbered objects used in the real experiment. The top, middle, and bottom rows include objects with high, medium, and low stiffness, respectively. } \label{fig:testobjreal} \vspace{-0.5cm} \end{figure} \begin{figure*} \centering \input{figures/real_result.tikz} \vspace{-1em} \caption{Grasp success rate per object in three cases. The last column shows the average success rate for all three cases.} \label{fig:realresult} \vspace{-1em} \end{figure*} \begin{figure}[!t] \centering \subfloat[Pinch grasp on soft sponge $\mathbf{E} = 2\cdot 10^5$.]{ \label{subfig:pinch} \includegraphics[width=.9\linewidth]{figures/real_sponge_soft_fingers.png} } \\ \subfloat[Cage grasp on rigid sponge $\mathbf{E} = 2\cdot 10^9$.]{ \label{subfig:cage} \includegraphics[width=.9\linewidth]{figures/real_sponge_hard_fingers.png} } \caption{Stiffness input image, along with grasp quality map and best synthesized grasp candidate indicated by two white fingers. For stiffness input image, the darker the color the stiffer the object is. For the grasp quality map, red indicates higher quality, and the green point denotes the best grasp.} \label{fig:graspstrategies} \vspace{-2em} \end{figure} To investigate how well the synthesized grasps perform in real world, we evaluated the grasp success rate on a Franka Emika Panda\xspace equipped with a parallel-jaw gripper. This allows us to study if grasps generated with the approach trained only on synthetic data transfer to real objects. 14 objects to grasp (\figref{fig:testobjreal}) were chosen as they represent a high variation in size, shape, and stiffness. We used an Intel RealSense D345 camera mounted to the robot's wrist to capture the RGB-D image. In addition to depth image, we also need to provide a stiffness image of the object. To do this, we segmented the object from the scene by subtracting the background and the table from the image and then assigning the same stiffness value to each pixel that the object occupied. We manually set the magnitude of stiffness for each object according to its perceived stiffness. The best grasp pose is then computed using the proposed method. The robot executed the best grasp by moving to a pre-grasp position approximately 25 mm above the grasp. Then, the robot moves linearly downwards until reaching the grasp pose or contact with the table is detected. From there, the robot closes its gripper, lifts the object, performs a predefined trajectory, and finally places an object at the goal position. A grasp is successful if the robot can pick the object and move it without dropping it. Otherwise, it is unsuccessful. To single out the effect stiffness input has on grasp performance for each object, we ran the experiments with three different stiffnesses: the correct one, only high, only low. For each object and stiffness, we randomly placed it ten times and evaluated the best grasp candidate. In total, this setup amounts to 420 grasps on 14 objects. The experimental results are presented in \figref{fig:realresult}. The results show that with the correct stiffness information, the grasp success rate of the proposed approach is approximately 17\% higher than when the stiffness is assumed to be either high or low. This result indicates that grasps generated on rigid objects do not necessarily transfer successfully to deformable objects and vice versa. For instance, if we assumed the deformable objects, such as objects 8, 9, 11, and 14, were rigid, many generated grasps were on specific parts of them, such as the arms or legs of the toy or wheel of the car. These grasps usually picked the object successfully but then, due to the deformation, dropped it when the robot started to accelerate. The same experiment on objects 6, 7 showed that grasps generated on the top or bottom of the object usually failed due to the elasticity of the object. If we instead assumed rigid objects, such as 1, 3, 4, 5, were soft, the network generated pinch grasps that failed due to collisions with the object. Some failed grasps are shown in \figref{fig:failandsuccess}a. One interesting finding was that given the correct stiffness information, the method was able to generate different grasping strategies depending on the stiffness of the object, as shown in \figref{fig:graspstrategies}. Specifically, in the case of the soft sponge \figref{fig:graspstrategies}a, the proposed method learned that the grasp quality is high across the whole objects thanks to their deformation, which in turn, enables pinch grasps. While in the case of a hard sponge \figref{fig:graspstrategies}b, the high-quality grasp tends to be generated at the center of the object, and the grasp width is almost as big as the object in order to successfully cage the object. \begin{figure}[!t] \centering \includegraphics[width=.9\linewidth]{figures/1stsuccess.png} \\ \vspace{-0.5 em} \subfloat[]{ \includegraphics[width=.9\linewidth]{figures/2ndsuccess.png} } \\ \includegraphics[width=.9\linewidth]{figures/fail_sponge.png} \\ \vspace{0.5 em} \includegraphics[width=.9\linewidth]{figures/fail_teddy.png} \\ \vspace{-0.5 em} \subfloat[]{ \includegraphics[width=.9\linewidth]{figures/fail_car.png} } \\ \caption{Some successful (a) and failed (b) grasps on the real robot.} \label{fig:failandsuccess} \vspace{-0.5cm} \end{figure} \subsection{Discussion} All experimental results show the benefit of generating stiffness-aware grasps. By comparing the proposed approach to the case where the stiffness information is ignored, we see that the proposed approach achieves higher grasp success rates. The primary reason for the difference in performance is that the object stiffness facilitates learning where to generate grasps that minimize the slippage caused by the deformation. If the object's stiffness was ignored, the network generated the same grasps regardless of the object stiffness. Together, these result backs the claim made in \cite{lin_feel3d} that grasps do not transfer well between rigid and deformable objects. Therefore, incorporating object stiffness in robotic grasping pipelines is beneficial when dealing with a wide range of unknown objects. Another interesting finding is that our approach can generate different grasp types such as pinch or cage grasps depending on the stiffness, even though there was no pinch grasps in the training dataset. This behavior is shown on object 6 in \figref{fig:graspstrategies}. Specifically, the sponge with a low Young's modulus admits pinching behavior where the grasp press on the object and pinch, while the hard sponge only admits caging grasps. One potential reason for such behavior is that the proposed network learned that the grasp quality is almost uniform across soft objects thanks to their deformation. Similar behaviors were also reported in \cite{sergey_handeye} where data was collected from 14 robots over the course of two months. However, it is worth pointing out that our approach learned to produce the same behavior on a completely synthetic dataset with orders of magnitude fewer data. Furthermore, our proposed approach provides more meaningful insights regarding the relationship between object deformation and grasps. \section{Conclusions and future work} \label{sec:conclusions} Grasping deformable objects has not been as well studied as rigid object grasping due to complexity in the modeling and simulating the dynamic behavior of such objects. However, with the rapid development of physics-based simulators that support soft bodies, the research gap between rigid and deformable objects is shrinking. To leverage the capability of such simulators and to challenge the rigidity assumption that has dominated robotic grasping, we presented an approach to synthesize grasps on objects with varying stiffness by a deep neural network trained on purely synthetic data. The key idea in this work is to integrate the object stiffness property into the grasp planning pipeline to study the relationship between the object deformation and the generated grasps. To train the proposed network, we generated our own training dataset using the Isaac Gym simulator. We demonstrated the performance of the generated grasps through experiments in both simulation and real-world scenarios on a wide range of objects with varying sizes, shapes, and stiffness. The results show a clear improvement in grasp success rate when taking stiffness property into account. Furthermore, the proposed approach shows the ability to generate different grasp strategies depending on object stiffness. The generalizability to objects with non-uniform stiffness remains open although the method should be able to account for all variability captured in the training data, making the simulation quality and efficiency a central bottleneck. The idea of exploiting deformations for grasping opens many interesting avenues. Our proposed method employs FEM simulations for which the computational cost may limit their use for general-purpose systems. Investigating the possibility to devise analytical quality measures that would exploit the deformations is an important future work. \section{Method} \label{sec:method} \subsection{Network} Our solution is based on the GG-CNN because it is orders of magnitude smaller than other recent grasping networks, thus it is faster to train and evaluate the network, while achieving state-of-the-art results in grasping rigid objects. We propose \textit{Def-GG-CNN}\xspace (\figref{fig:pipeline}), a fully convolutional network to synthesize grasps on objects with different stiffness including deformable ones. To enable \textit{Def-GG-CNN}\xspace to learn stiffness-dependent grasping strategies, it has, alongside the depth image, an additional stiffness image input. The stiffness image represents Young's modulus of the object at each pixel. The output of the network is the grasp map \textbf{G} that represents a grasp quality, and gripper parameters (orientation, gripper width) for each pixel of the depth image. The proposed network is trained with supervised learning on a synthetic dataset further explaned in \secref{sec:dataset}. \begin{figure}[tbp] \centering \def0.5\linewidth{\linewidth} {\fontsize{9}{8 \input{figures_tex/graspdeform_vertical.pdf_tex}} \caption{The proposed pipeline where stiffness information (highlighted in red box) is incorporated.} \label{fig:pipeline} \vspace{-0.5em} \end{figure} \subsection{Grasp map representation} Each pixel in the grasp map \textbf{G} represents a 4-dof grasp. We use the same representation of \textbf{G} as defined in \cite{morrison2018closing}. As shown in \figref{fig:pipeline}, the grasp map \textbf{G} consist of three images: grasp quality \textbf{Q}, orientation $\boldsymbol\phi$, and gripper width \textbf{W}. \textbf{Q} denotes the quality of a grasp centered at each pixel. The quality of a grasp is a scalar value between [0,1], where the higher the value, the better the grasp. $\boldsymbol\phi$ is the orientation image, representing the pixel-wise orientation of a grasp around the image normal. Because an antipodal grasp is symmetric beyond 180 degrees, we limit the orientation between [$-\pi/2,~\pi/2$] radians. Finally, \textbf{W} is the width image that describes the pixel-wise gripper width from [0,~150] pixels. We transform the pixel-dependent gripper width to real-world units using the measured depth and the camera parameters. \section{Problem Formulation} This work addresses the problem of generating antipodal grasps on unknown objects with different stiffnesses lying on a supporting surface. The goal is to calculate a grasp for each pixel in the depth image while taking into account object stiffness. More formally, we train a model $\mathcal{M}$ that takes as input a depth image $\mathbf{I_d}$ and a stiffness image $\mathbf{I_s}$, and produces a grasp map \textbf{G} that incorporates grasp quality and grasp parameters (orientation, gripper width) for grasps centered at each pixel in the input. \begin{equation*} \mathcal{M}: (\mathbf{I_d},\mathbf{I_s}) \mapsto \textbf{G}. \end{equation*} To achieve this goal, we propose to use the \ac{dnn} in \figref{fig:pipeline} to map from depth and stiffness images to grasps \textbf{G} in the image, which we can easily transform to the real world using known coordinate transforms. \section{Dataset} \label{sec:dataset} To train \textit{Def-GG-CNN}\xspace, we need a dataset consisting of depth, stiffness, quality, orientation, and width images. To date, there exists no such dataset, and, thus, we opted to curate our own synthetic dataset. The pipeline of generating training data is visualized in \figref{fig:datagen}. We first convert the triangular mesh of an object into tetrahedral mesh using fTetWild \cite{ftetwild} and feed that tetrahedral mesh to the Isaac Gym simulator to enable its soft bodies simulation feature. The stiffness of an object can then be varied by adjusting the material parameters , \textit{i.e.}, Young's modulus and Poisson's Ratio. Then using the object triangular mesh, we sample grasp candidates which are later evaluated with Isaac Gym using proper quality metrics. Based on the performance of the grasps, we then label the grasps, convert them to the desired representation, and store them in the training dataset. \begin{figure}[!t] \centering \def0.5\linewidth{\linewidth} {\fontsize{5}{8 \input{figures_tex/datagennew.pdf_tex}} \caption{The training data generation pipeline.} \label{fig:datagen} \vspace{-0.5cm} \end{figure} \textbf{Depth and stiffness input:} We captured depth images of target objects with a virtual camera set to view the scene from top-down. To model variable object stiffness, four values of Young's modulus from $2\cdot 10^4$ to $2\cdot 10^9$ were used. The Young's modulus is normalized to [0,1] range and the corresponding stiffness value is assigned to every pixel in the stiffness image that the object occupies. \textbf{Grasp candidates:} Grasps are sampled with an antipodal grasp sampler to obtain approximately 200 grasp candidates for each target object. All grasps that collide with the mesh are filtered out, resulting in a final set of 25 to 40 collision-free grasps for each object. \textbf{Quality metrics:} None of the standard grasp quality metrics, such as the Ferrari \& Canny $L_1$ metric \cite{ferraricanny}, are directly applicable for both rigid and deformable objects. As a quality metric, we use a \textit{shake task}\xspace which measures how easily an object is displaced in hand under linear accelerations. A higher metric means a better grasp as it indicates that a grasp can withstand higher accelerations. We use this metric to label a grasp as a positive or negative grasp by checking if the linear acceleration it can withstand is above or below a threshold. Specifically, after successfully lifting the object for each grasp candidate, we linearly increase the acceleration of the grasp along 16 directions until the gripper loses contact with the objects or reaches the upper acceleration limit, which is set to 50 $m/s^2$. Then we compute the average acceleration over all directions, and if this value is higher than the threshold of 25 $m/s^2$, we label the grasp candidate as a positive grasp. \textbf{Ground-truth grasp map:} To further simplify the data generation, we only use positively labeled grasps as ground-truth grasps to train the network. To generate the ground-truth grasps, we first transform all grasps to the image space. To do so, we represent the grasps as rectangles in the image as displayed in \figref{fig:grasprep}. Four parameters define the rectangles: grasp center, grasp orientation, grasp width, and finger height. Finally, we use the rectangles as image masks to generate ground-truth grasp maps \textbf{G}. Specifically, all pixels of the quality images \textbf{Q}, angle images $\boldsymbol\phi$, and width images \textbf{W} within the rectangle are set to the values given from the \textit{shake task}\xspace. In contrast, all pixels outside the rectangle are set to invalid. \textbf{Training dataset:} As a training dataset, we generate and label grasps on 30 objects. The objects include 13 primitive objects provided in Isaac Gym, 5 objects from the YCB dataset \cite{ycb}, and 12 objects with adversarial geometry from the EGAD! dataset\cite{egad}. Because we set the stiffness for each object to four different values, the training set contains, in total, 120 objects. We use the Franka Emika Panda\xspace gripper model to execute grasps on objects in the simulator. To counteract the small size of the training set, we further augment the dataset with random crops, zooms, and rotations to create a set of 5400 depth and stiffness images with 27000 corresponding labeled grasp maps. \begin{figure}[!t] \centering \def0.5\linewidth{0.5\linewidth} {\color{white} \fontsize{8}{8 \input{figures_tex/grasprep.pdf_tex}} \caption{A grasp is represented as a rectangle in 2D image plane.} \label{fig:grasprep} \vspace{-0.5cm} \end{figure}
{'timestamp': '2021-09-14T02:14:40', 'yymm': '2109', 'arxiv_id': '2109.05320', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05320'}
arxiv
\section{Introduction} Fine-grained classification involves distinguishing between classes that have subtle variations among them. For example, in image classification, we can classify birds from non-birds, or attempt a more fine-grained classification of bird species \cite{akata2015evaluation}. In NLP, one example is sentiment analysis, where we could have a coarse positive/negative classification, or a fine-grained set of categories that differentiate ``positive'' and ``very positive'' (i.e., an ordinal scale), such as in \citet{socher2013recursive}. Similarly, for emotion classification, we could try to classify a text into 4 to 6 emotions, or into much finer classifications of 27 \cite{demszky2020goemotions} or 32 \cite{rashkin2019towards} emotion categories. This involves distinguishing between some closely confusable pairs of emotions, such as ``sad'' and ``devastated'', or ``furious'' and ``annoyed''. Fine-grained classification tasks are challenging precisely due to the presence of class interference amongst closely confusable classes \cite{collins2018evolutionary,zhao2017survey}. The standard approach today to task classification involves using a pre-trained language model (e.g., BERT) which is fine-tuned on downstream tasks using a standard cross-entropy loss. However, this standard loss may not be the optimal manner in which to train fine-grained classification models. A simple counterexample is that cross-entropy loss treats misclassifications as nominal, not ordinal, so misclassifying a ``positive'' as a ``very positive'' is no worse (in terms of the loss) as ``very negative''. But even within nominal categories, misclassifying ``annoyed'' as ``furious'' is quite different from a misclassification of ``joyful'', as there are varying degrees of semantic similarity between nominal categories. Intuitively, we can try to improve model performance by modifying the loss to reflect the \emph{contrast} between pairs of examples of the same or different classes. Such contrastive approaches are widely used in computer vision tasks for label-noise reduction, semi-supervised and self-supervised learning tasks \cite{le2020contrastive}. More recently in NLP, \citet{gunel2021supervised} used a supervised contrastive loss to improve fine-tuning performance of pre-trained language models in several few-shot learning scenarios. In this work, we incorporate inter-class relationships into a Label-aware Contrastive Loss (LCL), which helps the model to differentiate the weights between different negative samples. At a high level, the model adaptively learns which pairs of classes are more similar, and which are more different. We use a dual-model approach where a weighting model learns the inter-label relationships that are used in the main embedding model's contrastive objective. We evaluate our approach on two popular tasks in NLP: emotion recognition (4 datasets to span both coarse- and fine-grained classification), and sentiment analysis (with a coarse and fine-grained version of the same dataset). We find that LCL outperforms existing contrastive learning losses, and performs comparably with the state-of-the-art. We supplement our findings with targeted experiments to provide evidence for boundary conditions---situations in which LCL should work best---and for how LCL affects model prediction confidence. \section{Related Work} \subsection{Fine-grained classification} Fine-grained classification is a popular problem in image classification, including tasks like distinguishing between different animal species \cite{wei2019deep, zhao2017survey}. We note that in NLP, ``fine-grained'' is commonly used when analysing different granularities of text, such as character-, word- and span-level information \cite{zirn2011fine,da2019fine,liu2020fine}. In this work, we use fine-grained classification to refer to the \emph{nature of labels associated with the task}. Fine-grained classification tasks involve finding subtle differences to distinguish between close classes. For instance, ``coarse" sentiment classification involves distinguishing negative and positive sentiments in text, and fine-grained sentiment classification involves further distinguishing the \emph{positive} class into \emph{very positive} and \emph{positive}. This problem is challenging because the classes are semantically similar, which makes it difficult for the model to learn the labels \cite{collins2018evolutionary}. Recent models have applied state-of-the-art attention mechanisms and multi-task learning to solve fine-grained sentiment classification. \citet{balikas2017multitask} performed fine-grained sentiment classification using a multi-task learning setup that performed both binary and fine-grained sentiment classification simultaneously. \citet{yin2020sentibert} composed the sentiment semantics using an attention network to enhance BERT's pre-training objective, and showed improvement in a downstream fine-grained sentiment analysis task. \citet{tian2020skep} modified the pre-training objectives of language models to include more sentiment-specific tasks, such as sentiment word masking and sentiment word prediction, and showed improved performance in fine-grained sentiment analysis. These previous methods mostly focus on improving the pre-training of language models, or incorporating multiple task training; here, we focus on improving contrastive fine-tuning to solve fine-grained text classification. Another important fine-grained classification task is that of emotion recognition. Traditionally, emotion recognition datasets have a small number of emotions (e.g., 4-7). Two recent datasets were proposed to address this issue: \citet{rashkin2019towards} introduced Empathetic Dialogues, which contains text conversations labelled with 32 emotion labels, and \citet{demszky2020goemotions} introduced GoEmotions, which contains Reddit comments labelled with 27 emotion labels. Recently, \citet{suresh2021knowledge} introduced a method to incorporate knowledge from emotion lexicons into an attention mechanism to improve fine-grained emotion classification on these two datasets. \citet{khanpour2018fine} similarly used lexicon-based features to tackle fine-grained emotion recognition from online health posts. However, there is still much work to be done in fine-grained emotion classification, and it has important implications for designing empathetic agents and chatbots \cite{roller2021recipes}. Finally, we note that fine-grained classification has also been explored in the context of entity-type classification \cite{ling2012fine,jin2019fine}. However, this task is generally multi-label in nature and is out of the scope of the current work. \subsection{Contrastive learning} Contrastive learning focuses on improving the ability of the model to differentiate a given data point from ``positive'' examples (points sharing the same label) and from ``negative'' examples (different labels). Contrastive learning has been widely used in computer vision, especially in self-supervised settings \cite{le2020contrastive,chen2020simple} where such learning guides the model based on similarities between the latent representation of the samples. \cite{chen2020simple} introduced SimCLR, a simplified version of contrastive loss that does not use memory banks \cite{tian2020contrastive,he2020momentum,misra2020self} or designated architectures \cite{bachman2019learning}, and which achieves improved performance in both semi-supervised and self-supervised settings. SimCLR uses data augmentation to create ``positive'' examples that are similar to a given input. \citet{khosla2020supervised} extended SimCLR to also leverage label information: they include other training examples with the same label in the set of ``positive'' examples. Contrastive loss has also been recently incorporated in both the pre-training and fine-tuning objectives of pre-trained language models. Self-supervised contrastive loss has been used for pre-training language models such as BERT \cite{fang2020cert,meng2021coco}. \citet{gunel2021supervised} used a combination of cross entropy and supervised contrastive loss for fine-tuning pre-trained language models to improve performance in few-shot learning scenarios. \citet{gao2021simcse} used a contrastive objective to fine-tune pre-trained language models to obtain sentence embeddings, and achieved state-of-the-art performance in sentence similarity tasks. In our work, we aim to improve the fine-tuning objective of pre-trained language models for downstream tasks involving fine-grained classes. \subsection{Other related work} In addition to the above works, we mention other related references which used similar techniques. Dual-model approaches are used in tasks like knowledge distillation, where the knowledge from a larger \emph{teacher} network is transferred to a lighter \emph{student} model \cite{hinton2015distilling,kim2016sequence,sun2020contrastive,sun2019patient,li2020bert,aguilar2020knowledge}, however, these works are mainly focused on model compression. Dual-model strategies have also been widely used in label-noise representation learning in image classification tasks \cite{han2018co,wei2020combating,lu2021co,feng2019learning} by updating each other with \textit{clean} samples (the samples which have the lowest loss value in every iteration). However, the sample selection performed by these works assume that the noise rate in each dataset is known or needs to be estimated, which is not always possible. Another set of works focus on sample re-weighting to focus on select samples more. \citet{plank2014learning} use inter-annotator agreement to guide the model's focus on samples that are harder to distinguish. Sample re-weighting is also widely used to reduce label noise. Although the majority of works in this area depend on a pre-determined weighting function, there are a few notable papers which automate this process by adaptively calculating weights: \citet{chang2017active} uses active learning to re-weight samples, while \citet{ren2018learning} uses gradients to learn weights, however their performance drops with large number of classes \cite{song2020learning}. Meta-Weight-Net uses a single-layer neural network to obtain the weights \cite{shu2019meta}. These methods all require clean validation data to optimize their learning objective. \section{Approach} \begin{figure*}[h] \includegraphics[width=0.9\textwidth]{fig/model.png} \centering \caption{Illustration of training strategy used in our Label-aware Contrastive Loss approach. The encoder network is in orange and the the weighting network is indicated in blue. In the encoder network, every sample from the training batch is compared against every other sample in the Label-aware Contrastive Loss function. Note that at testing time, only the contextual encoder is used. } \label{fig:model} \end{figure*} \subsection{Contrastive Loss} A Contrastive Loss (CL) brings the latent representations of samples belonging to the same class closer together, by defining a set of positives (that should be closer) and negatives (that should be further apart). The type of positives and negatives vary and is dependent on the contrastive loss used. Throughout this section we denote the set of positives as $\mathcal{P}$ and set of negatives as $\mathcal{N}$. Let us also denote a batch of sample and label pairs as $\{x_{i},y_{i}\}_{i \in I}$, where $I = \{1, \cdots,K\}$ is the indices of the samples and $K$ is the batch-size. In the self-supervised version of contrastive loss \cite{chen2020simple}, one applies augmentation to all $K$ samples to produce $K$ augmented data-points. Therefore, the batch size becomes $2K$ and $I = \{1, \cdots, 2K\}$. The positive set for a given $x_{i}$ contains only one sample, the augmented version of $x_{i}$, and we denote its index as $g(i)$. The negative set would be the rest of the samples in the batch. The loss is defined as: \begin{equation} L_{self} = \sum_{i=1}^{2K} -\log \frac{\exp(h_{i} \cdot h_{g(i)}/\tau)}{\sum_{k \in \mathcal{I}/i} \exp(h_{i} \cdot h_{k}/\tau)} \end{equation} where $\tau$ is the temperature hyper-parameter. Larger values of $\tau$ scale down the dot-products, creating more difficult comparisons. $h_{i}$ is the normalised representation vector of $x_{i}$ obtained from an encoder $\Phi$. \citet{khosla2020supervised} extended the above loss to a Supervised Contrastive Loss (SCL) by including the samples belonging to the same class as $x_{i}$ in its positive set. The positive set is given by $\mathcal{P} = \{p : {p \in I} , {y_{p} = y_{i}} \land p \neq i\}$, with size $|\mathcal{P}|$. The supervised contrastive loss is given by: \begin{equation} \label{eq:scl} L_{SCL} = \sum_{i=1}^{2K} \frac{-1}{|\mathcal{P}|} \sum_{p \in \mathcal{P}} \log \frac{\exp(h_{i} \cdot h_{p}/\tau)}{\sum_{k \in \mathcal{I}/i} \exp(h_{i} \cdot h_{k}/\tau)} \end{equation} \subsection{Label-aware Contrastive Loss} In our work, we introduce relationships between class labels to adaptively distinguish between the negative examples. From Eqn. \ref{eq:scl} we can see that Supervised Contrastive Loss weights all positive and negative samples equally to the current sample $x_{i}$. But not all negatives are equal. In certain fine-grained text classification tasks, we have semantically-similar labels with more subtle differences, and are thus more \textit{confusable}. For example, ``sad'' and ``devastated'' are semantically closer emotion categories than ``sad'' and ``happy''. Thus, our goal was to introduce a method for adaptively weighting a given input's positive/negative samples based on the label-relationships between them, thereby helping the model differentiate the more difficult negatives. We propose Label-aware Contrastive Loss (LCL) which adapts Contrastive Loss for fine-grained classification tasks by incorporating inter label-relationships. For the positive set, we follow \cite{khosla2020supervised, gunel2021supervised} where $\mathcal{P}$ of a given sample contains the augmented sample and samples within the same class. We utilise a weighting vector $\boldsymbol{w_{i}} \in \mathbb{R}^C$ where $C$ is total number of classes to weight the pair-wise similarity values of the supervised contrastive loss defined in Eq. \ref{eq:scl}. Our adapted loss function for each entry $i$ and total across the batch is: \begin{equation} \mathcal{L}_{i} = \sum_{p \in \mathcal{P}} \log \frac{ w_{i,y_{i}} \cdot \exp(h_{i} \cdot h_{p}/\tau)}{\sum_{k \in \mathcal{I} \setminus i} w_{i,y_{k}} \cdot \exp(h_{i} \cdot h_{k}/\tau)} \end{equation} \begin{equation} L_{LCL} = \sum_{i=1}^{2K} \frac{-1}{|\mathcal{P}|}\mathcal{L}_{i} \label{eq:lcl} \end{equation} Here, $w_{i,y_{k}}$ indicates the relationship between an input $x_{i}$ and a label $y_{k}$. Just as in the previous losses, $h_{i} \in \mathbb{R}^{d}$ is the output representation of the encoder for $x_{i}$. We normalise $h_{i}$ for the similarity comparison, similar to \citet{chen2020simple}. In contrastive loss we want the weights of the positives to be higher and that of the negatives to be lower. However, we want to increase the weight of confusable negative labels relative to other negative labels. In our work, we aim to incorporate these inter-label relationships into the contrastive objective. To weigh each comparison sample differently, in addition to a primary encoder $\Phi$, we use a weighting network $\Psi$. We follow a dual-model strategy similar to co-teaching approaches \cite{han2018co,wei2020combating} where the weighting network is a second network that coordinates with the primary encoder. The input batch is fed into $\Psi$ and output is optimised using Cross-entropy loss $L_{w}$. The prediction probabilities obtained from the softmax layer, i.e. soft labels, is used to obtain confidence of the current sample, is given by: \begin{equation} \label{eq:weight} \boldsymbol{w_{i}}= \frac{\exp(h_{i})}{\sum_{c=1}^{C} \exp(h_{i})} \end{equation} Here, $\boldsymbol{w_{i}} = \{w_{i,c}\}_{c=1}^{C}$ where $C$ is the total number of classes. Each $w_{i,c}$ denotes the confidence of the weighting network that sample $x_{i}$ belongs to class $c$. When $\Psi$ is given a \textit{confusable} sample, it will have higher scores for the classes that are more closely associated with the current sample. We hypothesize that incorporating these high values back into the negative comparison in the supervised contrastive loss of the primary encoder would steer the encoder toward finding more distinguishing patterns to differentiate between \textit{confusable} samples. \textbf{Training setup:} The output vector of the weighting network is optimized using a Cross Entropy Loss $L_{w}$, while the output of the encoder network is optimized by using a linear combination of $L_{LCL}$ and Cross Entropy Loss $L_{e}$. The encoder and weighting networks are jointly optimised using objective function $L_{f}$: \begin{equation} L_{f} = \alpha (L_{w} + L_{e}) + (1-\alpha) L_{LCL} \end{equation} Here, $\alpha$ is a tunable loss scaling factor similar to \citet{gunel2021supervised}. We note that both the encoder and the weighting network are utilised during training, but in the testing phase, we use only the primary encoder network. The overall training process is shown in Fig. \ref{fig:model}. Each input training batch $I$ is passed to the encoder network $\Phi$ and the weighting network $\Psi$ simultaneously. Here, both these networks are initialised by a pre-trained language model and the [CLS] token of the last layer of $\Phi$ is the final representation $h_{i}$ which is used for computing $L_{LCL}$. For performing the classification, $h_{i}$ is projected down using the classifier and the output is optimised using cross-entropy loss $L_{e}$. The architecture of the weighting network was designed in the same way as the fine-tuning setup of the pre-trained language model of choice, and the weight vector $\boldsymbol{w}_{i}$ is the output probability vector obtained after the softmax projection. \section{Experiments} \subsection{Datasets} We evaluate our approach using two tasks, Emotion Recognition and Sentiment Analysis. We choose these tasks as it helps demonstrate our model’s performance in different types of inter-class relationships that exist in text classification. Specifically, in sentiment classification the classes are ordinal, whereas in emotion recognition the classes are nominal\footnote{Although there still may be underlying latent structure such that some classes may be semantically more similar than others, e.g., \emph{afraid} vs. \emph{anxious} vs. \emph{joyful}.}. For emotion recognition, we use the following 4 datasets, ordered in decreasing number of classes: \begin{itemize} \item Empathetic Dialogues \cite{rashkin2019towards}\footnote[2]{\url{https://github.com/facebookresearch/EmpatheticDialogues}}: a dataset of two-way conversations between a speaker and listener, and labelled with 32 emotions. In this work, we only use the first turn of the conversation, which consists of the speaker describing an emotional incident. The train/validation/test split for the dataset is 19,533 / 2,770 / 2,547 samples respectively. \item GoEmotions \cite{demszky2020goemotions}\footnote[3]{\url{https://github.com/google-research/google-research/tree/master/goemotions}}, a dataset of Reddit comments labelled with 27 emotions (we did not include samples with neutral label). The original dataset is multi-labelled, i.e, some samples have more than one label. In this work, we use only the single-labelled samples, which is $\sim$80\% of the total data. The train/validation/test split of this dataset is 23,485 / 2,956 / 2,984. \item ISEAR (International Survey on Emotion Antecedents and Reactions) \cite{scherer1994evidence}\footnote[4]{\url{https://www.unige.ch/cisa/research/materials-and-online-research/research-material/}} contains sentences of emotion experiences labelled with one of 7 emotion categories. The train/validation/test split of the dataset is 4,599 / 1,533 / 1,534. \item EmoInt \cite{mohammad2017wassa}\footnote[5]{\url{http://saifmohammad.com/WebPages/EmotionIntensity-SharedTask.html}} consists of tweets labelled with one of 4 emotion categories. The train/validation/test split of this dataset is 3,612 / 346 / 3,141. \end{itemize} For Sentiment Analysis, we use the 5-class and 2-class classification versions of the Standford Sentiment Treebank \cite{socher2013recursive}, which consists of movie reviews annotated for sentiment. The SST-5 has 5 classes (\emph{very negative}, \emph{negative}, \emph{neutral}, \emph{positive}, and \emph{very positive}), while the SST-2 is only a binary (\emph{negative}/\emph{positive}) classification. The train/validation/test split for the SST-5 is 8,544/ 1,101 / 2,210, and for SST-2 is 6,920 / 872 / 1,821. \subsection{Implementation Details} We initialised both the pre-trained encoder and weighting network using $\text{ELECTRA}_{base}$ (\texttt{electra-base-discriminator}) from HuggingFace’s Transformers library \cite{wolf2019transformers}, which consists of 12 Transformer layers with a hidden representation size of 768. As is convention, we use the representation corresponding to the [CLS] token of the last layer as an input into the final classification layer \cite{clark2019electra}. The classifier present in the primary encoder consists of a 2-layer dense network with the first layer having hidden size of 768 with a ReLU activation, followed by an output layer. The dropout was set to 0.1. Similar to previous research \cite{khosla2020supervised,gunel2021supervised}, we use data augmentation to generate positive samples. Here, we use synonym replacement where we substitute 30\% of the words in the input text by replacing it with words with semantic similarity using WordNet dictionary \cite{miller1995wordnet}. The coverage of the WordNet dictionary was $\sim$69\% for EmpatheticDialogues, $\sim$69\% for SST-2 and SST-5, $\sim$66\% for ISEAR, $\sim$62\% for EmoInt and $\sim$61\% for GoEmotions. Previous research \cite{wei2019eda} have shown that synonym replacement works well as it could introduce new vocabulary words and help the model generalise. In addition, synonym replacement does not require an external model unlike other augmentation methods like back-translation. For training, we used the Adam optimiser and early stopping based on performance on the validation set. We ran our models with 5 random seed settings and report the mean performance. More details regarding the hyper-parameter settings and computing infrastructure can be found in the Appendix. Source code is available at \url{https://github.com/varsha33/LCL_loss}. \subsection{Model comparisons and evaluation} For the emotion classification task we calculate classification accuracy and F1 score, while for sentiment analysis we compare accuracy of sentence-level sentiment classification. For both tasks, we compare LCL against the following baselines: \begin{itemize} \item \textbf{Fine-tuning objectives}: We compare against the standard Cross-entropy Loss, as well as Supervised Contrastive Loss (SCL) \cite{gunel2021supervised}. In both comparisons and in LCL, we use $\text{ELECTRA}_{base}$ as the pre-trained language model. \item \textbf{General pre-trained language models}: For emotion classification, we also compare with $\text{BERT}_{base}$ \cite{devlin2019bert} as our baseline. We use the same fine-tuning architecture as \citet{devlin2019bert}. For sentiment analysis, we compare against $\text{BERT}_{base}$ (SST-2 \cite{devlin2019bert} and SST-5 \cite{munikar2019fine}) and $\text{RoBERTa}_{base}$ \cite{liu2019roberta}. \item \textbf{Sentiment-specific language models}: For sentiment analysis, we compare against SentiBERT \cite{yin2020sentibert}, SentiLARE \cite{ke2019sentilare} and SKEP \cite{tian2020skep}, which are language models designed specifically for sentiment analysis and related tasks. \end{itemize} \section{Results and Discussion} \begin{table*}[htb] \resizebox{\textwidth}{!}{% \begin{tabular}{lcccc|cccc} \hline Dataset: & \multicolumn{2}{c}{Empathetic Dialogues} & \multicolumn{2}{c|}{GoEmotions} & \multicolumn{2}{c}{ISEAR} & \multicolumn{2}{c}{EmoInt} \\ Number of classes: & \multicolumn{2}{c}{32} & \multicolumn{2}{c|}{27} & \multicolumn{2}{c}{7} & \multicolumn{2}{c}{4} \\ & Acc / \% & F1 & Acc / \% & F1 & Acc / \% & F1 & Acc / \% & F1 \\ \hline $\text{BERT}_{base}$ & 55.8 (0.8) & 54.4 (1.2) & 64.1 (0.5) & 63.0 (0.9) & 69.2 (0.3) & 69.3 (0.1) & 85.0 (0.6) & 85.0 (0.6) \\ \hline ELECTRA$_{base}$ + Cross-Entropy Loss & 58.3 (0.5) & 56.8 (0.5) & 64.8 (0.3) & 63.9 (0.4) & 71.4 (0.2) & 71.4 (0.2) & 85.5 (0.9) & 85.5 (0.9) \\ ELECTRA$_{base}$ + SCL \cite{gunel2021supervised} & 58.5 (0.7) & 57.0 (0.9) & 64.3 (0.4) & 63.0 (0.4) & 70.5 (0.5) & 70.5 (0.6) & 85.7 (0.2) & 85.8 (0.2) \\ ELECTRA$_{base}$ + LCL & \textbf{60.1 (0.3)} & \textbf{59.1 (0.3)} & \textbf{65.5 (0.2)} & \textbf{64.8 (0.2)} & \textbf{72.4 (0.2)} & \textbf{72.4 (0.2)} & \textbf{86.6 (0.3)} & \textbf{86.6 (0.3)} \\ \hline \end{tabular} } \caption{Summary of results for fine-grained emotion recognition. We divide the table into fine-grained (left) and coarse-grained (right) emotion classification, based on the number of classes. We compare the results of an ELECTRA encoder trained with: a standard cross-entropy loss, a Supervised Contrastive Loss (SCL), and our proposed Label-aware Contrastive Loss (LCL). The results shown are averaged over 5 runs, with standard deviations in parenthesis. } \label{tab:emo} \end{table*} \subsection{Emotion Classification Performance} \label{res:emotion} For emotion classification we compared our proposed Label-aware Contrastive Loss (LCL) work with the standard training objective, i.e., cross-entropy loss. We also compared with \citet{gunel2021supervised}'s formulation of Supervised Contrastive Loss (SCL), who used a linear combination of SCL and Cross-entropy loss for fine-tuning pre-trained language models (in contrast to the original SCL paper, \citealp{khosla2020supervised}, who used a two-stage training regime). For all fine-tuning objectives, we used $\text{ELECTRA}_{base}$ as the pre-trained language model. To evaluate the approaches we use top-1 Accuracy and weighted macro F1-score. As shown in Table \ref{tab:emo}, our LCL objective function improved classification performance compared to both SCL and cross-entropy loss, on both fine-grained emotion classification (32-class, LCL$>$SCL, t-test on accuracy, $t=4.20, p=.007$, LCL$>$CEL, $t=6.42, p<.001$; and 27-class classification; LCL$>$SCL, $t=5.70, p<.001$, LCL$>$CEL, $t=4.32, p=.002$), as well as coarse-grained emotion classification (7-class, LCL$>$SCL, $t=7.39, p<.001$, LCL$>$CEL, $t=7.70, p<.001$; and 4-class classification, LCL$>$SCL, $t=5.34, p<.001$, LCL$>$CEL, $t=2.25, p=.078$ not significant). The consistent improved performance of LCL is in contrast to SCL, which did not outperform standard cross-entropy loss, (all $p>.05$, with SCL in fact performing worse than CEL on ISEAR, $t=3.34, p=.02$). These results suggest that incorporating class relationships into the fine-tuning objective of pre-trained language models can improve classification accuracies. \subsection{Sentiment Analysis Performance} \begin{table}[htb] \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{lcc} \hline\hline & SST-5 & SST-2 \\ & Acc / \% & Acc / \% \\ \hline $\text{BERT}_{base}$ \cite{munikar2019fine} & 53.2 (-) & \\ $\text{BERT}_{base}$\cite{devlin2019bert} & & 93.5(-) \\ $\text{RoBERTa}_{base}$ \cite{liu2019roberta} & 56.2 (-) & 94.8(-) \\ SentiBERT\cite{yin2020sentibert} & 57.8 (-) & 94.7 (-) \\ SentiLARE\cite{ke2019sentilare} & \textbf{58.6 (-)} & \\ SKEP \cite{tian2020skep} & & \textbf{96.7 (-)}\\ $\text{ELECTRA}_{base}$\cite{clark2019electra} & & 93.4 (-) \\ \hdashline $\text{ELECTRA}_{base}$ (Our implementation) & 57.1 (1.2) & 94.4 (0.3) \\ $\text{ELECTRA}_{base}$+ SCL \cite{gunel2021supervised} & 57.4 (0.6) & 94.3 (0.2) \\ $\text{ELECTRA}_{base}$ + LCL (Ours) & \textbf{58.5 (0.2)} & \textbf{94.5 (0.1)} \\ \hline \end{tabular}% } \caption{Summary of results for fine-grained (5-class) and coarse-grained (2-class) sentiment analysis. The results shown are averaged over 5 runs, with standard deviations in parenthesis.} \label{tab:sentiment-results} \end{table} For sentiment analysis, we used the sentence inputs from SST-5 and SST-2. In addition to comparing LCL with varying fine-tuning objectives (cross-entropy and SCL), we also compare against recent state-of-the-art works, focusing on pre-trained language models and pre-trained language models learnt specifically for sentiment classification such as SentiBERT \cite{yin2020sentibert}, SentiLARE \cite{ke2019sentilare}, and SKEP \cite{tian2020skep}. To ensure a fair comparison, we use the $base$ version of the pre-trained language models unless mentioned otherwise. To evaluate, we use top-1 Accuracy. From the results in Table \ref{tab:sentiment-results}, in the case of SST-5, our LCL objective showed improved classification performance compared to SCL ($t=3.61, p=.01$), and standard cross-entropy loss (SST-5: $t=2.40, p=.069$, although this is not significant due to high SD in CEL performance). Our LCL-fine-tuned model also achieves a performance comparable to the state-of-the-art performance of SentiLARE, although not statistically different ($p=.77$). On SST-2, our LCL performance gains compared to cross-entropy and SCL are far more modest (neither were statistically significant; $p=.78$ and $p=.32$ respectively), and it performs comparably to previous SOTA pre-trained models, although it does not do as well as SKEP ($p<.001$). We provide two possible reasons: one, there is already very high performance (e.g. 94\% accuracies) on this binary classification task, which makes it difficult to get clear consistent improvements. Second and more importantly, we designed LCL to increase inter-class contrast, and so our method should work better for higher number of classification, compared to binary classification. Indeed, we see that LCL's improvements are much stronger and consistent on the fine-grained (5-class) sentiment classification task. \subsection{Case Study: Varying number of classes} \begin{table*}[] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{lccc|c|cccc} Number of classes: & \textbf{32} & \textbf{16} & \textbf{8} & \textbf{4-easy} & \textbf{4hard-a} & \textbf{4hard-b} & \textbf{4hard-c} & \textbf{4hard-d} \\ \hline Cross-Entropy Loss & 58.1 (0.7) & 68.8 (0.4) & 78.0 (0.6) & \textbf{89.2 (0.3)} & 56.1 (0.5) & 63.2 (0.9) & 54.3 (1.0) & 67.4 (0.6) \\ Supervised Contrastive Loss & 58.6 (0.5) & 67.9 (0.6) & 77.0 (0.8) & 88.8 (0.5) & 55.4 (0.5) & 63.7 (1.1) & 53.3 (0.8) & 68.1 (0.7) \\ Label-aware Contrastive Loss & \textbf{60.1 (0.2)} & \textbf{69.6 (0.5)} & \textbf{78.7 (0.4)} & 88.8 (0.6) & \textbf{57.5 (0.7)} & \textbf{64.2 (0.7)} & \textbf{55.6 (0.6)} & \textbf{69.5 (0.5)} \end{tabular} } \caption{Case study using class subsets of EmpatheticDialogues. For brevity, we only report accuracy scores. Column headers give the number of class labels in that comparison. 4-easy denotes a coarse-grained set of four emotions that are more easily distinguishable (on which we predicted that LCL would not add much), while the 4-hard sets denote fine-grained sets of four emotions that are semantically more similar. Results shown are averaged over 10 runs, with standard deviations in parentheses.} \label{tab:fine-emotion} \end{table*} We designed LCL to increase inter-class contrast, and we see marked improvements for all the tasks studied except for the 2-class (SST-2) classification. We hypothesized that LCL should do better with an increasing number of classes, but unfortunately it is difficult to draw that inference from Tables \ref{tab:emo} and \ref{tab:sentiment-results} as each dataset only provides one datapoint about number of classes, and there are also differences across datasets which is difficult to control for. Thus, in this experiment, we used the dataset with the largest number of emotion classes, Empathetic Dialogues (with 32-classes), and subsampled some fraction of emotion classes from this dataset to create ``mini-datasets'' of differing number of emotion classes. This allows us to systematically vary the number of classes that our LCL-tuned model has to learn to classify, and examine the performance of the model. We predict that LCL will have a greater contribution to performance when (i) the number of classes is larger, and (ii) the classes are more confusable. The full dataset has 32-classes. We randomly sampled a partition of 16 emotions\footnote{ \{\emph{Afraid}, \emph{Angry}, \emph{Annoyed}, \emph{Anxious}, \emph{Confident}, \emph{Disappointed}, \emph{Disgusted}, \emph{Excited}, \emph{Grateful}, \emph{Hopeful}, \emph{Impressed}, \emph{Lonely}, \emph{Proud}, \emph{Sad}, \emph{Surprised}, \emph{Terrified}\}}, and 8 emotions\footnote{ \{\emph{Angry}, \emph{Afraid}, \emph{Ashamed}, \emph{Disgusted}, \emph{Guilty}, \emph{Proud}, \emph{Sad}, \emph{Surprised}\}}. We also created several subsets of 4-emotions. We designed a ``4-easy'' with 4 widely separated emotion classes (4-easy: \{\emph{Angry}, \emph{Afraid}, \emph{Joyful}, \emph{Sad}\}) which are the same classes as EmoInt and comprise a subset of \citet{ekman1999basic}'s list of six ``basic" emotions. (We predicted that LCL would not perform too well on this easy subset). We adopted a data-driven approach to pick the ``hard" subsets by picking the most-confusable sets of 4 emotions. First, we trained a standard cross-entropy loss model (similar to our weighting network in LCL in Fig.\ref{fig:model}), to obtain the 32-by-32 confusion matrix, which gives us an estimate of how confusable each pair of classes is. We exhaustively enumerated all 35,960 (32-choose-4) 4-class combinations: For each combination we extracted the corresponding 4x4 sub-matrix of the 32-by-32 confusion matrix, and calculated the sum of the off-diagonal elements of the 4x4 sub-matrix. The highest confusable combination of emotions was (4-hard-a: \{\emph{Anxious}, \emph{Apprehensive}, \emph{Afraid}, \emph{Terrified}\}). After excluding these emotions, the next-most confusable combinations were (4-hard-b: \{\emph{Devastated}, \emph{Nostalgic}, \emph{Sad}, \emph{Sentimental}\}), (4-hard-c: \{\emph{Angry}, \emph{Ashamed}, \emph{Furious}, \emph{Guilty}\}), and (4-hard-d: \{\emph{Anticipating}, \emph{Excited}, \emph{Hopeful}, \emph{Guilty}\}). We predicted that for all of these ``hard" sets that contain confusable emotions, LCL should outperform the other methods. The results from this case study are given in Table \ref{tab:fine-emotion}. For the 32, 16, and 8-class classification, as we predicted, we see a robust and consistent improvement of our proposed LCL over SCL and cross-entropy loss (16 classes: LCL$>$SCL, $t=6.28, p<.001$; LCL$>$CEL, $t=3.82, p=.001$; 8 classes: LCL$>$SCL, $t=6.27, p<.001$; LCL$>$CEL, $t=3.16, p=.007$). For the easy 4-class classification where the classes are conceptually ``far apart'', and hence, contrastive learning should not add much, we see that all three methods perform identically well ($p>.15$). But when we consider the more difficult 4-class classifications where the classes are much more conceptually similar, then LCL outperforms the other two methods by a statistically-significant margin (all $p$'s $<.05$ except for LCL and SCL in 4-hard-b because of the high SD's in that comparison). Thus, our results provide evidence that LCL is an effective fine-tuning strategy, especially when there are a large number of highly-similar classes. \subsection{Quantifying model confidence} Finally, we wanted to try to quantify the intuition that LCL helps to reduce the confusion among confusable classes. Beyond looking at the top-1 accuracy, we turned to the distribution of prediction scores among the different emotion classes. If LCL helps the model to better differentiate emotion classes, then we should also see this in the distribution of prediction scores for the different classes. For example, consider an example where \emph{devastated} is the model's predicted label, and \emph{sad} is a closely confusable class; if LCL helps to sharpen the model's ability to differentiate closely confusable classes, then the model's prediction score for \emph{devastated} should also be much higher than that for \emph{sad}. In general, we predict that LCL would result in more ``peaky'' distributions. \begin{figure}[htb] \centering \includegraphics[width=\columnwidth]{fig/entropy-1.png} \caption{Averaged entropy of the prediction score distributions, for the top-$k$ choices. Here, decreasing entropy carries the intuition that the distribution is more ``peaky'', such that the model is less confused by close alternatives.} \label{fig:entropy} \end{figure} We propose to use information-theoretic entropy to quantify this. We predict that LCL would result in prediction score distributions with lower entropy, which correponds to more ``peaky'' distributions. For a data point $x_i$, let us denote the prediction score as $S \in \mathbb{R}^{C}$, where $C$ is the total number of class labels. We then take the top-$k$ prediction scores $S_k$ as the sub-vector of $S$ with the $k$-largest values (i.e., for $k=2$, $S_k$ would consist of the two largest values in $S$). We normalize $S_k$ to sum to 1, and then calculate the entropy: \begin{equation} \text{Entropy}_{k} = - \sum_{k} s_{k} \cdot \log_{2}(s_{k}) \end{equation} In Figure \ref{fig:entropy}, we present the averaged entropy of our model's prediction scores, plotted against $k$ for the fine-grained emotion classification (Empathetic Dialogues and GoEmotion) and fine-grained sentiment analysis (SST-5). For Empathetic Dialogues, we see that LCL produces distributions with far lower entropies, compared to cross-entropy and SCL, and this is true as we look across the top-$k$ classes. For GoEmotions, we see a slightly different pattern, where both SCL and LCL produce markedly less-entropic distributions compared to the vanilla cross-entropy loss, but there was not much difference between SCL and our LCL. Finally, for SST-5, which was the most fine-grained sentiment analysis task we looked at, we start to see the same pattern that LCL produces the lowest entropy distributions, but this inference is limited by the small domain of $k$. This post-hoc analysis suggests that LCL helps the model to learn prediction distributions that are more confident. Note that this analysis looks at the confidence of the model's choice compared to the space of possible choices, and is independent of whether or not the predictions are correct (i.e., an inaccurate but confident model will also produce peaky, lower-entropic distributions), and so this result complements the other evaluation metrics used (accuracy and F1-scores). \section{Conclusion} In this paper we introduced a Label-aware Contrastive Loss that weights (negative) classes based on how closely confusable they are with the target class. Fine-tuning with LCL showed increased classification performance, especially in situations with (i) larger number of classes, and (ii) more confusable classes. LCL also seems to encourage the model to be more confident in its decisions. We view our approach as just one way to instantiate the general idea of adaptively weighting different classes, and future work could explore other methods such as incorporating external knowledge about the class labels, or incorporating different distance metrics between different classes. We feel that this class of approaches are promising, as they exemplify the idea that not all negative classes are or should be treated equally. \section*{Acknowledgements} This research is supported by the National Research Foundation, Singapore under its AI Singapore Program (AISG Award No: AISG2-RP-2020-016).
{'timestamp': '2021-09-14T02:19:01', 'yymm': '2109', 'arxiv_id': '2109.05427', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05427'}
arxiv
\section{Discussion and Conclusion} \label{sec:conclusion} In this paper, we propose \textit{Confirm-it}, a multimodal conversational model based on a decoding strategy inspired by cognitive studies of human behavior. We show that, through the proposed beam search re-reanking algorithm, our model generates dialogues that are more effective (based on task-accuracy) and more natural (based on the dialogues features discussed above). We believe further improvement could be obtained by increasing the performance of every single module. Moreover, the structure of the generated dialogues remains to be analysed, and we agree with~\citet{csleval2020} that a proper evaluation should involve humans. In future work, our method can be easily extended to other task-oriented dialogue tasks which involve a conversational agent as far as it has a module that generates questions and a module that performs a classification task. Depending on the task at hand, different ways to take intermediate probabilities into account can be designed, but the core idea of the method would not change. \section*{Acknowledgements} The authors kindly acknowledge the support of NVIDIA Corporation with the donation of the GPUs used in our research. We would like to thank Albert Gatt, Stella Frank, Claudio Greco, and Michele Cafagna for their suggestions and comments. Finally, we thank the anonymous reviewers for the insightful feedback. \section{Introduction} \label{sec:introduction} Quite important progress has been made on multimodal conversational systems thanks to the introduction of the Encoder-Decoder framework~\cite{suts:seq14}. The success of these systems can be measured by evaluating them on task-oriented referential games. Despite the high task-success achieved and the apparent linguistic well-formedness of the single questions, the quality of the generated dialogues, according to surface-level features, have been shown to be poor; this holds for systems based on both greedy and beam search (e.g.~\citet{shekhar-etal-2019-beyond, zarriess-schlangen-2018-decoding, murahari-etal-2019-improving}). \citet{test:inter2021} found that when taking these surface-level features as a proxy of linguistic quality, the latter does not correlate with task success, and the authors point to the importance of studying deeper features of dialogue structures. We aim to develop a multimodal model able to generate dialogues that resemble human dialogue strategies. Cognitive studies show that humans do not always act as ``rational'' agents. When referring to objects, they tend to be overspecific and prefer properties irrespectively of their utility for identifying the referent~\cite{gatt2013bayesian}; when searching for information or when learning a language, they tend to follow confirmation-driven strategies. Modelling such behaviour in language learning, \citet{medina2011words} and \citet{trueswell2013propose} propose a procedure in which a single hypothesized word-referent pair is maintained across learning instances, and it is abandoned only if the subsequent instance fails to confirm the pairing. Inspired by these theories, we propose a model, \textit{Confirm-it}, which generates questions driven by the agent's confirmation bias. \begin{figure}[t]\centering \includegraphics[width=1\linewidth]{images/fig_intro_new_2.pdf} \caption{ At turn 2, among the questions proposed by the beam search, \textit{Confirm-it} chooses $b$ since it is the most suitable one to confirm the current conjecture. } \label{fig:intro} \end{figure} Take the example of a referential guessing game in which an agent has to ask questions to guess an object in a given image. \textit{Confirm-it} will ask questions that reinforce its beliefs about which is the target object, till proven otherwise. For instance, in Figure~\ref{fig:intro}, after learning that the target is a living entity (turn 1), the agent conjectures the target is the dog on the right of the picture (though in principle, it could have been any of the candidates). Hence, the decoder generates the question that would let it confirm such belief, ``is it a dog?''. If its expectations are not met (viz., it receives a negative answer to such question - turn 2b), it moves its attention to another candidate object. We do not claim that our choice represents the optimal strategy to play the game, but we believe that it makes the generated dialogue more human-like. \cut{\citet{mazuecos-etal-2020-role} compared GDSE against other State-Of-The-Art models playing the Questioner task by measuring the \textit{effectiveness} of each question, defined as the ability of a question to discard candidate objects in the visual scene that are not the target. The authors found that, for the majority of the models considered, successful dialogues do not have a higher percentage of effective questions based on this metric, and that the model closest to humans is VDST~\cite{pang_gw}. VDST uses the probability distribution of the guesser to guide the question generator, and it builds on the assumption that at turn zero all objects are equally probable. We diverge from this assumption but we agree on the importance of establishing a tied connection between the probability distribution assigned by the Guesser to the candidate objects and the generation of questions. \at{Forse questo paragrafo si può accorciare parecchio.} } To evaluate this strategy, we take as a test-bed GuessWhat?!\@ \cite{guesswhat_game}, a two-player game between a Questioner that has to guess the target, and an Oracle (called ``external Oracle'' in the following) who is aware of the target. The widely used architecture of the Questioner, GDSE, jointly trains a Question Generator (QGen) and a Guesser~\cite{shekhar-etal-2019-beyond}. We augment this architecture with a module that simulates an internal Oracle. Being an ``internal'' Oracle, at test time this agent does not know what the target object is: while at training time it learns to answer questions by receiving the gold standard datapoint (the question, the actual target, and the human answer), at test time it assumes the target is the candidate object to which the Guesser assigns the highest probability. Hence, the three modules of the Questioner straightforwardly cooperate one another. The internal Oracle guides the QGen to ask questions that reinforce the Guesser's beliefs. Concretely, at training time, through Supervised Learning (SL) the QGen learns to ask human-like questions turn-by-turn, the internal Oracle to answer them, and the Guesser to guess the target object once the dialogue ends. At test time, we implement a beam search re-ranking algorithm that simulates the single-conjecture learning strategy used by humans: among the questions the QGen generates via beam search, the algorithm promotes the questions whose answer (obtained via the internal Oracle that receives the candidate with the highest probability as the target) increases the most the model's confidence in its hypothesis about the target. We run both quantitative and qualitative analyses, and evaluate the effectiveness of the dialogue strategy by asking human annotators to guess the target object given the dialogues generated by \textit{Confirm-it}. We compare results giving the dialogue generated by \textit{Confirm-it} when using the re-ranking algorithm and when generating the question proposed by the plain beam search. We show that the task accuracy of both the conversational agent and human subjects increases when receiving the dialogues generated by the \textit{Confirm-it} re-ranking algorithm. \section{Introduction} \label{sec:introduction} Quite important progress has been made on multimodal conversational systems thanks to the introduction of the Encoder-Decoder framework~\cite{suts:seq14}. The success of these systems can be measured by evaluating them on task-oriented referential games. Despite the high task-success reached and the apparent linguistic well-formedness of the single questions, the quality of the generated dialogues, according to surface-level features, have been shown to be poor; this holds for systems based on both greedy and beam search~\cite{shekhar-etal-2019-beyond, zarriess-schlangen-2018-decoding, murahari-etal-2019-improving}. \citet{test:inter2021} found that when taking these surface-level features as a proxy of linguistic quality, the latter does not correlate with task success, and the authors point to the importance of studying deeper features of dialogue structures. We aim to develop a multimodal model able to generate more natural dialogues, namely dialogues that resemble human dialogue strategies. Cognitive studies show that humans do not always act as ``rational'' agents. When referring to objects, they tend to be overspecific and prefer properties irrespectively of their utility for identifying the referent~\cite{gatt2013bayesian}; when searching for information or when learning a language, they tend to follow confirmation-driven strategies. Modelling such behaviour in language learning, \citet{medina2011words} and \citet{trueswell2013propose} propose a procedure in which a single hypothesized word-referent pair is maintained across learning instances, and it is abandoned only if the subsequent instance fails to confirm the pairing, reflecting a `fast mapping' learning process. Inspired by these theories, we propose a model, \textit{Confirm-it}, which generates questions driven by the agent's confirmation bias. \begin{figure}[t]\centering \includegraphics[width=1\linewidth]{images/fig_intro_new_2.pdf} \caption{ At turn 2, among the questions proposed by the beam search, \textit{Confirm-it} chooses $b$ since it is the most suitable one to confirm the current conjecture. } \label{fig:intro} \vspace*{-6pt} \end{figure} Take the example of a referential guessing game in which an agent has to ask questions to guess an object in a given image. \textit{Confirm-it} will ask questions that reinforce its beliefs about which is the target object, till proven otherwise. For instance, in Figure~\ref{fig:intro}, after learning that the target is a living entity (turn 1), the agent conjectures the target is the dog on the right of the picture (though in principle, it could have been any of the candidates). Hence, the decoder generates the question that would let it confirm such belief, ``is it a dog?''. If its expectations are not met (viz., it receives a negative answer to such question -turn 2b), it moves its attention to another candidate object. We do not claim that our choice represents the optimal strategy to play the game, but we believe that it makes the dialogue more natural in its flow and more effective because it takes into account the model's intrinsic biases and intermediate predictions. \cut{\citet{mazuecos-etal-2020-role} compared GDSE against other State-Of-The-Art models playing the Questioner task by measuring the \textit{effectiveness} of each question, defined as the ability of a question to discard candidate objects in the visual scene that are not the target. The authors found that, for the majority of the models considered, successful dialogues do not have a higher percentage of effective questions based on this metric, and that the model closest to humans is VDST~\cite{pang_gw}. VDST uses the probability distribution of the guesser to guide the question generator, and it builds on the assumption that at turn zero all objects are equally probable. We diverge from this assumption but we agree on the importance of establishing a tied connection between the probability distribution assigned by the Guesser to the candidate objects and the generation of questions. \at{Forse questo paragrafo si può accorciare parecchio.} } To evaluate this strategy, we take as a test-bed GuessWhat?!\@ \cite{guesswhat_game}, a two-player game between a Questioner that has to guess the target and an Oracle. The widely used architecture of the Questioner, GDSE, jointly train a Question Generator (QGen) and a Guesser~\cite{shekhar-etal-2019-beyond}. We augment it with a module that simulates an internal oracle. The three modules of the Questioner straightly cooperate one with the other: the internal oracle guides the question generator to ask questions that reinforce the Guesser's beliefs. Concretely, at training time, through Supervised Learning (SL) the QGen learns to ask human-like questions turn-by-turn, the internal oracle to answer them, and the guesser to guess the target object once the dialogue ends. At test time, we exploit a beam search re-ranking algorithm that simulates the single-conjecture learning strategy used by humans. Among the questions the QGen generates via beam search, the algorithm promotes the one that helps the guesser reinforce its belief. We run both quantitative and qualitative analyses, and evaluate the effectiveness of the dialogue strategy by asking humans to guess the target given dialogues generated by \textit{Confirm-it}. We compare results when giving the dialogue generated by \textit{Confirm-it} using the re-ranking algorithm and when generating the question proposed by the plain beam search. We show that the task accuracy both of the conversational agent and human subjects increases when receiving dialogues generated by the \textit{Confirm-it} re-ranking. \section{Model and Re-ranking Strategy} \label{sec:model_experiments} Our model, \textit{Confirm-it}, builds on GDSE~\cite{shekhar-etal-2019-beyond}. In the latter, the hidden state representation produced by a multimodal encoder is used to jointly train the question generator (QGen) and the Guesser module. The image is encoded with a ResNet-152 network~\cite{he2016:resnet} and the dialogue history is encoded via an LSTM network. QGen uses greedy search to generate questions. To this multi-tasking setting, \textit{Confirm-it} adds an internal Oracle trained to answer the question at each turn. Moreover, it relies on beam search and, at inference time, it goes through a re-ranking phase which simulates the single-conjecture learning strategy. The model architecture is provided in the Supplementary Material (SM) and the algorithm is spelled out below. \begin{algorithm} \caption{The \textit{Confirm-it} algorithm}\label{alg:confirm} \begin{algorithmic}[1] \REQUIRE History $H$, Beam size $B$, Max turns $T$, Image $I$, Distractors $D_{1:N-1}$, target $o_t$, \REQUIRE Candidates $C_{1:N} \gets D_{1:N-1}+o_t$ \REQUIRE Internal Oracle $IO$ \REQUIRE Target-aware external $Oracle$ \FOR{$turn = 1:T$} \STATE $\overset{\wedge}p(c_{k_{1:N}}) \gets Guesser(H, I, C_{1:N})$ \STATE $c_{h} \gets argmax(\overset{\wedge}p(c_{k_{1:N}}))$ \STATE $q_{1:B} \gets QGen(H, I)$ \STATE $a_{1:B}^* \gets IO(H+q_{1:B}, c_{h})$ \STATE $H^*_{1:B} = H + (q_{1:B}, a_{1:B}^*)$ \STATE $p^* \gets Guesser(H^*_{1:B}, I, C_{1:N})$ \STATE $Q \gets q_{1:B}[argmax(p^*(c_{h}))]$ \STATE $Oracle$ provides an answer $A$ to $Q$ \STATE $H \gets H+Q+A$ \ENDFOR \end{algorithmic} \end{algorithm} \cut{\citet{shekhar-etal-2019-beyond} propose the Visually-Grounded Dialogue State Encoder model (GDSE). This model uses a visually grounded dialogue state that takes the visual features of the input image and each question-answer pair in the dialogue history to create a shared representation used both for generating a follow-up question (QGen module) and guessing the target object (Guesser module) in a multi-task learning scenario. More specifically, the visual features are extracted with a ResNet-152 network \cite{he2016:resnet} and the dialogue history is encoded with an LSTM network. In this work, we augment the GDSE architecture with the Oracle model so that all the three tasks involved in GuessWhat?!\@(asking questions, guessing the target, answering questions) are performed by the same model (GDSE-v3). We adopt the \textit{modulo-n} training proposed in \citet{shekhar-etal-2019-beyond} to address the issue of dealing with tasks with different levels of difficulty. We use $n=7$ and we train the Oracle module with the same frequency as the Guesser module. In the Supplementary Material (SM) we report the model's architecture.} Algorithm \ref{alg:confirm} describes the beam search re-ranking algorithm used by \textit{Confirm-it} to promote the generation of an effective dialogue strategy. Given an image, a set of candidate objects, a target object $o_t$, and a beam size of $B$, at each dialogue turn the model predicts a probability distribution over the set of candidate objects given the current dialogue history. The candidate that receives the highest probability is considered the model's \textit{hypothesis} $c_{h}$. The QGen outputs $B$ questions, ordered by their probability. Each of these questions is answered by the model's internal Oracle that receives $c_{h}$ as the target object. Among these $B$ questions, \textit{Confirm-it} selects the question $Q$ that, paired with the answer provided by the internal Oracle, increases the most the model's confidence over $c_{h}$, measured as the probability assigned by the Guesser. The external Oracle (who is aware of the real target object $o_t$) answers $Q$, and this new question-answer pair is appended to the dialogue history. In SM we provide a step-by-step example of how \textit{Confirm-it} works. None of the features of our case-study are crucial for the method to be applied to other tasks, e.g. it does need the questions to be polar, it does not need the questions to be visually grounded, it does not need the dialogue to be asymmetrical. \paragraph{Implementation details\footnote{Our code is available at: \url{https://github.com/albertotestoni/confirm_it}}} For the multi-task training, we adopt the \textit{modulo-n} training proposed in \citet{shekhar-etal-2019-beyond}, i.e. we train the Oracle and guesser modules every $n$ (=7) epochs of the QGen. At inference time, we use a beam size of 3 and let the model generate dialogues of 5 turns. \section{Related Work} \label{sec:related} For open-ended language generation, \citet{holt:thecu20} claim that decoding strategies that optimize for output with high probability (like beam search) lead to highly deteriorated texts, since the highest scores are often assigned to generic, incoherent, and repetitive sequences. Several works propose reranking strategies on the set of hypotheses produced by the beam search following different criteria~\cite{dusek-jurcicek-2016-sequence,blain2017exploring,agarwal-etal-2018-char2char,BorgeaudE20,HargreavesVE21} to improve both the performance on a given task and the quality of the output. In this work, we present a cognitively-inspired reranking technique for a visual dialogue questioner agent. In visual dialogue systems, the quality of the output has been improved mainly by aiming at reducing repetitions in the output. This goal has been achieved through Reinforcement Learning by adding auxiliary objective functions~\cite{murahari-etal-2019-improving}, intermediate rewards \cite{zang18}, regularized information gain techniques \cite{shukla-etal-2019-ask}, or intermediate probabilities with an attention mechanism \cite{pang_gw}. Different from these works, we do not use the Reinforcement Learning paradigm and, instead of focusing on improving surface-level features, we indirectly operate on the dialogue structure. \citet{ruggeri2015children} studied the way children and young adults search for information while asking yes-no questions given a set of candidate hypotheses. The authors found that when prior knowledge favours some hypotheses over others, participants asked more hypothesis-scanning questions (i.e., questions that are tentative solutions, with a specific hypothesis that is directly tested). This is in line with the observation in~\citet{baron:think10} that humans phrase questions to receive an affirmative answer that supports their theory, and with the broader finding in ~\citet{wason60} that they tend to select the information that is in accord with their prior beliefs. Inspired by these studies, we propose a new dialogue strategy for playing referential guessing games by exploiting the probabilities assigned by the Guesser module to different candidate objects. \cut{ This is line with the more general observation on humans being driven by confirmation (or verification) biases. For instance, when searching for information, they phrase questions to receive an affirmative answer that supports their theory~\cite{baron:think10}. In other words, they tend to select the information that supports their view, that is in accord with their prior beliefs~\cite{wason60}.} \cut{This widely used confirmation-driven approach has been found also in cognitive studies of language learning. These studies claim that humans follow the single-conjecture learning procedure when acquiring a new word meaning. In other words, learners hypothesize a single word-referent pairing based on conceptual and referential biases and abandon such hypothesis only if the subsequent instance fails to confirm such pairing (e.g. \citealt{medina2011words,trueswell2013propose}).} \section{Results} \label{sec:results} \begin{table}[] \centering \begin{tabular}{c|c} \hline \textbf{Decoding Strategy} & \textbf{Accuracy 5Q} \\ \hline \textit{Confirm-it} & 51.38 \\ \hline Beam Search & 47.03 \\ \hline Random Re-Rank & 46.29 \\ \hline Greedy Search & 46.58 \\ \hline \end{tabular} \caption{Accuracy results of \textit{Confirm-it} on the GuessWhat?!\@ test set when generating 5 questions per dialogue following different decoding strategies. \textit{Confirm-it} refers to the accuracy achieved by our re-ranking algorithm compare to a random re-ranking of candidate questions, plain beam search, and greedy search.} \label{tab:accuracy} \end{table} \begin{table*}[] \centering \small \begin{tabular}{|c|c|c|c|c|c|c|} \hline & \begin{tabular}[c]{@{}c@{}}Human\\ Accuracy $\uparrow$ \end{tabular} & \begin{tabular}[c]{@{}c@{}}\% games with\\ repetitions $\downarrow$ \end{tabular} & CHAIR-s $\downarrow$ & \begin{tabular}[c]{@{}c@{}}\% Yes\\ Last Turn$\uparrow$ \end{tabular} & \begin{tabular}[c]{@{}c@{}} \% novel $(q_{t-1},q_t)$\\ per dialogue $\uparrow$\end{tabular} \\ \hline Beam Search& 70.8 & 38.50 & 31.07 & 71.87 & 36.75 \\ \hline \textit{Confirm-it}& 77.0 & 30.36 & 28.46 & 76.68 & 48.25 \\ \hline Human Dialogues & 96.0 & 0.01& 7.45 & 86.64 &-\\\hline \end{tabular} \caption{ \textit{Human Accuracy} refers to the task accuracy achieved by human annotators when receiving dialogues generated by the plain Beam Search, \textit{Confirm-it} re-ranking, or the original dialogues produced by human players from the GuessWhat?! test set. The other columns report relevant statistics of the dialogues: percentage of games with at least one repeated question verbatim, hallucination rate (CHAIR-s), percentage of positive answers in the final turn (\% yes Last Turn), and percentage of consecutive questions not seen at training time (lexical overlap, \% novel $q_{t-1},q_t$ per dialogue). } \label{tab:analysis} \end{table*} We study to what extent the re-ranking phase lets the model generate more effective and more natural dialogues. To this end, we evaluate the \textit{Confirm-it} task-accuracy with and without the ranking phase\footnote{Remember that \textit{Confirm-it} is based on the GDSE architecture. For comparison, the accuracy reached by GDSE is 45.55\% with greedy search and 46.40\% using beam search decoding.} and report qualitative analyses of the dialogues. \paragraph{Task-accuracy} Table~\ref{tab:accuracy} shows the task accuracy results of our model in the GuessWhat?!\@ game. When the model undergoes the re-ranking phase, \textit{Confirm-it} accuracy has an increase of +4.35\% with respect to what it achieves when it outputs the question selected by the plain beam search, and an increase of +4.8\% against greedy search. Note that, instead, randomly re-ranking the set of questions lowers the performance. This result shows that confirmation-driven strategies help generate more effective dialogues. Interestingly, our re-ranking method does not require additional training compared to the SL paradigm. \begin{figure}[t]\centering \includegraphics[width=0.93\linewidth]{images/comparison_example_1.pdf} \caption{Through re-ranking, dialogues become more effective and more natural. The target object is highlighted in green.} \label{fig:comparison} \end{figure} \paragraph{More Effective Dialogues} To verify whether the improvement of \textit{Confirm-it} is really due to the generation of more effective dialogues to solve the guessing task, we asked human subjects to guess the target given a dialogue. We sampled 500 games from the GuessWhat?!\@ test set containing less than 7 candidate objects. Each participant played 150 games equally divided among dialogues generated by the model with the plain beam search, with our re-ranking strategy, and by the GuessWhat?!\@ human players (taken from the original test set). We made sure no participant played the same game more than once. In total, 10 English proficient volunteers within our organization joined the experiment. As we can see from Table \ref{tab:analysis}, human annotators reach an accuracy of 70.8\% in identifying the target object when receiving dialogues generated by beam search and 77\% with \textit{Confirm-it}, suggesting that the re-ranking phase let the model generate more effective dialogues. The accuracy that the annotators achieve when playing the game with dialogues extracted from the original GuessWhat?!\@ test set (and thus generated by human players) is much higher (96\%). \cut{In total, 10 English proficient volunteers within our organization joined the experiment. They were instructed on the GuessWhat?!\@ task and each participant played on average 50 games with dialogues generated by beam search and 50 by \textit{Confirm-it}. } \cut{\at{To be removed? -->} Moreover, we asked participants to compare two dialogues (one generated with beam search and one with our algorithm) given an image and a target object and to select the dialogue that sounds more natural to identify the target. We found that in the majority of the cases, humans preferred dialogues generated by \textit{Confirm-it} (54.2\% vs. 45.8\%). In SM, we report an example of the annotation carried out by human subjects. } \cut{\at{ Forse sono io che devo ancora metabolizzare, ma non mi torna la descrizione dei risultati se qui non scriviamo qualcosa tipo: In the following, we use ``Beam Search'' to present the results obtained with a beam search decoding without re-ranking. We use instead ``\textit{Confirm-it}'' for the results obtained with the re-ranking algorithm described above.}} \paragraph{More Natural Dialogues} Figure~\ref{fig:comparison} reports a sample game that illustrates the difference between a dialogue generated by human players, one generated by the plain beam search, and one by our re-ranking algorithm. The dialogue generated by beam search contains a repetition (``is it a glass?''), it asks about entities not present in the image (``chair'' and ``glasses'') and it ends with a non-conclusive negatively answered question. These features contribute to making the dialogues sound unnatural. We check whether the re-ranking phase helps our model to get closer to human dialogues with respect to these features. To this end, we compute the percentage of games with repeated questions and with the last turn containing a positively answered question. Moreover, we employ CHAIR-s to measure the percentage of hallucinated entities in a sequence, originally proposed in ~\citet{rohrbach-etal-2018-object} for image captioning and recently applied also to GuessWhat?!\@ \cite{testoni-bernardi-2021-ive}. CHAIR-S is defined as the number of dialogues with at last one hallucinated entity divided by the total number of dialogues. As we can see from Table~\ref{tab:analysis}, dialogues generated by \textit{Confirm-it} contain fewer games with at least one repeated question compared to the beam search setting (-8.14\%), fewer games with hallucinated entities (-2.61\%)\footnote{\citet{rohrbach-etal-2018-object} propose another variant of the CHAIR metric called CHAIR-i (per-instance), defined as the number of hallucinated objects in a sequence divided by the total number of objects mentioned. CHAIR-i results: 18.28 (Beam Search), 15.02 (\textit{Confirm-it}), 4.11 (Human Dialogues).}, and more games with the last turn containing a positively answered question (71.87\% vs. 76.68\%). The reduced number of hallucinations is a direct consequence of the \textit{Confirm-it} strategy: following up on a single object through the dialogue, the model is less likely to engage in spurious exchanges on irrelevant objects. Though this strategy continuously looks for confirmations, it is worth noting that it does not increase the number of repetitions, which instead are significantly reduced. This is an interesting property emerging from the interplay between the internal Oracle and the re-ranking strategy, which suggests that asking the very same question more than once in a dialogue does not increase the model's confidence in its hypothesis. \paragraph{Qualitative Analysis of the Strategy} We also evaluated the strategy followed by \textit{Confirm-it} by looking at the model's decisions throughout the dialogue. Interestingly, the model does not select only questions for which it expects a positive answer, though they are the majority (67\%). See the SM, for a game in which the re-ranking promoted a question answered negatively by the internal Oracle. Moreover, though the model looks for confirmations, it properly updates its beliefs when disconfirmed: when the model receives from its interlocutor an answer different from the one it expects (based on its internal Oracle), in 70\% of the cases the Guesser changes the probabilities over the candidates accordingly, i.e., it assigns the highest probability to a new candidate object. Finally, the use of a human-like strategy does not imply having learned to simply mimic human dialogues from the training set: the re-ranking shows an absolute increase of +12\% in the number of pairs of consecutive questions not seen during training (see Table~\ref{tab:analysis}). \section{Task and Dataset} \label{sec:task_data} GuessWhat?!\@ \citep{guesswhat_game} is an asymmetric game involving two human participants who see a real-world image from MSCOCO \cite{lin:2014}. One of the participants (the Oracle) is secretly assigned a target object in the image, while the other participant (the Questioner) has to guess it by asking binary (Yes/No) questions to the Oracle. The GuessWhat?!\@ dataset consists of more than 150k human-human English dialogues containing on average 5.3 questions per dialogue.
{'timestamp': '2021-09-14T02:14:22', 'yymm': '2109', 'arxiv_id': '2109.05312', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05312'}
arxiv
\section{Introduction} \label{sec:introduction} Learning high-quality sentence embeddings is a fundamental task in Natural Language Processing. The goal is to map semantically similar sentences close together and dissimilar sentences farther apart in the representation space. Many recent successes have been achieved by training on the NLI datasets \citep{bowman2015large, williams2017broad,wang2018glue}, where the task is often to classify each sentence pair into one of three categories: entailment, contradiction, or neutral. \begin{figure}[htbp] \centering \begin{subfigure}{0.46\textwidth} \centering \includegraphics[scale=0.33]{./figures/pillustration.pdf} \caption{Spearman Correlation Evaluation on STS.} \label{fig:stshist} \end{subfigure} \vspace{0.2cm} \begin{subfigure}{0.46\textwidth} \centering \includegraphics[scale=0.31]{./figures/bertbase_stackoverflow_2.pdf} \caption{TSNE visualization of the StackOverflow embeddings.} \label{fig:tsne_stackoverflow} \end{subfigure} \caption{Simultaneoulsy encoding semantic categorical structure and pairwise entailment and contradiction understanding into embeddings. } \label{fig:motivation_validation} \end{figure} Despite promising results, prior work \citep{conneau2017supervised, cer2018universal, reimers-2019-sentence-bert} share a common weakness: the sentences forming a contradiction pair may not necessarily belong to different semantic categories. Consequently, optimizing the model for semantic entailment and contradiction understanding alone is inadequate to encode the high-level categorical concepts into the representations. Moreover, the vanilla siamese (triplet) loss only learns from the individual sentence pairs (triplets), which often requires substantial training examples to achieve competitive performance \citep{oh2016deep,thakur2020augmented}. As shown in Section \ref{subsec:clustering}, the siamese loss can sometimes drive a model to bad local optima where the performance of high-level semantic concept encoding is degraded when compared with its baseline counterpart. In this paper, we take inspiration from self-supervised contrastive learning \citep{bachman2019learning,he2020momentum, chen2020simple} and propose jointly optimizing the pairwise semantic reasoning objective with an \textit{instance discrimination loss}. We name our approach Pairwise Supervised Contrastive Learning (PairSupCon). \dejiao{As noticed by the recent work \citep{wu2018unsupervised, zhang-etal-2021-supporting}, instance discrimination learning can implicitly group similar instances together in the representation space without any explicit learning force directs to do so.} PairSupCon leverages this implicit grouping effect to bring together representations from the same semantic category while, simultaneously enhancing the semantic entailment and contradiction reasoning capability of the model. Although the prior work mainly focuses on pairwise semantic similarity related evaluations, we argue in this paper that the capability of encoding the high-level categorical semantic concept into the representations is an equally important aspect for evaluations. As shown in Section \ref{sec:experiments}, the previous state-of-the-art model that performs best on the semantic textual similarity (STS) tasks results in degenerated embeddings of the categorical semantic structure. On the other hand, better capturing the high-level semantic concepts can in turn promote better performance of the low-level semantic entailment and contradiction reasoning. This assumption is consistent with how human categorize objects in a top-down reasoning manner. We further validate our assumption in Section \ref{sec:experiments}, where PairSupCon achieves an averaged improvement of $10\%-13\%$ over the prior work when evaluated on eight short text clustering tasks, and yields $5\%-6\%$ averaged improvement on seven STS tasks. \section{Related Work} \paragraph{Sentence Representation Learning with NLI}{ The suitability of leveraging NLI to promote better sentence representation learning is first observed by InferSent \citep{conneau2017supervised}, where a siamese BiLSTM network is optimized in a supervised manner with the semantic entailment and contraction classification objective. Universal Sentence Encoder \citep{cer2018universal} later augments an unsupervised learning objective with the supervised learning on NLI, and shows better transfer performance on various downstream tasks. More recently, SBERT \citep{reimers2019sentence} finetunes a siamese BERT \citep{devlin2018bert} model on NLI and sets new state-of-the-art results. However, SBERT as well as the above work adopt the vanilla siamese or triplet loss, which often suffer from slow convergence and bad local optima \citep{oh2016deep,thakur2020augmented}. } \paragraph{Self-Supervised Instance Discrimination}{ Another relevant line of work is self-supervised contrastive learning, which essentially solves an instance discrimination task that targets at discriminating each positive pair from all negative pairs within each batch of data \citep{oord2018representation,bachman2019learning,he2020momentum, chen2020simple}. Owing to their notable successes, self-supervised instance discrimination has become a prominent pre-training strategy for providing effective representations for a wide range of downstream tasks. While recent successes are primarily driven by the computer vision domain, there is an increasing interest in leveraging variant instance discrimination tasks to support Pretraining Language Models (PLMs) \citep{meng2021coco,giorgi2020declutr,wu2020clear,rethmeier2021primer}. Our proposal can be seen as complementary to this stream of work, considering that the instance discrimination learning based PLMs provide a good foundation for PairSupCon to further enhance the sentence representation quality by further learning on NLI. As demonstrated in Section \ref{sec:experiments}, by training a pre-trained BERT-base model for less than an hour, PairSupCon attains substantial improvement on various downstream tasks that involve sentence semantics understanding at different granularities. } \begin{figure*} \centering \begin{subfigure}{0.49\textwidth} \centering \includegraphics[scale=0.40]{./figures/model.pdf} \caption{Joint optimization framework of PairSupCon.} \end{subfigure} \begin{subfigure}{0.49\textwidth} \centering \includegraphics[scale=0.39]{./figures/nli_samples.pdf} \caption{Entailment and contradiction samples.} \end{subfigure} \caption{Illustration of PairSupCon. \textbf{(a):} Training framework of PairSupCon. \textbf{(b)}: Despite the entailment sample is more similar to the anchor, both the contradiction and entailment samples are likely from the same semantic category as the anchor.} \label{fig:pairsupcon_model} \end{figure*} \paragraph{Deep Metric Learning}{ Inspired by the pioneering work of \citep{hadsell2006dimensionality,weinberger2009distance}, many recent works have shown significant benefit in learning deep representations using either siamese loss or triplet loss. However, both losses learn from individual pairs or triplets, which often require substantial training data to achieve competitive performance. Two different streams of work have been proposed to tackle this issue, with the shared focus on nontrivial pairs or triplets optimization. \citet{wang2014learning,schroff2015facenet,wu2017sampling,harwood2017smart} propose hard negative or hard positive mining that often requires expensive sampling. \citet{oh2016deep} extends the vanilla triplet loss by contrasting each positive example against multiple negatives. Our work leverages the strength of both lines, with the key difference being the above work requires categorical level supervision for selecting hard negatives. To be more specific, negative samples that have different categorical labels from the anchor but are currently mapped close to the anchor in the representation space, are likely to be more useful and hence being sampled. However, there are no categorical labels available in NLI. We thereby contrast each positive pair against multiple negatives collected using an unsupervised importance sampling strategy, for which the hypothesis is that hard negatives are more likely to locate close to the anchor. The effectiveness of this assumption is investigated in Section \ref{subsec:ablation}. } \section{Model} Following SBERT \citep{reimers-2019-sentence-bert}, we adopt the SNLI \citep{bowman2015large} and MNLI \citep{williams2017broad} as our training data, and refer the combined data as NLI for convenience. The NLI data consists of labeled sentence pairs and each can be presented in the form: (\textit{premise, hypothesis, label}). The premise sentences are selected from existing text sources and each premise sentence is paired with variant hypothesis sentences composed by human annotators. Each label indicates the hypothesis type and categorizes semantic relation of the associated premise and hypothesis sentence pair into one of three categories: \textit{entailment, contradiction}, and \textit{neural}, correspondingly. Prior work solely optimizes either siamese loss or triplet loss on NLI. We instead aiming to leverage the implicit grouping effect of instance discrimination learning to better capture the high-level categorical semantic structure of data while, simultaneously promoting better convergence of the low-level semantic textual entailment and contradiction reasoning objective. \subsection{Instance Discrimination} We leverage the \textit{positive (entailment)} pairs of NLI to optimize an instance discrimination objective which tries to separate each positive pair apart from all other sentences. Let $\mathcal{D} = \left\{(x_j, x_{j'}), y_j\right\}_{j=1}^{M}$ denote a randomly sampled minibatch, with $y_i= \pm 1$ indicating an entailment or contradiction pair. Then for a premise sentence $x_i$ within a \textit{positive} pair $(x_i, x_{i'})$, we aim to separate its hypothesis sentence $x_i'$ from all other $2M$-2 sentences within the same batch $\mathcal{D}$. To be more specific, let $\mathcal{I} = \left\{i, i'\right\}_{i=1}^{M}$ denote the corresponded indices of the sentence pairs in $\mathcal{D}$, we then minimize the following for $x_i$, \begin{align} \ell_{\text{ID}}^i = -\log \frac{\exp(s(z_i, z_{i'})/\tau)}{\sum_{j \in \mathcal{I}\setminus i} \exp(s(z_{i}, z_j)/\tau)}\;. \label{eq:pairsupcon_pos} \end{align} In the above equation, $z_j = h(\psi(x_j))$ denotes the output of the instance discrimination head in Figure \ref{fig:pairsupcon_model}, $\tau$ denotes the temperature parameter, and $s(\cdot)$ is chosen as the cosine similarity, {\em i.e.,~} $\text{s}(\cdot) = z_i^Tz_{i'} / \|z_i\| \|z_{i'}\|$. Notice that Equation (\ref{eq:pairsupcon_pos}) can be interpreted as a ($2M$--1)-way softmax based classification loss of classifying $z_i$ as $z_i'$. Similarly, for the hypothesis sentence $(x_{i'})$ we also try to discriminate its premise $(x_{i})$ from all the other sentences in $\mathcal{D}$. We denote the corresponding loss as $\ell_{\text{ID}}^{i'}$ that is defined by exchanging the roles of instances $x_{i'}$ and $x_{i}$ in Equation \eqref{eq:pairsupcon_pos}, respectively. In summary, the final instance discrimination loss is averaged over all positive pairs in $\mathcal{D}$, \begin{align} \mathcal{L}_{\text{ID}} = \frac{1}{P_M}\sum_{i=1}^{M} \mathbbm{1}_{y_i=1} \cdot \left(\ell_{\text{ID}}^{i} + \ell_{\text{ID}}^{i'}\right)\;. \label{eq:pairsupcon_batchloss_pos} \end{align} Here, $\mathbbm{1}_{(\cdot)}$ denotes the indicator function, and $P_M$ is the number of positive pairs in $\mathcal{D}$. As demonstrated in Section \ref{sec:experiments}, optimizing the above loss not only helps implicitly encode categorical semantic structure into representations, but also promotes better pairwise semantic reasoning capability, though no pairwise supervision except the true entailment labels are present to the model. \subsection{Learning from Hard Negatives} \label{sec:hargneg_sample} Notice that Eq (\ref{eq:pairsupcon_pos}) can be rewritten as \begin{align} &\ell^i_{\text{ID}} = \nonumber \\ &\log\left(1 + \sum_{j \neq i, i'}\exp\left[\frac{\text{s}(z_{i}, z_j)- \text{s}(z_i, z_{i'})}{\tau}\right]\right)\;. \nonumber \end{align} It can be interpreted as extending the vanilla triplet loss by treating the other $2M$--2 samples within the same minibatch as negatives. However, the negatives are uniformly sampled from the training data, regardless of how informative they are. Ideally, we want to focus on hard negatives that are from different semantic groups but are mapped close to the anchor, {\em i.e.,~} $z_i$, in the representation space. Although the categorical level supervision is not available in NLI, we approximate the importance of the negative samples via the following, \begin{align} \label{eq:weighted_instdisc} &\ell^i_{\text{wID}}= \\ & \log\left(1 + \sum_{j \neq i, i'}\exp\left[\frac{\alpha_j\text{s}(z_{i}, z_j)- \text{s}(z_i, z_{i'})}{\tau}\right]\right)\;. \nonumber \end{align} Here $\alpha_j = \frac{\exp(\text{s}(z_i, z_{j})/\tau)}{\frac{1}{2M-2}\sum_{k \neq i, i'} \exp(\text{s}(z_{i}, z_k)/\tau)}$, which can be interpreted as the relative importance of $z_j$ among all $2M$-2 negatives of anchor $z_{i}$. The assumption is that hard negatives are more likely to be those that are located close to the anchor in the representation space. Although there might exists false negatives, {\em i.e.,~} those located close to the anchor $z_i$ but are from the same category, the probability is low as long as the underlying number of categories of the training data is not too small and each minibatch $\mathcal{D}$ is uniformly sampled. \subsection{Entailment and Contradiction Reasoning} The instance discrimination loss mainly focuses on separating each positive pair apart from the others, whereas there is no explicit force in discriminating contradiction and entailment. To this end, we jointly optimize a pairwise entailment and contradiction reasoning objective. We adopt the softmax-based cross-entropy to form the pairwise classification objective. Let $u_i=\psi(x_i)$ denote the representation of sentence $x_i$, then for each labeled sentence pair $(x_i, x_{i'}, y_i)$ we minimize the following, \begin{align} \ell_{\text{C}}^i = \text{CE}\left(f(u_i, u_{i'}, |u_i-u_{i'}|), y_i\right)\;. \label{eq:pair_classify} \end{align} Here $f$ denotes the linear classification head in Figure \ref{fig:motivation_validation}, and CE is the cross-entropy loss. Different from \citet{reimers2019sentence}, we exclude the neural pairs from the original training set and focus on the binary classification of semantic entailment and contradiction only. Our motivation is that the concept semantic neural can be well captured by the instance discrimination loss. Therefore, we drop the neural pairs from the training data to reduce the functional redundancy of the two losses in PairSupCon and improve the learning efficiency as well. \paragraph{Overall loss}{In summary, our overall loss is \begin{align} \mathcal{L} = \sum_{i=1}^{M} \ell_{\text{C}}^i + \beta \mathbbm{1}_{y_i=1} \cdot \left(\ell_{\text{wID}}^{i} + \ell_{\text{wID}}^{i'}\right)\;, \end{align} where $\ell_{\text{C}}^i$ and $\ell_{\text{wID}}^{i}, \ell_{\text{wID}}^{i'}$ are defined in Equations (\ref{eq:pair_classify}) and (\ref{eq:weighted_instdisc}), respectively. In the above equation, $\beta$ balances between the capability of pairwise semantic entailment and contradiction reasoning, and the capability of the high-level categorical semantic structure encoding. We dive deep into the trade-off between these two aspects by evaluating PairSupCon with different $\beta$ values in Section \ref{subsec:ablation}, and show how different $\beta$ values can benefit different downstream tasks. Unless otherwise specified, we set $\beta=1$ in this paper for the purpose of providing effective representations to various downstream tasks instead of being tailored to any specific ones. } \begin{table*}[htbp] \begin{center} \begin{tabular}{lccccccccc} & \textbf{AG}& \textbf{SS}&\textbf{SO}& \textbf{Bio}&\textbf{Tweet}& \textbf{G-TS}&\textbf{G-S}& \textbf{G-T}& \textbf{Avg.} \\ \cline{2-10} BERT$_{\text{distil} \cdot \text{base}}$ &\textbf{85.8}& 68.4& 20.7& 32.0& 47.5& 63.2& 56.8& 50.0& 53.1\\ SBERT$^{\diamondsuit}_{\text{distil} \cdot \text{base}}$&61.1& 54.9& 32.2& 32.6& 45.9& 56.7& 50.7& 48.2& 47.8 \\ SimCSE$^{\spadesuit}$&-&-&-&-&-&-&-&-&- \\ \hline \textbf{PairSupCon}$_{\text{distil} \cdot \text{base}}$ &82.5& \textbf{71.5}& \textbf{63.6}& \textbf{39.0}& \textbf{54.2}& \textbf{69.1}& \textbf{63.6}& \textbf{59.7}& \textbf{62.9} \\ \\ BERT$_{\text{base}}$ &79.7& 64.0& 21.8& 32.3& 45.1& 61.0& 55.8& 46.7& 50.8 \\ SBERT$^{\diamondsuit}_{\text{base}}$&65.8& 62.5& 29.6& 31.9& 45.6& 56.5& 50.2& 49.3& 48.9 \\ SimCSE$^{\spadesuit}$& 82.4& 67.3& 49.0& 37.5& 56.1& 68.1& 63.2& 59.6& 60.4 \\ \hline \textbf{PairSupCon}$_{\text{base}}$ &\textbf{83.0}& \textbf{73.6}& \textbf{63.8}& \textbf{38.8}& \textbf{55.7}& \textbf{69.4}& \textbf{64.5}& \textbf{60.4}& \textbf{63.7} \\ \\ BERT$_{\text{large}}$ &83.1& 66.5& 26.4& 31.4& 44.3& 62.3& 55.8& 46.4& 52.0 \\ SBERT$^{\diamondsuit}_{\text{large}}$ &66.6& 63.7& 37.7& 34.6& 47.7& 59.1& 53.8& 49.5& 51.6 \\ SimCSE$^{\spadesuit}$& 82.7& 66.3& 49.0& 40.5& \textbf{57.9}& 68.1& 62.4& 60.8& 61.0 \\ \hline \textbf{PairSupCon}$_{\text{large}}$ &\textbf{84.2}& \textbf{75.7}& \textbf{63.9}& \textbf{41.8}& 55.8& \textbf{70.4}& \textbf{64.8}& \textbf{61.3}& \textbf{64.7} \\ \end{tabular} \caption{Clustering accuracy reported on eight shorttext clustering datasets. The results are averaged over 10 clustering runs using KMeans with independent seeds. ${\diamondsuit}$ and $\spadesuit$: results evaluated on the checkpoints provided by \citet{reimers-2019-sentence-bert} and \citet{gao2021simcse}, respectively. } \label{tab:Cluster_Eval} \end{center} \end{table*} \section{Experiments} \label{sec:experiments} \paragraph{Baselines}{In this section, we mainly investigate the effective strategies of leveraging the labeled NLI data to enhance the sentence representations of the pre-trained language models (PLMs). We compare PairSupCon against the vanilla BERT \citep{devlin2018bert, sanh2019distilbert} models and the previous state-of-the-art approach, SBERT \citep{reimers-2019-sentence-bert}. We noticed a concurrent work SimCSE \citep{gao2021simcse} when we were preparing this submission. Although SimCSE also leverages the instance discrimination learning to improve the sentence embeddings, it shares a different motivation and focus than ours. We compare PairSupCon against SimCSE to show how different instance discrimination based approaches enhance the sentence representations differently, while our contribution is claimed over the previous SOTA models. Please refer to Appendix \ref{appendix:implementation} for the details of our implementation. } \begin{table}[!htbp] \begin{center} {\scriptsize {\begin{tabular}{l|ccccc} \hline Dataset & $N$ & $W$ & $C$ & L &S \\ \hline AgNews (AG) &8K &23 &4 & 2K &2K \\ StackOverflow (SO) & 20K &8 & 20 &1K &1K \\ Biomedical (Bio)& 20K &13 & 20 &1K &1K \\ SearchSnippets (SS)& 12K &18 & 8 & 2.66K & .37K \\ GooglenewsTS (G-TS)& 11K & 28 & 152 & 430 & 3 \\ GooglenewsS (G-S)& 11K & 22 & 152 & 430 & 3 \\ GooglenewsT (G-T)& 11K & 6 & 152 & 430 & 3 \\ Tweet (Tweet)& 5K & 8 & 89 & 249& 1 \\ \hline \end{tabular}}} \caption{Statistics of eight short text clustering datasets. $N$: number of text examples; $W$: average number of words contained in each text example; $C$ number of clusters; L: the size of the largest cluster; and $S$: the size of the smallest cluster. } \label{tab:cluster_datastats} \end{center} \end{table} \subsection{Clustering} \label{subsec:clustering} \paragraph{Motivation}{Existing work mainly focuses on the semantic similarity (a.k.a STS) related tasks. We argue that an equally important aspect of sentence representation evaluation -- the capability of encoding the high-level categorical structure into the representations, has so far been neglected. Desirably, a model should map the instances from the same category close together in the representation space while mapping those from different categories farther apart. This expectation aligns well with the underlying assumption of clustering and is consistent with how human categorizes data. We evaluate the capabilities of categorical concept embedding using K-Means \citep{macqueen1967some,lloyd1982least}, given its simplicity and the fact that the algorithm itself manifests the above expectation. We consider eight benchmark datasets for short text clustering. As indicated in Table \ref{tab:cluster_datastats}\footnote{Please refer to Appendix \ref{appendix:cluster_data_stats} for more details.}, the datasets present the desired diversities of both the size of each cluster and the number of clusters of each dataset. Furthermore, each text instance consists of 6 to 28 words when averaged within each dataset, which well covers the spectrum of NLI where each instance has 12 words on average. Therefore, we believe the proposed datasets can provide an informative evaluation on whether an embedding model is capable of capturing the high-level categorical concept. } \begin{table*}[htbp] \begin{center} \begin{tabular}{lcccccccc} & \textbf{STS12}& \textbf{STS13}&\textbf{STS14}& \textbf{STS15}&\textbf{STS16}& \textbf{SICK-R}&\textbf{STS-B}& \textbf{Avg.} \\ \cline{2-9} BERT$_{\text{distil} \cdot \text{base}}$ &43.4& 64.9& 54.1& 66.6& 68.5& 63.5& 57.2& 59.8 \\ SBERT$^{\diamondsuit}_{\text{distil} \cdot \text{base}}$&69.8& 72.2& 70.7& 79.9& 75.4& 74.5& 78.4& 74.4 \\ SimCSE$^{\spadesuit}$&-&-&-&-&-&-&-&- \\ \hline \textbf{PairSupCon}$_{\text{distil} \cdot \text{base}}$ &\textbf{73.6}& \textbf{84.1}& \textbf{78.3}& \textbf{84.4}& \textbf{81.8}& \textbf{77.8}& \textbf{82.3}& \textbf{80.3} \\ \\ BERT$_{\text{base}}$ &30.9& 59.9& 47.7& 60.3& 63.7& 58.2& 47.3& 52.6 \\ SBERT$^{\diamondsuit}_{\text{base}}$ &71.0& 76.5& 73.2& 79.1& 74.3& 72.9& 77.0& 74.9 \\ SimCSE$^{\spadesuit}$& \textbf{75.3}& \textbf{84.7}& \textbf{80.2}& \textbf{85.4}& 80.8& \textbf{80.4}& \textbf{84.3}& \textbf{81.6}\\ \hline \textbf{PairSupCon}$_{\text{base}}$ &74.3& 84.4& 79.0& 84.8& \textbf{81.4}& 79.0& 82.6& 80.8 \\ \\ BERT$_{\text{large}}$ &27.7& 55.8& 44.5& 51.7& 61.9& 53.9& 47.0& 48.9 \\ SBERT$^{\diamondsuit}_{\text{large}}$ &72.3& 78.5& 74.9& 81.0& 76.3& 73.8& 79.2& 76.5 \\ SimCSE$^{\spadesuit}$&\textbf{75.8}& \textbf{86.3}& \textbf{80.4}& \textbf{86.1}& 80.9& \textbf{81.1}& \textbf{84.9}& \textbf{82.2} \\ \hline \textbf{PairSupCon}$_{\text{large}}$ &74.2& 85.8& 79.5& 85.5& \textbf{81.7}& 80.4& 83.7& 81.5 \\ \end{tabular} \caption{Spearman rank correlation between the cosine similarity of sentence representations and the ground truth labels on seven Semantic Textual Similarity (STS) tasks. $\diamondsuit$ and $\spadesuit$: results evaluated on the checkpoints provided by \citet{reimers-2019-sentence-bert} and \citet{gao2021simcse}, respectively. } \label{tab:STS_compare} \end{center} \end{table*} \paragraph{Evaluation Results}{The evaluation results are summarized in Table \ref{tab:Cluster_Eval}. We run K-Means with the scikit-learn package \citep{scikit-learn} on the representations provided by each model and report the clustering accuracy \footnote{We computed the clustering accuracy using the Hungarian algorithm \citep{munkres1957algorithms}.} averaged over 10 independent runs. \footnote{We randomly select 10 independent seeds and fix them for all evaluations} As Table \ref{tab:Cluster_Eval} indicates, in comparison with the vanilla BERT models, SBERT results in degenerated embedding of the categorical semantic structure by simply optimizing the pairwise siamese loss. One possible reason is that SBERT uses a large learning rate (2e-05) to optimize the transformer, which can cause catastrophic forgetting of the knowledge acquired in the original BERT models. We find using a smaller learning rate for the backbone can consistently improve the performance of SBERT (see the performance of BERT-base with "Classificaiton" in Table \ref{tab:PairSupCon_ablation}). Nevertheless, PairSupCon leads to an averaged improvement of $10.8\%$ to $15.2\%$ over SBERT, which validates our motivation in leveraging the implicit grouping effect of the instance discrimination learning to better encode the high-level semantic concepts into representations. Moreover, PairSupCon also attains better performance than SimCSE, and we suspect this is because PairSupCon better leverages the training data. Specifically, PairSupCon aims to discriminate an positive (entailment) sentence pair apart from all other sentences, no matter they are premises or hypotheses. In contrast, SimCSE only separates a premise from the other premises through their entailment and contradiction hypotheses, while there is no explicit instance discrimination force within the premises or the hypotheses alone. Considering the statistic data difference \citep{williams2017broad} between premises and hypotheses, PairSupCon can potentially better capture categorical semantic concepts by leveraging additional intrinsic semantic properties of the premises or the hypotheses that are undiscovered by SimCSE. } \begin{figure*}[htbp] \centering \begin{subfigure}{0.92\textwidth} \centering \includegraphics[scale=0.36]{./figures/spearman_ablation.pdf} \label{fig:stshist_ablation} \end{subfigure} \vspace{0.1cm} \begin{subfigure}{0.9\textwidth} \centering \includegraphics[scale=0.33]{./figures/bertbase_stackoverflow_4.pdf} \label{fig:tsne_stackoverflow_ablation} \end{subfigure} \caption{Ablation study of PairSupCon. \textbf{First Row}: Spearman correlation evaluated on the STS tasks. \textbf{Second Row}: visualization of the StackOverflow \citep{xu2017self} representations using t-SNE \citep{maaten2008visualizing}.} \label{fig:motivation_ablation} \end{figure*} \subsection{Semantic Textual Similarity} \label{subsec:sts} Next, we asses the performance of PairSupCon on seven STS tasks, namely STS 2012-2016 \citep{agirre2012semeval,agirre2013sem,agirre2014semeval,agirre2015semeval,agirre2016semeval}, STS Benchmark \citep{cer2017semeval}, and SICK-Relatedness \citep{marelli2014sick}. These datasets include pairs of sentences with a fine-grained gold semantic similarity score ranges from 0 to 5. To enable a fair comparison, we follow the setup in SBERT \citep{reimers-2019-sentence-bert}, and compute the Spearman correlation\footnote{Same as SBERT \citep{reimers-2019-sentence-bert} and SimCSE \citep{gao2021simcse}, we concatenate all the topics and report the overall Spearman’s correlation.} between cosine similarity of sentence embeddings and the ground truth similarity scores of each pair. The evaluation results are reported in Table \ref{tab:STS_compare}. PairSupCon substantially outperforms both the vanilla BERT and SBERT models. This validates our assumption that, by implicitly encoding the high-level categorical structure into the representations, PairSupCon promotes better convergence of the low-level semantic entailment reasoning objective. This assumption is consistent with the top-down categorization behavior of humans. Although SimCSE leverages STS-Benchmark as the development set while PairSupCon is fully blind to the downstream tasks\footnote{We also evaluate PairSupCon with STS-Benchmark as the development set in Appendix \ref{appendix:sts_dev}.}, we hypothesize the performance gain of SimCSE on STS is mainly contributed by explicitly merging the entailment and contradiction separation into the instance discrimination loss. On the other hand, as we discussed in Section \ref{subsec:clustering}, PairSupCon achieves more obvious performance gain on the clustering tasks through a bidirectional instance discrimination loss. Therefore, developing a better instance discrimination based sentence representation learning objective by incorporating the strengths of both SimCSE and PairSupCon could be a promising direction. \begin{table}[htbp] \begin{center} \begin{tabular}{@{\extracolsep{8pt}}ccc@{}} \textbf{Loss Func.} & \multicolumn{2}{c}{\textbf{Downstream}} \\ \cline{2-3} & \textbf{STS} & \textbf{Clustering}\\ Classification & 76.0& 52.9 \\ InstanceDisc &79.0 & \textbf{65.5} \\ \hline \hline \textbf{PairSupCon}& \\ $\beta=0.5$ & \textbf{81.0} & 61.6 \\ $\underline{\beta=1}$ & 80.8 & 63.7 \\ $\beta=2$ & 80.4 & 64.6 \\ $\beta=4$ & 80.0 & 65.0 \\ $\beta=4$ & 79.5 & 65.4 \\ \hline \end{tabular} \caption{Ablation study of PiarSupCon on BERT-base. We underline the setting used for all our experiments.} \label{tab:PairSupCon_ablation} \end{center} \end{table} \begin{table}[htbp] \begin{center} \begin{tabular}{@{\extracolsep{5pt}}lcc@{}} \textbf{Loss Func.} & \multicolumn{2}{c}{\textbf{Downstream}} \\ \cline{2-3} & \textbf{STS} & \textbf{Clustering}\\ \textbf{InstanceDisc} & \\ w/o HardNegSample & 78.4 & 64.3\\ w/ HardNegSample & \textbf{79.0} & \textbf{65.5} \\ \hline \hline \textbf{PairSupCon}& \\ w/o HardNegSample & 80.2 & 62.1\\ w/ HardNegSample & \textbf{80.8} & \textbf{63.7}\\ \hline \end{tabular} \caption{Ablation of hard negative sampling. We choose BERT-base as backbone.} \label{tab:importance} \end{center} \end{table} \subsection{Ablation Study} \label{subsec:ablation} We run extensive ablations to better understand what enables the good performance of PairSupCon. For notational convenience, we name the pairwise semantic relation classification objective in PairSupCon as \textbf{Classification}, and the instance discrimination objective as \textbf{InstanceDisc}. \begin{table*}[htbp] \begin{center} {\small{ \begin{tabular}{lccccccc} & \textbf{MR}& \textbf{CR}&\textbf{SUBJ}& \textbf{MPQA}&\textbf{SST}& \textbf{TREC}&\textbf{MRPC} \\ \cline{2-8} BERT$_{\text{distil} \cdot \text{base}}$ &61.4(4.0) &69.0(2.6) &\textbf{86.2}(1.8) &67.4(3.8) &67.3(4.2) &\textbf{59.2}(6.3) &59.8(6.9) \\ SBERT$^{\diamondsuit}_{\text{distil} \cdot \text{base}}$&\textbf{69.8}(1.9) &\textbf{83.3}(1.9) &80.4( 2.8) &81.9(1.5) &78.8(1.2) &39.8(4.2) &\textbf{60.4}(3.4) \\ SimCSE$^{\spadesuit}$&-&-&-&-&-&-&- \\ \hline \textbf{PairSupCon}$_{\text{distil} \cdot \text{base}}$ &65.6 (6.4) &80.5(1.5) &82.7 (3.3) &\textbf{83.8}(1.1) &\textbf{79.9}(1.6) &52.5(3.2) &59.7(2.0) \\ \\ BERT$_{\text{base}}$ &61.8(4.3) &68.2(3.1) &\textbf{87.4}(1.6) &63.6(5.2) &68.0(1.7) &\textbf{58.4}(2.1) &56.5(12.1)\\ SBERT$^{\diamondsuit}_{\text{base}}$ &\textbf{72.9}(1.7) &81.2(4.9) &81.9(1.1) &80.7(2.4) &78.0 (6.1) &45.8(1.9) &60.0(3.9)\\ SimCSE$^{\spadesuit}$&71.8(1.8) &\textbf{82.9}(1.5) &85.9(2.0) &79.0(4.2) &80.0(3.7) &54.5(4.0) &57.8(5.1) \\ \hline \textbf{PairSupCon}$_{\text{base}}$ &72.8(2.0) &81.8(2.6) &85.7(1.9) &\textbf{82.7}(1.2) &\textbf{80.2}(3.2) &49.3(3.9) &\textbf{61.4}(4.4) \\ \\ BERT$_{\text{large}}$ &64.4(4.4) &70.9(2.9) &\textbf{86.6}(3.0) &62.9(4.6) &73.1(3.0) &\textbf{57.2}(2.9) &\textbf{63.4}(9.2) \\ SBERT$^{\diamondsuit}_{\text{large}}$ &\textbf{78.5}(0.9) &\textbf{85.1}(6.3) &79.8(3.6) &83.3(1.6) &82.5(4.8) &43.5(4.9) &58.8(4.7) \\ SimCSE$^{\spadesuit}$&75.4(2.3) &84.5(3.0) &85.5(2.8) &84.0(1.9) &\textbf{84.9}(2.2) &52.4(3.4) &59.6(2.4) \\ \hline \textbf{PairSupCon}$_{\text{large}}$ &74.8(2.6) &84.8(4.1) &84.6(2.3) &\textbf{85.2}(1.3) &83.7(1.7) &50.4(5.7) &62.6(5.3) \\ \end{tabular}}} \caption{Few-shot learning evaluation on SentEval. For each task, we randomly sample 16 labeled instances per class and report the mean (standard deviation) performance over 5 different training sets. $\diamondsuit$ and $\spadesuit$: results evaluated on the checkpoints provided by \citet{reimers-2019-sentence-bert} and \citet{gao2021simcse}, respectively. } \label{tab:senteval_fsl_compare} \end{center} \end{table*} \paragraph{PairSupCon versus. Its Components}{In Figure \ref{fig:motivation_ablation}, we compare PairSupCon against its two components, namely Classification and InstanceDisc. As it shows, InstanceDisc itself outperforms Classification on both STS and categorical concept encoding. The result matches our expectation that contrasting each positive pair against multiple negatives, despite obtained through unsupervised sampling, yields better performance than simply learning from each individual pair. By jointly optimizing both objectives, PairSupCon leverages the implicit grouping effect of InstanceDisc to encode the high-level categorical structure into representations while, simultaneously complementing InstanceDisc with more fine-grained semantic concept reasoning capability via Classification. Table \ref{tab:PairSupCon_ablation} indicates a trade-off between the high-level semantic structure encoding and the low-level pairwise entailment and contradiction reasoning capability of PairSupCon. Focusing more on the pairwise classification objective, {\em i.e.,~} using smaller $\beta$ values, can hurt the embeddings of the high-level semantic structure. This result is not surprising, especially considering that sentences forming a contradiction pair are not necessarily belong to different semantic groups. On the other hand, InstanceDisc only focuses on separating each positive pair from all other samples within the same minibatch, and an explicit force that discriminates semantic entailment from contradiction is necessary for PairSupCon to achieve competitive performance on the more fine-grained pairwise similarity reasoning on STS. As indicated in Table \ref{tab:PairSupCon_ablation}, we can tune the $\beta$ values to attain effective representations for specific downstream tasks according to their semantic granularity focuses. We set $\beta=1$ for all our experiments with the goal to provide effective universal sentence representations to different downstream tasks. } \paragraph{Hard Negative Sampling Helps}{ In Table \ref{tab:importance}, we compare both PairSupCon and InstanceDisc against their counterparts where the negatives in the instance discrimination loss are uniformly sampled from data. As it shows, the hard negative sampling approach proposed in Section \ref{sec:hargneg_sample} leads to improved performance on both STS and clustering tasks. We associate this performance boost with our assumption that hard negatives are likely located close to the anchor. A properly designed distance-based sampling approach can drive the model to better focus on hard negative separation and hence lead to better performance. On the other hand, hard negative sampling without any supervision is a very challenging problem, especially considering that samples within the local region of an anchor are also likely from the same semantic group as the anchor. As a consequence, a solely distance-based sampling approach can induce certain false negatives and hurt the performance. To tackle this issue, leveraging proper structure assumption or domain-specific knowledge could be potential directions, which we leave as future work. } \subsection{Transfer Learning} \label{subsec:transfer_learning} In order to provide a fair and comprehensive comparison with the existing work, we also evaluate PairSupCon on the following seven transferring tasks: MR \citep{pang2005seeing}, CR \citep{hu2004mining}, SUBJ \citep{pang2004sentimental}, MPQA \citep{wiebe2005annotating}, SST \citep{socher2013recursive}, TREC \citep{li2002learning}, and MRPC \citep{dolan2004unsupervised}. We follow the widely used evaluation protocol, where a logistic regression classifier is trained on top of the frozen representations, and the testing accuracy is used as a measure of the representation quality. We adopt the default configurations of the SentEval \citep{conneau2018senteval} toolkit and report the evaluation results in Table \ref{tab:senteval_compare_full_supervision} in Appendix \ref{appendix:transfer_learning}. As we can see, the performance gap between different methods are relatively small. We suspect the reason is that the transfer learning tasks do not present enough complexities to fully uncover the performance gap between different approaches, especially considering that most tasks are binary classification with a large amount of labeled training examples. To further examine our hypothesis, we extend the evaluation to the setting of few-shot learning, where we uniformly sample 16 labeled instances per class for each task. We report the mean and standard deviation of the evaluation performance over 5 different sample sets in Table \ref{tab:senteval_fsl_compare}. Although we observe more obvious performance gap on each specific task, there is no consistent performance gap between different approaches when evaluated across different tasks. Therefore, to better evaluate the transfer learning performance of sentence representations, more complex and diverse datasets are required. \section{Discussion and Conclusion} In this paper, we present a simple framework for universal sentence representation learning. We leverage the implicit grouping effect of instance discrimination learning to better encoding the high-level semantic structure of data into representations while, simultaneously promoting better convergence of the lower-level semantic entailment and contradiction reasoning objective. We substantially advance the previous state-of-the-art results when evaluated on various downstream tasks that involve understanding semantic concepts at different granularities. We carefully study the key components of our model and pinpoint the performance gain contributed by each of them. We observe encouraging performance improvement by using the proposed hard negative sampling strategy. On the other hand, hard negative sampling without any supervision is an crucial, yet significantly challenging problem that should motivate further explorations. Possible directions include making proper structure assumption or leveraging domain-specific knowledge. The substantial performance gain attained by our model also suggests developing explicit grouping objectives could be another direction worth investigation.
{'timestamp': '2022-02-01T02:18:26', 'yymm': '2109', 'arxiv_id': '2109.05424', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05424'}
arxiv
\section{Introduction} As Deep Neural Networks (DNNs) become more widespread in all kinds of devices and situations, what is the associated energy cost? In this work we explore the evolution of different metrics of deep learning models, paying particular attention to {\em inference} computational cost and its associated energy consumption. The full impact, and its final carbon footprint, not only depends on the internalities (hardware and software directly involved in their operation) but also on the externalities (all social and economic activities around it). From the AI research community, we have more to say and do about the former. Accordingly, more effort is needed, within AI, to better account for the internalities, as we do in this paper. In our study, we differentiate between training and inference. At first look it seems that training cost is higher. However, for deployed systems, inference costs exceed training costs, because of the multiplicative factor of using the system many times \citep{martinez2018accounting}. Training, even if it involves repetitions, is done once but inference is done repeatedly. It is estimated that inference accounts for up to 90\% of the costs \citep{aws}. There are several studies about training computation and its environmental impact \citep{ai_and_compute,gholami2020ai_and_memory_wall,canziani2017analysis,7723730,anthony2020carbontracker,thompson2020computational} but there are very few focused on inference costs and their associated energy consumption DNNs are deployed almost everywhere \citep{balas2019handbook}, from smartphones to automobiles, all having their own compute, temperature and battery limitations. Precisely because of this, there has been a pressure to build DNNs that are less resource demanding, even if larger DNNs usually outperform smaller ones. Alternatively to this in-device use, many larger DNNs are run on data centres, with people accessing them repeated in a transparent way, e.g., when using social networks \citep{park2018deep}. Millions of requests imply millions of inferences over the same DNN. Many studies report that the size of neural networks is growing exponentially \citep{xu2018scaling,bianco2018benchmark}. However, this does not necessarily imply that the cost is also growing exponentially, as more weights could be implemented with the same amount of energy, mostly due to hardware specialisation but especially as the energy consumption per unit of compute is decreasing. Also, there is the question of whether the changing costs of energy and their carbon footprint \citep{europa-footprint} should be added to the equation. Finally, many studies focus on the state-of-the-art (SOTA) or the cutting-edge methods according to a given metric of performance, but many algorithmic improvements usually come in the months or few years after a new technique is introduced, in the form of {\em general use} implementations having similar results with much lower compute requirements. All these elements have been studied separately, but a more comprehensive and integrated analysis is necessary to properly evaluate whether the impact of AI on energy consumption and its carbon footprint is alarming or simply worrying, in order to calibrate the measures to be taken in the following years and estimate the effect in the future. For conducting our analysis we chose two representative domains: Computer Vision (CV) and Natural Language Processing (NLP). For CV we analysed image classification models, and ImageNet \citep{russakovsky2015ImageNet} more specifically, because there is a great quantity of historical data in this area and many advances in this domain are normally brought to other computer vision tasks, such as object detection, semantic segmentation, action recognition, or video classification, among others. For NLP we analysed results for the General Language Understanding Evaluation (GLUE) benchmark \citep{wang2019glue}, since language understanding is a core task in NLP. We focus our analysis on inference FLOPs (Floating Point Operations) required to process one input item (image or text fragment). We collect inference FLOPs for many different DNNs architectures following a comprehensive literature review. Since hardware manufacturers have been working on specific chips for DNN, adapting the hardware to a specific case of use leads to performance and efficiency improvements. We collect hardware data over the recent years, and estimate how many FLOPs can be obtained with one Joule with each chip. Having all this data we finally estimate how much energy is needed to perform one inference step with a given DNN. Our main objective is to study the evolution of the required energy for one prediction over the years. The main findings and contributions of this paper are to (1) showcase that better results for DNN models are in part attributable to algorithmic improvements and not only to more computing power; (2) determine how much hardware improvements and specialisation is decreasing DNNs energy consumption; (3) report that, while energy consumption is still increasing exponentially for new cutting-edge models, DNN inference energy consumption could be maintained low for increasing performance if the efficient models that come relatively soon after the breakthrough are selected. We provide all collected data and performed estimations as a data set, publicly available in the appendixes and as a GitHub repository\footnote{Temporary copy in: \url{https://bit.ly/3DTHvFC} . The rest of the paper covers the background, introduces the methodology and presents the analysis of hardware and energy consumption of DNN models and expounds on some forecasts. Discussion and future work close the paper. \section{Background}\label{section:background} In line with other areas of computer science, there is some previous work that analyses compute and its cost for AI, and DNNs more specifically. Recently, OpenAI carried out a detailed analysis about AI efficiency \citep{hernandez2020measuring}, focusing on the amount of compute used to train models with the ImageNet dataset. They show that 44 times less compute was required in 2020 to train a network with the performance AlexNet achieved seven years before. However, a demand for better task performance, linked with more complex DNNs and larger volumes of data to be processed, the growth in demand for AI compute is still growing fast. \citep{thompson2020computational} reports the computational demands of several Deep Learning applications, showing that progress in them is strongly reliant on increases in computing power. AI models have doubled the computational power used every 3.4 months since 2012 \citep{ai_and_compute}. The study \citep{gholami2020ai_and_memory_wall} declare similar scaling rates for AI training compute to \citep{ai_and_compute} and they forecast that DNNs memory requirements will soon become a problem. This exponential trend seems to impose a limit on how far we can improve performance in the future without a paradigm change. Compared to training costs, there are fewer studies on inference costs, despite using a far more representative share of compute and energy. \citeauthor{canziani2017analysis} (\citeyear{canziani2017analysis}) study accuracy, memory footprint, parameters, operations count, inference time and power consumption of 14 ImageNet models. To measure the power consumption they execute the DNNs on a NVIDIA Jetson TX1 board. A similar study \citep{7723730} measures energy efficiency, Joules per image, for a single forward and backward propagation iteration (a training step). This study benchmarks 4 Convolutional Neural Networks (CNNs) on CPUs and GPUs on different frameworks. Their work shows that GPUs are more efficient than CPUs for the CNNs analysed. Both publications analyse model efficiency, but they do this for very concrete cases. We analyse a greater number of DNNs and hardware components in a longer time frame These and other papers are key in helping society and AI researchers realise the issues about efficiency and energy consumption. \citeauthor{strubell2019energy} (\citeyear{strubell2019energy}) estimate the energy consumption, the cost and CO\textsubscript{2} emissions of training various of the most popular NLP models. \citeauthor{henderson2020towards} (\citeyear{henderson2020towards}) performs a systematic reporting of the energy and carbon footprints of reinforcement learning algorithms. \citeauthor{bommasani2021opportunities} (\citeyear{bommasani2021opportunities}) (section 5.3) seek to identify assumptions that shape the calculus of environmental impact for foundation models. \citeauthor{schwartz2019green} (\citeyear{schwartz2019green}) analyse training costs and propose that researchers should put more attention on efficiency and they should report always the number of FLOPs. % These studies contribute to a better assessment of the problem and more incentives for their solution. For instance, new algorithms and architectures such as EfficientNet \citep{tan2020efficientnet} and EfficientNetV2 \citep{tan2021efficientnetv2} have aimed at this reduction in compute. When dealing about computing effort and computing speed (hardware performance), terminology is usually confusing. For instance, the term `compute' is used ambiguously, sometimes applied to the number of operations or the number of operations per second. However, it is important to clarify what kind of operations and the acronyms for them. In this regard, we will use the acronym FLOPS to measure hardware performance, by referring to the number of floating point operations {\em per second}, as standardised in the industry, while FLOPs will be applied to the amount of computation for a given task (e.g., a prediction or inference pass), by referring to the number of operations, counting a multiply-add operation pair as two operations. An extended discussion about this can be found in the appendix. \section{Methodology}\label{section:methodology} We collect most of our information directly from research papers that report results, compute and other data for one or more newly introduced techniques for the benchmarks and metrics we cover in this work. We manually read and inspected the original paper and frequently explored the official GitHub repository, if exists. However, often there is missing information in these sources, so we need to get the data from other sources, namely: \begin{itemize} \item \emph{Related papers}: usually the authors of another paper that introduces a new model compare it with previously existing models, providing further information \item \emph{Model implementations}: {\small \ttfamily{PyTorch}} \citep{pytroch} contains many (pre-trained) models, and their performance is reported. Other projects do the same (see, e.g., \citep{pretrainedmodels,cvpytroch}). \item \emph{Existing data compilations}: there are some projects and public databases collecting information about deep learning architectures and their benchmarks, e.g., \citep{git_convnet,coleman2017dawnbench,mattson2020mlperf,git_nlp,pwc}. \item \emph{Measuring tools}: when no other source was available or reliable, we used the {\small \ttfamily ptflops} library \citep{ptflops} or similar tools to calculate the model's FLOPs and parameters (when the implementation is available). \end{itemize} \noindent Given this general methodology, we now discuss in more detail how we made the selection of CV and NLP models, and the information about hardware. \subsection{CV Models Data Compilation} There is a huge number of models for image classification, so we selected models based on two criteria: popularity and accuracy. For popularity we looked at the times that the paper presenting the model is cited on Google Scholar and whether the model appears mentioned in other papers (e.g., for comparative analyses). We focused on model's accuracy as well because having the best models per year in terms of accuracy is necessary for analysing progress. To achieve this we used existing compilations \citep{pwc} and filtered by year and accuracy. For our selection, accuracy was more important than popularity for recent models, as they are less cited than the older ones because they have been published for a shorter time. Once we selected the sources for image classification models, we collected the following information: Top-1 accuracy on ImageNet, number of parameters, FLOPs per forward pass, release date and training dataset. Further details about model selection, FLOPs estimation, image cropping \citep{krizhevsky2012ImageNet} and resolution \citep{simonyan2015deep,zhai2021scaling} can be found in the Appendix (and Table \ref{tab:modelDetails}). \subsection{NLP Models Data Compilation} For NLP models we noted that there is much less information about inference (e.g., FLOPs) and the number of models for which we can get the required information is smaller than for CV. We chose GLUE for being sufficiently representative and its value determined for a good number of architectures. To keep the numbers high we just included all the models since 2017 for which we found inference compute estimation \citep{clark2020electra}. Further details about FLOPs estimation and counting can be found in the Appendix (selected models in in Table \ref{tab:nlp_data}). \subsection{Hardware Data Compilation} Regarding hardware evolution, we collected data for Nvidia GPUs\footnote{\url{https://developer.nvidia.com/deep-learning}}. We chose Nvidia GPUs because they represent one of the most efficient hardware platforms for DNN\footnote{We considered Google's TPUs (\url{https://cloud.google.com/tpu?hl=en}) for the analysis but there is not enough public information about them, as they are not sold but only available as a service.} and they have been used for Deep Learning in the last 10 years, so we have a good temporal window for exploration. In particular, we collected GPU data for Nvidia GPUs from 2010 to 2021. The collected data is: FLOPS, memory size, power consumption (reported as Thermal Design Power, TDP) and launch date. As explained before, FLOPS is a measure of computer performance. From the FLOPS and power consumption we calculate the efficiency, dividing FLOPS by Watts. We use TDP and the reported peak FLOPS to calculate efficiency. This means we are considering the efficiency (GLOPS/Watt) when the GPU is at full utilisation. In practice the efficiency may vary depending on the workload, but we consider this estimate (``peak FLOPS''/TDP) accurate enough for analysing the trends and for giving an approximation of energy consumption. In our compilation there are desktop GPUs and server GPUs. We pay special attention to server GPUs released in the last years, because they are more common for AI, and DNNs in particular. A discussion about discrepancies between theoretical and real FLOPS as well as issues regarding Floating Point (FP) precision operations can be found in the Appendix. \section{Computer Vision Analysis}\label{section:CV} In this section, we analyse the evolution of ImageNet \citep{deng2009ImageNet} (one pass inference) according to performance and compute. Further details in the Appendix. \subsection{Number of Parameters and FLOPs}\label{section:params} The number of parameters is usually reported, but it is not directly proportional to compute. For instance, in CNNs, convolution operations dominate the computation: if $d$, $w$ and $r$ represent the network's depth, widith and input resolution, the FLOPs grow following the relation \citep{tan2020efficientnet}: $$\mbox{FLOPs} \propto d + w^2 + r^2$$ \noindent This means that FLOPs do not directly depend on the number of parameters. Parameters affect network depth ($d$) or width ($w$), but distributing the same number of parameters in different ways will result in different numbers of FLOPs. Moreover, the resolution ($r$) does not depend on the number of parameters directly, because the input resolution can be increased without increasing network size. \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig1_ParamsVSGFLOPS.pdf} \caption{\label{fig:params}Relation between the number of parameters and FLOPs (both axes are logarithmic). \end{figure} Despite this, Fig.~\ref{fig:params} shows a linear relation between FLOPs and parameters. We attribute this to the balanced scaling of $w$, $d$ and $r$. These dimensions are usually scaled together with bigger CNNs using higher resolution. Note that recent transformer models \citep{vaswani2017attention} do not follow the growth relation presented above. However, the correlation between the number of parameters and FLOPs for CNNs is 0.772 and the correlation for transformers is 0.994 (Fig.~\ref{fig:params}). This suggests that usually in both architectures parameters and FLOPs scale in tandem. We will use FLOPs, as they allow us to estimate the needed energy relating hardware FLOPS with required FLOPs for a model \citep{how_fast,clark2020electra}. \subsection{Performance and Compute} There has been very significant progress for ImageNet. In 2012, AlexNet achieved 56\% Top-1 accuracy (single model, one crop). In 2021, Meta Pseudo Labels (EfficientNet-L2) achieved 90.2\% Top-1 accuracy (single model, one crop). However, this increase in accuracy comes with an increase in the required FLOPs for a forward pass. A forward pass for AlexNet is 1.42 GFLOPs while for EfficientNet-L2 is 1040 GFLOPs (details in the appendix). \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig2_AccVSDate.pdf} \caption{\label{fig:acc_years}Accuracy evolution over the years. The size of the balls represent the GFLOPs of one forward pass. } \end{figure} Fig.~\ref{fig:acc_years} shows the evolution from 2012 to 2021 in ImageNet accuracy (with the size of the bubbles representing the FLOPs of one forward pass). In recent papers some researchers began using more data than those available in ImageNet1k for training the models. However, using extra data only affects training FLOPs, but does not affect the computational cost for {\em inferring} each classification (forward pass). \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig3_GFLOPSevol.pdf} \caption{\label{fig:date_flops}GFLOPs over the years. The dashed line is a linear fit (note the logarithmic $y$-axis\xspace) for the models with highest accuracy per year. The solid line includes all points.} \end{figure} If we only look at models with the best accuracy for each year we can see an exponential growth in compute (measured in FLOPs). This can be observed clearly in Fig.~\ref{fig:date_flops}: the dashed line represents an exponential growth (shown as a linear fit since the $y$-axis\xspace is logarithmic). The line is fitted with the models with highest accuracy for each year. However not all models released in the latest years need so much compute. This is reflected by the solid line, which includes all points. We also see that for the same number of FLOPs we have models with increasing accuracy as time goes by. In Table \ref{table:tableAlexNet} there is a list of models having similar number of FLOPs as AlexNet. In 2019 we have a model (EfficientNet-B1) with the same number of operations as AlexNet achieving a Top-1 accuracy of 79.1\% without using extra data, and a model (NoisyStudent-B1) achieving Top-1 accuracy of 81.5\% using extra data. In a period of 7 years, we have models with similar computation with much higher accuracy. We observe that when a SOTA model is released it usually has a huge number of FLOPs, and therefore consumes a large amount of energy, but in a couple of years there is a model with similar accuracy but with much lower number of FLOPs. These models are usually those that become popular in many industry applications. This observation confirms that better results for DNN models of {\em general use} are in part attributable to algorithmic improvements and not only to the use of more computing power. \begin{table}[!h] \centering \resizebox{0.7\columnwidth}{!}{% \begin{tabular}{@{}lccc@{}} \toprule \textbf{Model} & \textbf{Top-1 Accuracy} & \textbf{GFLOPs} & \textbf{Year} \\ \midrule \textbf{AlexNet} \citep{krizhevsky2012ImageNet} & 56.52 & 1.42 & 2012 \\ \textbf{ZFNet} \citep{zeiler2013visualizing} & 60.21 & 2.34 & 2013 \\ \textbf{GoogleLeNet} \citep{szegedy2014going} & 69.77 & 3.00 & 2014 \\ \textbf{MobileNet} \citep{howard2017mobilenets} & 70.6 & 1.14 & 2017 \\ \textbf{MobileNetV2 1.4} \citep{sandler2019mobilenetv2} & 74.7 & 1.18 & 2018 \\ \textbf{EfficientNet-B1} \citep{tan2020efficientnet}& 79.1 & 1.40 & 2019 \\ \textbf{NoisyStudent-B1} \citep{xie2020selftraining} & 81.5 & 1.40 & 2019 \\ \bottomrule \end{tabular}% } \vspace{0.3cm} \caption{Results for several DNNs with a similar number of FLOPs as AlexNet. \label{table:tableAlexNet}} \end{table} Finally, Fig.~\ref{fig:acc_flops} shows that the Pareto frontier (in grey) is composed of new models (in yellow and green), whereas old models (in purple and dark blue) are relegated below the Pareto. As expected, the models which use extra data are normally those forming the Pareto frontier. Let us note again that extra training data does not affect inference GFLOPs. \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig4_AccVSGFLOPS.pdf} \caption{\label{fig:acc_flops}Relation between accuracy and GFLOPs.} \end{figure} \section{Natural Language Analysis}\label{section:NLP} In this section, we analyse the trends in performance and inference compute for NLP models. To analyse performance we use GLUE, which is a popular benchmark for natural language understanding, one key task in NLP. The GLUE benchmark\footnote{Many recent models are evaluated on SUPERGLUE, but we choose GLUE to have a temporal window for our analysis.} is composed of nine sentence understanding tasks, which cover a broad range of domains. The description of each task can be found in \citep{wang2019glue}. \subsection{Performance and Compute} We represent the improvement on the GLUE score in relation to GFLOPs over the years in Fig.~\ref{fig:flops_glue} (and in Fig.~\ref{fig:date_glue} in the Appendix). GFLOPs are for single input of length 128, which is a reasonable sequence length for many use cases, being able to fit text messages or short emails. We can observe a very similar evolution to the evolution observed in ImageNet: SOTA models require a large number of FLOPs, but in a short period of time other models appear, which require much fewer FLOPs to reach the same score. There are many models that focus on being efficient instead of reaching high score, and this is reflected in their names too (e.g., MobileBERT \citep{sun2020mobilebert} and SqueezeBERT \citep{iandola2020squeezebert}). We note that the old models become inefficient (they have lower score with higher number of GLOPs) compared to the new ones, as it happens in CV models. \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig6_GFLOPSVSGLUE.pdf} \caption{\label{fig:flops_glue}GFLOPs per token analysis for NLP models.} \end{figure} \subsection{Compute Trend} In Fig.~\ref{fig:date_flops_nlp} we include all models (regardless of having performance results) for which we found inference FLOPs estimation. The dashed line adjusts to the models with higher GFLOPs (models that, when released, become the most demanding model) and the solid line to all NLP models. In this plot we indicate the input sequence length, because in this plot we represent models with different input sequence lengths. We observe a similar trend as in CV: the GFLOPS of the most cutting-edge models have a clear exponential growth, while the general trend, i.e., considering all models, does not scale so aggressively. Actually, there is a good pocket of low-compute models in the last year. \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig7_GFLOPSNLP.pdf} \caption{\label{fig:date_flops_nlp}GFLOPs per token analysis for NLP models.} \end{figure} \section{Hardware Progress}\label{section:hardware} We use FLOPS as a measure of hardware performance and FLOPS/Watt as a measure of hardware efficiency. We collected performance for different precision formats and tensor cores for a wide range of GPUs. The results are shown in Fig.~\ref{fig:gpus}. Note that the $y$-axis\xspace is in logarithmic scale. Theoretical FLOPS for tensor cores are very high in the plot. However, the actual performance for inference using tensor cores is not so high, if we follow a more realistic estimation for the Nvidia GPUs (V100, A100 and T4\footnote{Specifications in: \url{https://www.nvidia.com/en-us/data-center/}.}). The details of this estimation are shown in Table \ref{tab:gpu_speed_up_models} in the appendix. \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig8_GPUsvsGFLOPS.pdf} \caption{\label{fig:gpus}Theoretical Nvidia GPUs GFLOPS per Watt. Data in Table \ref{tab:gpu_theorical} in the appendix.} \end{figure} With these estimations we obtained good linear fits (with the $y$-axis\xspace in logarithmic scale) to each data set, one for CV and another for NLP, as shown by the solid lines in Fig.~\ref{fig:gpus_adapted}. Notice that there is a particular point in Fig.~\ref{fig:gpus_adapted} for year 2018 that stands out among the others by a large margin. This corresponds to T4 using mixed precision, a GPU specifically designed for inference, and this is the reason why it is so efficient for this task. \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig9_GFLOPSvsWatts.pdf} \caption{\label{fig:gpus_adapted}Nvidia GPU GFLOPS per Watt adapted for CV (CNNs) and NLP models. Data in Table \ref{tab:gpu_models} in the appendix.} \end{figure} \section{Energy Consumption Analysis} Once we have estimated the inference FLOPs for a range of models and the GFLOPS per Watt for different GPUs, we can estimate the energy (in Joules) consumed in one inference. We do this by dividing the FLOPs for the model by FLOPS per Watt for the GPU. But how can we choose the FLOPS per Watt that correspond to the model? We use the models presented in Fig.~\ref{fig:gpus_adapted} to obtain an estimation of GLOPS per Watt {\em for the model's release date}. In this regard, \citeauthor{henderson2020towards} (\citeyear{henderson2020towards}) report that FLOPs for DNNs can be misleading sometimes, due to underlying optimisations at the firmware, frameworks, memory and hardware that can influence energy efficiency. They show that energy and FLOPs are highly correlated for the same architecture, but the correlation decreases when different architectures are mixed. We consider that this low correlation does not affect our estimations significantly as we analyse the trends through the years and we fit in the exponential scale, where dispersion is reduced. To perform a more precise analysis it would be necessary to measure power consumption for each network with the original hardware and software, as unfortunately the required energy per (one) inference is rarely reported. \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig10_EstimatedJoules.pdf} \caption{\label{fig:watts_estimation}Estimated Joules of a forward pass (CV). The dashed line is a linear fit (logarithmic $y$-axis\xspace) for the models with highest accuracy per year. The solid line fits all models.} \end{figure} \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig11_JoulesNLP.pdf} \vspace{-0.2cm} \caption{\label{fig:watts_estimation_nlp}Estimated Joules of a forward pass (NLP). Same interpretation as in Fig.~\ref{fig:watts_estimation} } \end{figure} We can express the efficiency metric FLOPS per Watt as FLOPs per Joule, as shown in Eq. \ref{eq:FLOPS/Watt}. Having this equivalence we can use it to divide the FLOPs needed for a forward pass and obtain the required Joules, see Eq. \ref{eq:joules}. Doing this operation we obtain the consumed energy in Joules. \begin{equation} \label{eq:FLOPS/Watt} \mbox{ \mbox{Efficiency} $= \frac{\mbox{HW Perf.}}{\mbox{Power}} \:\: \mbox{in units:} \:\: \cfrac{FLOPS}{Watt} = \cfrac{FLOPs/s}{Joules/s} = \cfrac{FLOPs}{Joule}$} \end{equation} \vspace{-0.1cm} \begin{equation} \label{eq:joules} \mbox{ \mbox{Energy} $= \frac{\mbox{Fwd. Pass}}{\mbox{Efficiency}} \:\: \mbox{in units:} \:\: \cfrac{FLOPs}{FLOPs/Joule} = Joule $} \end{equation} Applying this calculation to all collected models we obtain Fig.~\ref{fig:watts_estimation} for CV. The dashed line represents an exponential trend (a linear fit as the $y$-axis\xspace is logarithmic), adjusted to the models with highest accuracy for each year, like in Fig.~\ref{fig:acc_years}, and the dotted line represent the average Joules for each year. By comparing both plots we can see that hardware progress softens the growth observed for FLOPs, but the growth is still clearly exponential for the models with high accuracy. The solid line is almost horizontal, but in a logarithmic scale this may be interpreted as having an exponential growth with a small base or a linear fit on the semi log plot that is affected by the extreme points. In Fig.~\ref{fig:watts_estimation_nlp} we do the same for NLP models and we see a similar picture. Fig.~\ref{fig:joules_acc} shows the relation between Top-1 Accuracy and Joules. Joules are calculated in the same way as in Fig.~\ref{fig:watts_estimation}. The relation is similar as the observed in Fig.~\ref{fig:acc_flops}, but in Fig.~\ref{fig:joules_acc} the older models are not only positioned further down in the $y$-axis\xspace (performance) but they tend to cluster on the bottom right part of the plot (high Joules), so their position on the $y$-axis\xspace is worse than for Fig.~\ref{fig:acc_flops} due to the evolution in hardware. This is even more clear for NLP, as seen in Fig.~\ref{fig:joules_acc_nlp}. \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig12_JoulesVSACC.pdf} \caption{\label{fig:joules_acc}Relation between Joules and Top-1 Accuracy over the years (CV, ImageNet).} \end{figure} \begin{figure}[!h] \centering \includegraphics[width=0.9\columnwidth]{Fig13_JoulesVSGLUE.pdf} \caption{\label{fig:joules_acc_nlp}Relation between Joules and GLUE score over the years (NLP, GLUE) } \end{figure} \section{Forecasting and Multiplicative Effect}\label{section:forecast} In our analysis we see that DNNs as well as hardware are improving their efficiency and do not show symptoms of standstill. This is consistent with most studies in the literature: performance will continue growing as compute grows, but at the same time efficiency is increasing. However, this is the first work that analyses whether these two things cancel, especially when we analyse inference and not training. Our conclusion is that they not cancel out for the cutting-edge models of each moment but this is less clear for the regular models in {\em general use} by industries and invididuals. However, since we are focusing on inference costs, we need to consider the multiplicative factor. How many inferences are performed {\em per capita}? This has definitely increased very significantly with the use of smart devices, Internet of things and many other devices around us, which are incorporating DNN-based services. However, how many inference passes per capita do we have at this moment, and how is this growing? This is very difficult to estimate, and we leave it for future work. However, it is interesting to a\-na\-ly\-se possible hypotheses: assume there is one inference pass of a neural network application per second per capita. What would this imply in terms of energy consumption? \begin{figure}[!t] \centering \includegraphics[width=0.9\columnwidth]{Fig14_JoulesVSHuman.pdf} \caption{\label{fig:joules_year_human}Estimated Joules per forward pass (e.g., one prediction) compared to human energy consumption in 1s (CV).} \end{figure} \begin{figure}[!t] \vspace{-0.3cm} \centering \includegraphics[width=0.9\columnwidth]{Fig15_JoulesVSHuman.pdf} \caption{\label{fig:joules_year_human_nlp}Estimated Joules per forward pass (e.g., one prediction) compared to human consumption in 1s (NLP).} \end{figure} In order to put this inference energy consumption in context we calculate the value of average human body energy consumption (we will refer to it as somatic or internal consumption) in one second and the average energy that a human being consumes in one second with all their commodities (we will refer to it as external consumption). The internal consumption is calculated assuming 2000 KCal per person day, and converting this to Joules/s, giving approximately 100 Joules/s. The external consumption is the sum of total energy consumption, including electricity, transport and heating, using the USA as a reference \citep{owidenergy}. This suggests 79,897 Kwh/year in 2019, which is approximately 10,000 Joules every second. The comparison of these two references with the trends can be seen in Fig.~\ref{fig:joules_year_human} (CV). As we see, the energy consumed for one inference of the best models approaches the energy consumed by the human body in one second but stills far from the external energy consumed in one second. If each human did an AI-based decision implying a forward pass every second during the whole day (and night), this would be still well below their internal consumption. However, AI-based decisions are becoming more ubiquitous. For instance, a self-driving car or a surveillance camera may be making many forward passes per second. For NLP, the trends are similar but the best models are growing much faster, as we see in Fig.~\ref{fig:joules_year_human_nlp}, while the regular models may even decrease. Here, the interpretation in terms of how many decisions are made in a second is also hard to determine. For instance, a language model interfaced by a human does not require more than the basic 128-token windows per second. However, many applications of language models can process data without interacting with humans at a much higher speed. \section{Discussion and Future Work}\label{section:discussion} In this work we have combined the analysis of several elements about AI, compute and energy consumption that allow us to have a different and more comprehensive perspective about the energy impact of AI. The most distinctive element of our analysis is that we focus on inference cost, which is usually lower than the training cost when both are reported in research papers, but because of multiplicative factors, it is much higher overall. Many DNN models are trained once and applied millions of times (forward passes). Our findings are very different from the unbridled exponential growth that is usually reported when just looking at the number of parameters of new deep learning models \citep{hestness2017deep,kaplan2020scaling,henighan2020scaling}. When we focus on inference costs of these networks, the energy that is associated is not growing so fast, because of several factors that partially compensate the growth, such as algorithmic improvements, hardware specialisation and hardware consumption efficiency. The gap gets closer when we analyse those models that settle, i.e., those models whose implementation become very popular one or two years after the breakthrough algorithm was introduced. These {\em general-use} models can achieve systematic growth in performance at an almost constant energy consumption. The main conclusion is that even if the {\em energy} used by AI were kept constant, the improvement in performance could be sustained with algorithmic improvements and fast increase in the number of parameters. This conclusion has an important limitation. It assumes a constant multiplicative factor. As more and more devices use AI (locally or remotely) the energy consumption can escalate just by means of increased penetration, in the same way that cars have become more efficient in the past two decades but there are many more cars in the world today. We hope this paper contributes to the increasing debate about AI and energy consumption by analysing the inference costs. As these are dominated by multiplicative factors, this should encourage not only AI researchers but economists and social scientists to participate in this analysis. Future studies would be enriched by socio-economic indicators about the use of AI (the degree of penetration), the cost of energy and devices as well as the carbon footprint per Joule \citep{europa-footprint}. Similarly, comparing energy consumption by AI and trends in human salaries could help determine where automation \citep{tolan2021measuring} becomes cost effective in economic terms. Finally, this paper has many limitations that originate from the limited information reported in scientific papers. Many papers include the number of hyperparameters, but it is less common to have complete information about FLOPs and energy consumption. It is even rarer when looking for inference costs. This information is not only necessary for the transparency of the field but it is of utmost relevance for producing studies such as the one we have presented here, with a larger number of benchmarks and models. Also, it is important that new techniques are reported with new but also old benchmarks, so that we can have larger temporal windows where we can analyse the evolution of the field. We hope that future studies can build on this one and better publishing practices. \bibliographystyle{abbrvnat}
{'timestamp': '2021-09-14T02:20:53', 'yymm': '2109', 'arxiv_id': '2109.05472', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05472'}
arxiv
\subsection{Data Collection and Filtering} \label{data-collect} We collected \texttt{FiSCU}\xspace from various online study guides such as \texttt{shmoop},\footnote{\url{https://www.shmoop.com/study-guides/literature}} \texttt{SparkNotes},\footnote{\url{https://www.sparknotes.com/lit/}} \texttt{CliffsNotes},\footnote{\url{https://www.cliffsnotes.com/literature}} and \texttt{LitCharts}.\footnote{\url{https://www.litcharts.com}} These sources contain educational material to help students study for their literature classes. These study guides include summaries of various literary pieces as well as descriptions of characters that appear in them. These literature summaries and character descriptions were written by literary experts, typically teachers, and are of high pedagogical quality. We used \texttt{Scrapy},\footnote{\url{https://scrapy.org/}} a free and open-source web-crawling framework to crawl these study guides. Our initial crawl resulted in a set of $1,774$ literature summaries and $25,525$ character descriptions. These included all characters mentioned in the literary pieces. However, not all characters, especially those that played a minor role in the literary piece, appeared in the corresponding literature summaries. Since our task involves making inferences about characters from the literature summarie , we filtered out the characters which do not appear in the summaries or their names or the descriptions had very little overlap with the literature summaries. This is done to mitigate the reference divergence issue~\cite{kryscinski-etal-2019-neural, maynez-etal-2020-faithfulness} and ensure that the literature summary has enough information about the character to generate the description. For this, we define the ``information overlap'' between two pieces of text $\mathcal{A}$ and $\mathcal{B}$, $IO(\mathcal{B}||\mathcal{A})$, as the ratio of the length of the longest overlapping word sub-sequence between $\mathcal{A}$ and $\mathcal{B}$, over the length of $\mathcal{A}$.\footnote{Technically this is the same as Rouge-L precision} Note that this information overlap measure is not symmetric and intuitively measures how much information about $\mathcal{A}$ is present in $\mathcal{B}$. We used the information overlap measure to filter our dataset as follows. If the information overlap of the literature summary with the character name, $IO($literature summary $||$ character name$)$, is less than $0.6$, then we consider that the character is not prominently mentioned in the literature summary and we remove that character from our dataset. Similarly, if the information overlap between the character description and the literature summary, $IO($literature summary $||$ character description$)$, is less than $0.2$, then we consider the character description generation less feasible and we remove that data point from our dataset.\footnote{These thresholds were chosen by experimenting with different values and manually analyzing the quality of (a subset of) the data.} \begin{table}[t] \footnotesize \centering \input{figures/data_stat} \caption{Statistics of the \texttt{FiSCU}\xspace dataset.} \label{tab:stat} \end{table} However, during these filtering steps, we did not want to remove the most important characters of the narrative. The online study guides list characters in decreasing order of their importance in the literary piece. For example, narrators, protagonists, antagonists, etc., are always described first. Leveraging this ordering, we always retained the top $3$ characters of the literary piece in our dataset. After the filtering process, our final dataset consists of $1,708$ literature summaries and $9,499$ character descriptions in total. This set was split into train ($80\%$), test ($10\%$), and validation ($10\%$) sets. The data splits were created to avoid any data-leakages -- each literary piece and all of its character descriptions were consistently part of only one of the train, test and validation sets. Table~\ref{tab:stat} shows the statistics of the final dataset. The dataset also contains the full-text of the books for $2,052$ of the character descriptions. \subsection{Dataset Reproducibility} \label{data_reproducibility} \texttt{FiSCU}\xspace is drawn from various study guides on the web. While we do not have the rights to directly redistribute this dataset, to allow other researchers to replicate the \texttt{FiSCU}\xspace dataset and compare to our work, we provide a simple script that will allow others to recreate \texttt{FiSCU}\xspace from a particular time-stamped version of these study guides on \textit{Wayback Machine}, a time-stamped digital archive of the web. Our script ensures that others will be able to recreate the same train, test and validation splits. \section{\texttt{FiSCU}\xspace Task Definitions} \label{sec:task-def} We introduce two new tasks on the \texttt{FiSCU}\xspace dataset \begin{itemize}[noitemsep,nolistsep] \item \textit{Character Identification} \item \textit{Character Description Generation} \end{itemize} \subsection{Character Identification} The \textit{Character Identification} task requires models to identify the character in an anonymized character description. Given a summary $S$, a candidate list of characters that appear in the literature summary $C=\{c_1, c_2, ..., c_k\}$, and an anonymized character description $D_{masked}^{c*}$, the goal in this task is to identify the name of the character $c^*$ described in the anonymized character description. We anonymize character descriptions by masking out all mentions of the character $c^*$ in the original description $D^{c*}$. \subsection{Character Description Generation} The \textit{character description generation} task tests the ability of NLP models to critically analyze the narrative from the perspective of characters and generate coherent and insightful character descriptions. Formally, given a literature summary, $S$, and a character name, $c$, the goal in this task is to generate the character's description, $D^{c}$. Generating the character description necessitates understanding and analyzing every salient information about the character in the literature summary. \subsection{Human Assessment of \texttt{FiSCU}\xspace} \label{data-validation} In order to verify the tractability of these two tasks as well as assessing the quality of the collected \texttt{FiSCU}\xspace dataset, we conducted a set of human evaluations on Amazon Mechanical Turk. We run our human assessment on the full test set of \texttt{FiSCU}\xspace. \vspace{0.2cm} \noindent{\bf Assessing the Character Identification task:} In the first human assessment, we showed annotators the literature summaries, anonymized character descriptions , and a list of character names (plus one randomly sampled character from the literary piece). The descriptions were anonymized by replacing all mentions of the corresponding character names with blanks.\footnote{\label{anonymizing_footnote}We identified mentions of a character in the summary by using a coreference system \cite{joshi2019coref,spanbert} as well as by matching the first name or the full name of the character.} For each anonymized character description, we asked 3 judges to identify which character it is describing by choosing from the list of choices. The judges also had the option of saying that they are unable to identify the character given the literature summary and the anonymized character description. \begin{figure}[t] \centering \includegraphics[width=1\columnwidth]{figures/human_assess.pdf} \caption{Human assessment of the feasibility of the character description generation task. } \label{fig:human-data-assess} \end{figure} \vspace{0.2cm} \noindent{\bf Assessing the Character Description Generation task:} In the second human assessment, the judges are shown the same summary along with the original de-anonymized character descriptions. For each character description, 3 judges were asked to evaluate the quality of the description by answering the following two questions: \begin{enumerate}[wide, noitemsep, nolistsep, labelwidth=!, labelindent=0pt \item {\bf Fact coverage:} Specify how much of the information about the specific character in the corresponding ``character description'' is present in the summary (either explicitly or implicitly). Answer choices included: a) \textit{almost all of the information}, b) \textit{most of the information}, c) \textit{some of the information}, d) \textit{little or none of the information}, and e) \textit{character does not appear in the summary at all}. \item {\bf Task difficulty:} Given the summary, how easy is it to write the character description on a Likert scale of 0-4 (0 being too difficult, 4 being too easy)? If in the previous question the judges found that some of the information in the character description was not present in the summary, they are asked to disregard that while answering this question. In other words, they only need to consider the information in the character description which is explicitly or implicitly mentioned in the summary. \end{enumerate} \begin{figure}[t!] \centering \includegraphics[width=0.95\columnwidth]{figures/identification_task.pdf} \caption{Approaches for \textit{Character Identification}.} \label{fig:identification} \end{figure} We recruited $200$ crowd-workers who were located in the US, UK, or CA, and had a $98\%$ approval rate for at least $5,000$ previous annotations. We collected each annotation from $3$ workers and use majority vote in our assessments. In the Appendix~\ref{appendix-annotations}, we describe several steps we took to alleviate limitations of using crowd-sourcing and ensure high quality annotations. Screenshots of our AMT experiments are provided in the Appendix. For the first assessment on identifying characters, the human accuracy was $91.80\%$ (Fleiss' Kappa \cite{landis1977measurement} $\kappa = 0.79 $), indicating the feasibility of the task. For the second assessment of fact coverage and task difficulty, we summarize the result in Fig.~\ref{fig:human-data-assess}. The top chart (`Fact Coverage') shows that around 75\% of the of the literature summaries contain reasonable amount of information about the character represented in the corresponding character description. The bottom chart (`Task Difficulty') shows that more than 90\% of the times, the human judges considered the task of writing the character descriptions from the literature summaries not too difficult.\footnote{There is a natural label bias in the annotations: most of the responses fell into few categories. In this case, standard inter-annotator agreement statistics are not reliable (the well-known paradoxes of kappa \cite{feinstein1990high}). Thus, we simply report a pairwise agreement (i.e., how often do two judges agree on the answer for the same question) of 0.71 and 0.64 for `fact coverage' and `task difficulty', respectively.} These results verify the feasibility of understanding and drawing reasonable inferences about characters in the literature summaries from the \texttt{FiSCU}\xspace dataset. Next, we describe models and establish baseline performances on the two proposed tasks. \section{Character Identification} We present two approaches to address this task: (1) solving it as a multiple-choice classification problem, and (2) using a generative classifier that generates, instead of identifying, the character name, as shown in Fig.~\ref{fig:identification}. In the multiple-choice approach, we use the standard setup introduced in BERT~\cite{devlin-etal-2019-bert} where the text from $c_i$, $D_{masked}^{c*}$ and $S$ (with custom prefix tokens) are concatenated as input, and the \texttt{[CLS]} token is projected to a final logit. We apply a Softmax function to the logits to obtain the scores for each $c_i$. For training practicalities, we limit the number of choices to 4 during training (using the earliest window of choices which include the correct one). During inference, we can generate the logits for all the answer choices since they are independent before the final Softmax. To establish a baseline performance, we experiment with finetuning RoBERTa~\cite{liu2019roberta}, and ALBERT~\cite{Lan2020ALBERT:} which have been shown to perform well in several classification tasks. However, both these models cannot process inputs longer than 512 tokens and the concatenated inputs are generally much longer. So we also tried Longformer~\cite{Beltagy2020LongformerTL}, a BERT-like model with an attention mechanism designed to scale linearly with sequence length, thus allowing the model to encode longer documents. However, despite trying various hyperparameters, Longformer was not able to match the scores in our experiments. \begin{table}[t] \scriptsize \centering \input{figures/discriminative_res} \caption{Accuracy for the \textit{Character Identification}. The `partial' description setup used a truncated description ($50$ words) to allow including more of the summary. } \label{tab:disc-res} \end{table} Our second approach, a generative classifier, is inspired by~\citet{JMLR:v21:20-074} who studied transfer learning by converting NLP problems into a text-to-text format. The generative classifier addresses the character identification problem by directly generating the character name $\hat{c}$, given all character names (answer choices), the masked character description, and the summary (see Fig.~\ref{fig:identification}). During inference, we compute the model's probability of each of the answer choices, and output the one with the highest probability. We use this procedure to train several strong baselines built on top of the following pre-trained transformer-based models: BART~\cite{lewis2019bart}, T5~\cite{JMLR:v21:20-074}, and Longformer~\cite{Beltagy2020LongformerTL}. \vspace{0.15cm} \noindent\textbf{Implementation Details.}\space\space The RoBERTa and ALBERT multiple-choice classifiers were trained for 6 epochs, initial learning rate 1e-5 (ADAM optimizer), batch size 16. The generative classifier using BART was trained for 5 epochs, initial learning rate 5e-6, batch size 8. We used the Transformer package~\cite{Wolf2019HuggingFacesTS} for training. The T5 model was trained for 12 epochs on a TPU using the default parameters from the T5 repository (learning rate 1e-3 with AdaFactor, batch size 8).\footnote{\url{https://github.com/google-research/text-to-text-transfer-transformer}} We truncate the summaries (and descriptions) to satisfy model-specific maximum input length. \vspace{0.2cm} \noindent\textbf{Results.}\space\space Table~\ref{tab:disc-res} shows the accuracies of different baselines. The highest accuracy is achieved by ALBERT-XXL ($83.33\%$) followed by T5-11B ($80.16\%$). Although both ALBERT and T5 were given partial character descriptions, their specific pre-training loss and larger number of parameters (for T5-11B) lead to superior performance over other baselines. We observe that there is still a significant difference between the human performance ($91.80\%$) and the best model performance ($83.33\%$) on the character identification task, warranting future work on this direction. \begin{table}[t] \scriptsize \centering \input{figures/results} \caption{Automatic evaluation results for \textit{Character Description Generation}. BART-L achieved the best BLEU and ROUGE scores while Longformer performed best on BERTScore. } \label{tab:gen-results} \end{table} \section{Character Description Generation} \label{generative} We present several strong baselines for generating character descriptions by fine-tuning pre-trained transformer-based language models (LM)~\cite{Vaswani:17}. We study two types of models: (1) a standard left-to-right LM, namely GPT2-L \cite{radford2019language} which is trained with LM objective to predict the next word; and (2) two encoder-decoder models, namely BART\footnote{We use the bart-large-xsum as initial weights as our task can benefit from the summarization capability.} \cite{lewis2019bart} and Longformer~\cite{Beltagy2020LongformerTL}\footnote{\url{https://github.com/allenai/longformer}. We initialize parameters of Longformer with the same pre-trained BART.} which initialize the state of the Transformer by reading the input, and learn to generate the output. One of the challenges of the proposed task is the length of the summaries, which might exceed the maximum allowable length for most existing pre-trained models. To overcome this, we either: (1) simply truncate the literature summary at the end, or (2) only keep sentences from the literature summary that have a mention of the character of interest. For the latter, we use a coreference resolution model, SpanBERT~\cite{joshi2019coref,spanbert}, to identify character mentions within a summary. This results in a modified dataset of character-specific literature summaries paired with character descriptions. In addition to these two approaches, we also fine-tune Longformer~\cite{Beltagy2020LongformerTL} with original full-length literature summary. Longformer leverages an efficient encoding mechanism to avoid the quadratic memory growth and has been previously explored for NLU tasks (encoder-only). We integrate this approach into the pre-trained encoder-decoder BART model to encode inputs longer than its maximum token limit. All the models take \texttt{[name] $c$ [sum] $S$ [desc]} as input and generate the character description $D^c$ as output. \vspace{0.05cm} \noindent\textbf{Experiment with Full Literary Pieces.} \space\space We also run an experiment on a subset of our data with accompanying full-text of the literary pieces. Since it is infeasible to use the full texts as input given the memory constraints of current models, we coarsely select spans of the full-text beginning $50$ tokens before, and $50$ tokens after the occurrence of character's name. We use a Longformer model where the input is simply the concatenation of the selected spans. Due to the small size of the this subset, we perform a $5$-fold cross validation starting from a pre-trained model fine-tuned on summary-description pairs.\footnote{Pre-training data do not contain instances of this subset. \vspace{0.05cm} \noindent\textbf{Implementation Details.}\space\space We use the Transformer library~\cite{Wolf2019HuggingFacesTS}. Each baseline was trained for $5$ epochs with effective batch size of $8$, and initial learning rate of 5e-6. We use the maximum input length of $1024$ for GPT2, and $2048$ for BART\footnote{BART originally accepts inputs of maximum 1024 BPE-tokens. We extend this to 2048 by adjusting its positional embeddings.} and the variant of Longformer with truncated input. For experiment with original books, we use $16,384$ which is the maximum allowable input length for Longformer. During inference, we use beam search decoding with $5$ beams. \begin{figure} \centering \includegraphics[width=1.0\columnwidth]{figures/fine-grained-plot-3_new} \caption{Breakdown results for BART-L on subsets with annotated fact coverage as all/most/some/little. Results for other baselines are provided in Appendix.} \label{tab:gen-results-fine} \end{figure} \subsection{Automatic Evaluation} Following previous works, we use several standard, widely used automatic evaluation metrics. We use \textbf{BLEU-4}~\cite{papineni2002bleu} that measures overlap of \textit{n}-gram up to $n=4$, \textbf{ROUGE-\textit{n}} ($n{=}1,2$), and \textbf{ROUGE-L} F-1 scores~\cite{lin2004rouge}\footnote{Note that we did not include perplexity score as it is not comparable across LM-based and encoder-decoder models.} . However, recent works~\cite{novikova2017we, wang-etal-2018-metrics} have raised concerns on the usage of these metrics as they fail to capture paraphrases and conceptual information. To overcome these issues, we additionally include a model-based metric, \textbf{BERTScore}~\cite{bert-score}, which measures the cosine similarity between contextualized embeddings of the gold and generated outputs.\footnote{We use the code at \url{https://github.com/Tiiiger/bert_score} The result of the automatic evaluation is presented in Table~\ref{tab:gen-results}. According to the table, BART-L consistently achieves the best performance across BLEU and ROUGE scores. However, Longformer achieves a slightly better BERTScore. Both BART and Longformer outperform GPT2 in general. This can be in part because BART and Longformer can handle longer context, and are initially pre-trained on a combination of books and Wikipedia data and further fine-tuned on summarization tasks, while GPT2 is pre-trained on WebText only.\footnote{While these models could have had access to the original book text, they do not have access to the character descriptions (our outputs) during pre-training. So, this information should not principally change any of our empirical conclusions.} Models perform relatively better in the length truncation setups than in the coreference truncatio . We posit that this is because a lot of the key points about major characters are likely to appear earlier in the book summary (favoring length truncation). Also, there might be errors introduced by the coreference resolution model itself. \begin{table}[t] \scriptsize \centering \input{figures/full_book_results} \caption{Automatic evaluation results for models using full-text of books vs. literature summaries.} \label{tab:full-book} \end{table} In order to have a better insight into the models' performance with respect to varying level of task feasibility, in Fig.~\ref{tab:gen-results-fine}, we additionally report the breakdown of the results for BART-L on separate subsets with ``almost all'', ``most'', ``some'', ``little or none'' of the information about the character (refer to \textit{Fact Coverage} in \S\ref{data-validation}). As expected, we observe a consistent decline in the performance with lower amount of fact coverage. Results for other baselines are reported in Table~\ref{tab:gen-results-fine-rest} of the Appendix. In Table ~\ref{tab:full-book}, we compare the models when using selected spans from the original literary piece as the input vs. literature summaries as the input. We observe a decline in performance when we used the full text. This reveals that even though the literary pieces contain all the character information, this information is scattered which makes it harder for the model to identify important facts about the character. Using full texts also requires encoders which are better at understanding dialog, first-person narratives and different writing styles of the authors. We invite the community to consider this challenging but important problem. \begin{figure}[t] \centering \includegraphics[width=0.90\columnwidth]{figures/human-eval-2.pdf} \caption{Human evaluation of generated character descriptions. While the descriptions are grammatically correct and logically coherent, they often misrepresent or miss important details about the character.} \label{fig:human-desc-eval} \end{figure} \subsection{Human Evaluation} \label{sec:human_eval} To better evaluate the quality of the generated character descriptions, we conduct a human evaluation on $100$ test pairs of literature summaries and character descriptions generated by the BART-L model on Amazon Mechanical Turk.\footnote{Here we are evaluating $4$ character descriptions per summary, for the total of $25$ literature summaries.} Given a literature summary and multiple generated character descriptions (shown one by one), the workers were asked to rate each generated description on a Likert scale of $1-5$ ($1$ being the worst, and $5$ being the best) according to the following criteria: (1) \textbf{Grammatical correctness} to indicate if the generated description is grammatically correct, (2) \textbf{Logical correctness} to indicate whether the generated description is logically meaningful and coherent, (3) \textbf{Faithfulness} of the generated description with respect to the given summary (a faithful character description will not mention facts which are irrelevant to the character and/or not stated in the summary), (4) \textbf{Centrality} to evaluate whether the description captures important details and key facts about the character, and finally (5) the \textbf{Overall score} considering all the four criteria listed above. We provide a screenshot of the experiment in Fig.~\ref{fig:human-assess-2} of the Appendix. Fig.~\ref{fig:human-desc-eval} presents the results of this human evaluation. We observe that the generated descriptions show a reasonable level of grammatical ($4.43$) and logical correctness ($3.94$). However, they lack behind when it comes to faithfulness ($3.11$) and centrality ($3.10$). We also report the distribution of ratings in Table~\ref{tab:human-eval-dist}. These results indicate that solving this task requires designing better models of character-centric analysis of narrative. \begin{table}[t] \footnotesize \centering \input{figures/human-eval-dist} \caption{Percentage of different ratings from human evaluation of generated descriptions (1=worst, 5=best).} \label{tab:human-eval-dist} \end{table} \begin{table}[t] \footnotesize \centering \input{figures/analysis_res} \caption{Error Analysis: proportion of generated descriptions with different error types.} \label{tab:analysis} \end{table} \subsection{Qualitative Analysis} \label{sec:analysis} \input{6-analysis} \section{Introduction} \label{sec:intro} \input{1-intro} \section{Background} \label{sec:background} \input{2-background} \section{The LiSCU Dataset} \label{sec:data} \input{3-data} \input{4-model} \section{Conclusion} \label{sec:conclusion} \input{7-conclusion} \section*{Acknowledgments} This work was supported in part by ETH Grant (ETH-19 21-1) and NSF grant IIS2047232. We would also like to thank Jena D. Hwang for helping with designing the AMT task. \section*{Broader Impacts and Ethics Statement} \label{sec:bias} \noindent{\bf Bias in Narrative Texts:} \texttt{FiSCU}\xspace is based on novels which often reflect societal norms and biases of their times. Such a dataset can be used to understand societal bias as well as design Natural Language Understanding models that can be more aware of and possibly even avoid such biases. With this motivation, we analyzed the issue of gender bias in \texttt{FiSCU}\xspace. First, we inferred the gender of the characters in our dataset using the pronouns used to refer to them. We could not infer the gender of some of the characters because of errors in the coreference system or lack of enough mentions, and we filtered them out for this analysis. We found that there are significantly more male characters than female characters in our dataset. Specifically, $66\%$ of the characters are male. This suggests that systems that do not account for this bias might end up having more training data (and hence yield better performance) on descriptions of male characters than of female characters. Second, we also investigated the scope of gender bias in the summaries. We computed the average number of mentions of male and female characters (in the summaries). We found that on average male and female characters are mentioned $32.1$ and $31.7$ times, respectively. This indicates that even though there are fewer female characters in the literary pieces of our dataset, the ones that are present play a significant role in the development of the narrative. Possibly because of their importance in the narrative, they are mentioned as many times as male characters in the summary (which describes the main developments and not all details from the literary piece). Third, we investigated if the literary experts who composed the descriptions were biased in their analysis. For this, we compute the length of character descriptions of various characters. We found that there is no significant difference between male and female characters in this aspect. Specifically, the average number of tokens in the description of a male character was $203$, and that of a female character was $200$. Also, the average number of sentences in the description of a male character was $9.4$ and that of a female character was $9.3$. This also aligns with our observation in the previous experiment where we found that female characters, though fewer, play important roles in the narrative, and so their descriptions are not any shorter than descriptions of male characters. Overall, this analysis suggests that descriptions are not biased in their treatment of male and female characters. In any language generation setting, such as ours, there is the possibility of (potentially harmful) social biases that can be introduced in the training data. As we did not specifically control or regularize our model to remove the possibility of such biases, we would urge downstream users to undertake the necessary quality-assurance testing to evaluate the extent to which such biases might be present and impacting their trained system and to make modifications to their model and procedures accordingly. \noindent{\bf Human participation in our study :} We conducted 2 human evaluations on Amazon Mechanical Turk. To ensure the annotators were fairly compensated, we did several rounds of test runs and estimated the average time to finish one HIT. Workers were paid \$12/hr based on the HIT timings. We did not ask any personal, sensitive or identifying information from the annotators. \section{Collecting Annotations from Crowd Workers} \label{appendix-annotations} To alleviate the limitations of crowd-sourcing and ensure high quality of annotations, we took several steps. First, we conducted a pilot annotation exercise where we (authors) assessed the feasibility of the proposed task on a subset (250 instances) of the data. This pilot annotation helped us set up the task on AMT in a way that would make the task feasible for turkers (e.g. by asking clear concise questions). Second, we designed our setup to avoid annotator fatigue by asking them to read the summary context once and answer questions about all characters in that summary. Third, we ran a few experiments on AMT (before annotating the entire set) where we also included a `comment` section for turkers to allow them to bring up issues or ambiguities in our setup. We then manually analyzed the results and modified the tasks based on the comments. Finally, after annotating the entire set, we computed inter-annotator agreement as a way to ensure trust in the annotation quality. We found reasonable agreements between annotators as reported in Footnote 10 of the paper. We would also like to mention that we received several comments from the annotators that they found the task very interesting and enjoyable. \begin{table*}[t] \scriptsize \centering \input{figures/results_fine_shortened} \caption{Breakdown results on subsets of test set with annotated fact coverage as all/most/some/little.} \label{tab:gen-results-fine-rest} \end{table*} \begin{table*}[t] \renewcommand{\arraystretch}{1.2} \scriptsize \centering \input{figures/example3_w_sum} \caption{Qualitative example 1 for the generated descriptions. Words in \textcolor{red}{red} correspond to hallucinated or missing content, words in \textcolor{MengGreen}{green} correspond to faithful information. } \label{tab:errore_examples1} \end{table*} \begin{table*}[t] \renewcommand{\arraystretch}{1.2} \scriptsize \centering \input{figures/example4_w_sum} \caption{Qualitative example 2 for the generated descriptions. Words in \textcolor{red}{red} correspond to hallucinated or missing content, and words in \textcolor{MengGreen}{green} correspond to faithful information. } \label{tab:errore_examples2} \end{table*} \begin{table*}[t] \renewcommand{\arraystretch}{1.2} \scriptsize \centering \input{figures/example2_w_sum} \caption{Qualitative example 3 for the generated descriptions. Words in \textcolor{red}{red} correspond to hallucinated or missing content, words in \textcolor{MengGreen}{green} correspond to faithful information, and \underline{underline} corresponds to generic repetitive content. } \label{tab:errore_examples3} \end{table*} \newpage \begin{table*}[t] \renewcommand{\arraystretch}{1.2} \scriptsize \centering \input{figures/example1_w_sum} \caption{Qualitative example 4 for the generated descriptions. words in \textcolor{MengGreen}{green} correspond to faithful information, and \underline{underline} corresponds to generic repetitive content. } \label{tab:errore_examples4} \end{table*} \begin{figure*}[t] \centering \includegraphics[width=0.9\linewidth]{figures/amt_1.jpg} \caption{An illustration of human assessment on AMT.} \label{fig:human-assess-1} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=0.8\linewidth]{figures/amt_2.png} \caption{An illustration of human evaluation for generated character description.} \label{fig:human-assess-2} \end{figure*}
{'timestamp': '2021-09-14T02:19:36', 'yymm': '2109', 'arxiv_id': '2109.05438', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05438'}
arxiv
\section{Concluding Remarks} \label{sec:conclusion} In this paper, we studied the obnoxious facility location game with dichotomous preferences. This game generalizes obnoxious facility location game to more realistic scenarios. All of the mechanisms presented in this paper run in polynomial time, except that the running time of Mechanism~\ref{mech:sum-min} has exponential dependence on $k$ (and polynomial dependence on $n$). We can extend the results of Section~\ref{subsec:min-min-square} to obtain an analogue of Theorem~\ref{thm:min-min-opt-eg-plane} that holds for arbitrary convex polygon. We showed that Mechanism~\ref{mech:sum-min} is WGSP for all $k$ and is efficient for $k \le 3$. Properties~1 and~2 in the proof of our associated theorem, Theorem~\ref{thm:opt-sum-min}, do not hold for $k>3$. Nevertheless, we conjecture that Mechanism~\ref{mech:sum-min} is efficient for all $k$. It remains an interesting open problem to reduce the gap between the $\Omega(\sqrt{n})$ and $O(n)$ bounds on the approximation ratio $\alpha$ of WGSP $\alpha$-egalitarian mechanisms. \subsection{Egalitarian mechanisms for the cycle} \label{subsec:min-min-cycle} In this section, we present egalitarian mechanisms for the case where the agents are located on the unit-circumference circle $C$. We denote the point antipodal to $u$ on $C$ by $\widehat{u}$. We begin by considering the natural adaptation of Mechanism~\ref{mech:min-min} to a cycle. \begin{custommech}{8} \label{mech:min-min-circle} Let $I = (n, 1, \mathbf{x}, \mathbf{a})$ denote the reported $\DOFL$ instance and let $H$ denote $\haters(I, 1)$. If $H$ is empty build facility $F_1$ at $0$. If $H$ has only one agent $i$, then build $F_1$ at $\widehat{x_i}$. Otherwise, build $F_1$ at the midpoint of the largest gap between any two consecutive agents from $H$. Formally, let $H$ have $\ell$ agents $z_0, \dots, z_{\ell-1}$ such that $x_{z_0} \le x_{z_1} \le \dots \le x_{z_{\ell-1}}$. Let $\oplus$ denote addition modulo $\ell$. Build $F_1$ at the midpoint of $x_{z_o}$ and $x_{z_{o\oplus 1}}$ where $o$ is the smallest number in $\{0, \dots \ell-1\}$ such that $\Delta(x_{z_{o\oplus 1}}, x_{z_o}) = \max_{j \in \{0, \dots \ell-1\} } \Delta(x_{z_{j\oplus 1}}, x_{z_j})$. \end{custommech} \begin{lemma} \label{lem:min-min-circle-sp} Mechanism~\ref{mech:min-min-circle} is SP for single-facility $\OOFLG$. \end{lemma} \begin{proof} Let $(I,I')$ denote a single-facility $\OOFLG$ instance with $I = (n, 1, \mathbf{x}, \mathbf{a})$, $I' = (n, 1, \mathbf{x}, \mathbf{a}'),$ and let $i$ be an agent such that $\mathbf{a}' = (\mathbf{a}_{-i}, a_i')$. Using the same arguments as in the proof of Lemma~\ref{lem:min-min-sp-sfo}, we restrict our attention to the case where $F_1$ is in $a_i \setminus a'_i$. Let Mechanism~\ref{mech:min-min-circle} build $F_1$ at $y$ when agent $i$ reports truthfully. Let $H = \haters(I, 1)$ denote the set of agents who dislike $\{F_1\}$. Note that Mechanism~\ref{mech:min-min-circle} does not build $F_1$ at the location of any agent in $H$, that is, $y \neq x_{i'}$ for any $i'$ in $H$. Let the arc of $C$ that goes clockwise from $y$ to $x_i$ be $r_1$ and let the arc of $C$ that goes anti-clockwise from $y$ to $x_i$ be $r_2$. Both arcs $r_1$ and $r_2$ include the end-points $y$ and $x_i$. We consider three cases. Case 1: No agent in $H - i$ is located on $r_1$ or $r_2$. Hence $H = \{i\}$. Thus $y = \widehat{x_i}$, and $\Delta(x_i, y) = 1/2$. When agent $i$ reports $a_i'$, $F_1$ is built at $0$. Since $\Delta(x_i, 0) \le 1/2$, reporting $a_i'$ does not benefit agent $i$. Case 2: There are agents in $H - i$ located on $r_1$ or $r_2$, but not both. Without loss of generality, we assume that there is an agent in $H - i$ located on $r_2$ (and that there are no agents in $H - i$ on $r_1$). Let $i'$ be the closest agent to $y$ in $H-i$ on $r_2$. Let $d' = \Delta(y, x_{i'})$. Thus, $y$ is the midpoint of $x_{i'}$ and $x_i$. Hence $d' = \Delta(x_i, y)$. Let $i''$ be the closest agent in $H-i$ in the clockwise direction from $x_i$. Thus, $\Delta(x_{i''}, x_i) \le 2d'$. Since $\Delta(x_{i''}, x_i) \le 2d'$, when agent $i$ reports $a_i'$, $F_1$ is built on $r_1$, which does not benefit agent~$i$. Case 3: There are agents in $H - i$ on $r_1$ and $r_2$. Let the closest agent from $y$ in $H - i$ on $r_2$ (resp., $r_1$) be $a$ (resp., $b$), respectively. We have $\Delta(x_a, y) = \Delta(y, x_b)$. Let $d'$ denote $\Delta(x_a, y)$. Note that $\Delta(x_i, y) \ge d'$. Let the first agent from $H - i$ in the anti-clockwise and clockwise direction from $x_i$ be $i'$ and $i''$. We have, $\Delta(x_i, x_{i'}) \le 2d'$ and $\Delta(x_i, x_{i''}) \le 2d'$. Thus, when agent $i$ reports $a_i'$, either $F_1$ is built at $y$ or $F_1$ is built within distance $d'$ of $x_i$, neither of which benefits agent $i$. Thus, agent $i$ does not benefit by reporting $a_i'$. \end{proof} \begin{lemma} \label{lem:min-min-circle-opt} Mechanism~\ref{mech:min-min-circle} is egalitarian for single-facility $\OOFLG$. \end{lemma} \begin{proof} Let $I = (n, 1, \mathbf{x}, \mathbf{a})$ denote the reported $\DOFL$ instance and let $H$ denote $\haters(I, 1)$. Using the same arguments as in the proof of Lemma~\ref{lem:min-min-opt-sfo}, we assume that all agents belong to $H$. Let $y^*$ denote an optimal location for the facility and let $\textsc{OPT}$ denote $\MMW (I, y^*)$. Let $y'$ denote the location at which Mechanism~\ref{mech:min-min-circle} builds the facility and let $\textsc{ALG}$ denote $\MMW (I, y')$. Below we establish that $\textsc{ALG} \ge \textsc{OPT}$, which implies that Mechanism~\ref{mech:min-min-circle} is egalitarian. If $H$ is empty, then trivially Mechanism~\ref{mech:min-min-circle} is egalitarian. For the remainder of the proof, assume that $H$ is non-empty. We say that an agent in $H$ is \emph{tight} if it is as close to $y^*$ as any other agent in $H$. Thus for any tight agent $i$, $\textsc{OPT} = \Delta(y^*,x_i)$. Let $i$ be a tight agent. Assume that in the shorter arc between $x_i$ and $y^*$, $x_i$ is anti-clockwise from $y^*$ (the other case can be handled similarly). Thus $\textsc{OPT} = \Delta(x_i, y^*)$. Let $i'$ be the closest agent in $H$ in the clockwise direction from $y^*$. The definition of $i'$ implies that $\Delta(x_{i'}, y^*) \ge \textsc{OPT}$. It follows that $\Delta(x_i, x_{i'}) \ge 2 \cdot \textsc{OPT}$. Since $\Delta(x_i, x_{i'})$ is the gap between two consecutive agents in $H$ and Mechanism~\ref{mech:min-min-circle} builds the facility at the midpoint of the largest gap, we deduce that $\textsc{ALG} \ge \textsc{OPT}$. \end{proof} We define Mechanism~9 as the $\OOFLG$ mechanism $\Parallel{M}$, where $M$ denotes Mechanism~\ref{mech:min-min-circle}. Using Lemmas~\ref{lem:min-min-sfo-ooflg-sp}, \ref{lem:min-min-sfo-ooflg-opt}, \ref{lem:min-min-circle-sp}, and~\ref{lem:min-min-circle-opt}, we immediately obtain Theorem~\ref{thm:min-min-opt-eg-circle} below. \begin{theorem} \label{thm:min-min-opt-eg-circle} Mechanism~9 is SP and egalitarian. \end{theorem} Theorem~\ref{thm:min-min-circle-lowerbound} below extends Theorem~\ref{thm:min-min-lowerbound} to the case of the cycle. Theorem~\ref{thm:min-min-circle-lowerbound} implies that Mechanism~9 is not WGSP. \begin{theorem} \label{thm:min-min-circle-lowerbound} Let $M$ be a WGSP $\alpha$-egalitarian mechanism. Then $\alpha$ is $\Omega(\sqrt{n})$, where $n$ is the number of agents. \end{theorem} \begin{proof} It is easy to verify that the construction used in the proof of Theorem~\ref{thm:min-min-lowerbound} also works for the cycle and establishes the same lower bound. (We identify the point $1$ with the point $0$.) \end{proof} The following variant of Mechanism~9 is SGSP. As in the SGSP mechanism for the case when the agents are located in the unit interval, in this variant, we first replace the reported dislikes of all agents with $\{F_1\}$ and use Mechanism~\ref{mech:min-min-circle} to determine where to build $F_1$. Then we build all of the remaining facilities at the same location as $F_1$. This mechanism is SGSP because it disregards the reported aversion profile. We claim that this mechanism is $n$-egalitarian, where $n$ denotes the number of agents. To prove this claim, we first observe that the largest gap between two consecutive agents who report to dislike $\{F_1\}$ is at least $1/n$. Thus the minimum welfare achieved by the mechanism is at least $1/(2n)$. Since the optimal minimum welfare is at most $1/2$, the claim holds. \section{Egalitarian Mechanisms} \label{sec:min-min} We now design egalitarian mechanisms for $\OOFLG$ when the agents are located on an interval, cycle, or square. In Definition~\ref{def:parallel} below, we introduce a simple way to convert a single-facility $\OOFLG$ mechanism into a $\OOFLG$ mechanism. Observe that for single-facility $\OOFLG$ mechanisms, specifying the input $\DOFL$ instance $I = (n, 1, \mathbf{x}, \mathbf{a})$ is equivalent to specifying $(n, 1, \mathbf{x}, \haters(I, 1))$. \begin{definition} \label{def:parallel} For any single-facility $\OOFLG$ mechanism $M$, $\Parallel{M}$ denotes the $\OOFLG$ mechanism that takes as input a $\DOFL$ instance $I =(n,k,\Location, \Aversion)$ and outputs $\mathbf{y} = (y_1, \dots, y_k)$, where $y_j$ is the location at which $M$ builds the facility on input $(n, 1, \mathbf{x}, \haters(I, j))$. \end{definition} Lemmas~\ref{lem:min-min-sfo-ooflg-sp} and \ref{lem:min-min-sfo-ooflg-opt} below reduce the task of designing a SP egalitarian $\OOFLG$ mechanism to the single-facility case. \begin{restatable}{lemma}{minminsfoooflgsp} \label{lem:min-min-sfo-ooflg-sp} Let $M$ be a SP single-facility $\OOFLG$ mechanism. Then $\Parallel{M}$ is a SP $\OOFLG$ mechanism. \end{restatable} \begin{proof} Let $(I,I')$ denote a $\OOFLG$ instance with $I = (n,k,\Location, \Aversion)$, $I' = (n,k,\Location,\LieAversion)$, and let $i$ be an agent such that $\mathbf{a}' = (\mathbf{a}_{-i}, a_i')$. Let $\mathbf{y} = (y_1, \dots, y_k)$ (resp., $\mathbf{y'} = (y'_1, \dots, y'_k)$) denote $\Parallel{M}(I)$ (resp., $\Parallel{M}(I')$). Since $M$ is SP, we have $\Delta(x_i, y_j) \ge \Delta(x_i, y_j')$ for each facility $F_j$ in $a_i$. Thus $w(I,i, \mathbf{y}) \ge w(I, i, \mathbf{y'})$, implying that agent $i$ does not benefit by reporting $a_i'$ instead of $a_i$. \end{proof} \begin{restatable}{lemma}{minminsfoooflgopt} \label{lem:min-min-sfo-ooflg-opt} Let $M$ be an egalitarian single-facility $\OOFLG$ mechanism. Then $\Parallel{M}$ is an egalitarian $\OOFLG$ mechanism. \end{restatable} \begin{proof} Let $I = (n,k,\Location, \Aversion)$ denote the reported $\DOFL$ instance. Let an optimal solution be $\mathbf{y^*} = (y_1^*, \dots, y_k^*)$ and let the optimal (maximum) value of the minimum welfare be $\textsc{OPT} = \MMW(I, \mathbf{y^*})$. Let $\Parallel{M}$ build the facilities at $\mathbf{y}' = (y'_1, \dots, y'_k)$, resulting in a minimum welfare $\textsc{ALG} = \MMW(I, \mathbf{y}')$. For each facility $F_j$, we define $\textsc{OPT}_j$ (resp., $\textsc{ALG}_j$), as the distance from $y_j^*$ (resp., $y'_j$) to the nearest agent in $\haters(I, j)$ (or $\infty$ if $\haters(I, j)$ is empty). We have, \begin{equation*} \textsc{OPT} = \min\left(\min_j \textsc{OPT}_j, \min_{i\in \indiff(I)} w(I,i, \mathbf{y^*})\right) \end{equation*} and \begin{equation*} \textsc{ALG} = \min\left(\min_j \textsc{ALG}_j, \min_{i\in \indiff(I)} w(I, i, \mathbf{y}')\right). \end{equation*} Since $M$ is egalitarian, we have $\textsc{OPT}_j = \textsc{ALG}_j$ for all $j$. The welfare of agents in $\indiff(I)$ does not depend on the locations of the facilities. Thus, $\textsc{ALG} = \textsc{OPT}$ implying that $\Parallel{M}$ is egalitarian. \end{proof} \subsection{Egalitarian mechanisms for the unit interval} \label{subsec:min-min-interval} We begin by describing a SP egalitarian mechanism for single-facility $\OOFLG$ when the agents are located in the unit interval. \begin{custommech}{6} \label{mech:min-min} Let $I = (n, 1, \mathbf{x}, \mathbf{a})$ denote the reported $\DOFL$ instance and let $H$ denote $\haters(I, 1)$. If $H$ is empty, build $F_1$ at $0$. Otherwise, let $H$ contain $\ell$ agents $z_1, \dots, z_\ell$ such that $x_{z_1} \le x_{z_2} \le \dots \le x_{z_\ell}$. Let $d_1 = x_{z_1}$ and $d_3 = 1 - x_{z_\ell}$. If $\ell = 1$, then build $F_1$ at $0$ if $d_1 \ge d_3$, and at $1$ otherwise. If $\ell>1$, let $m$ be the midpoint of the leftmost largest interval between consecutive agents in $H$. Formally, $m = (x_{z_o} + x_{z_{o+1}}) / 2$, where $o$ is the smallest number in $[\ell-1]$ such that $x_{z_{o+1}} - x_{z_o} = \max_{j \in [\ell-1]} (x_{z_{j+1}} - x_{z_j})$. Let $d_2 = m - x_{z_o}$. Then build facility $F_1$ at $0$ if $d_1 \ge d_2$ and $d_1 \ge d_3$, at $m$ if $d_2 \ge d_3$, and at $1$ otherwise. \end{custommech} The following lemma shows that Mechanism~\ref{mech:min-min} is SP. It is established by examining how the location of the facility changes when an agent misreports. \begin{restatable}{lemma}{minminspsfo} \label{lem:min-min-sp-sfo} Mechanism~\ref{mech:min-min} is SP for single-facility $\OOFLG$. \end{restatable} \begin{proof} Let $(I,I')$ denote a single-facility $\OOFLG$ instance with $I = (n, 1, \mathbf{x}, \mathbf{a})$, $I' = (n, 1, \mathbf{x}, \mathbf{a}')$, and let $i$ be an agent such that $\mathbf{a}' = (\mathbf{a}_{-i}, a_i')$. If $F_1$ does not belong to $a_i$, the welfare of agent $i$ is independent of the location of $F_1$ and agent $i$ does not benefit by reporting $a'_i$. Moreover, if $F_1$ is in $a_i \cap a_i'$, then the location of $F_1$ does not change by reporting $a'_i$ instead of $a_i$, and again, agent $i$ does not benefit by reporting $a'_i$. Thus for the remainder of the proof, we assume that $F_1$ is in $a_i \setminus a'_i$. Let Mechanism~\ref{mech:min-min} build $F_1$ at $y$ when agent $i$ reports truthfully. We assume that $y < x_i$ (the other case can be handled symmetrically). Let $H = \haters(I, 1)$ denote the set of agents who dislike $\{F_1\}$. Note that Mechanism~\ref{mech:min-min} does not build $F_1$ at the location of any agent in $H$, that is, $y \neq x_{i'}$ for any $i'$ in $H$. Let $d_1$, $d_2$, and $d_3$ be as defined in Mechanism~\ref{mech:min-min} when all agents report truthfully. We consider two cases based on whether there is an agent from $H$ between $y$ and $x_i$. Case 1: No agent in $H - i$ is located in $[y, x_i]$. We consider two cases. Case 1.1: $y = 0$. Thus $d_1 = x_i$. When agent $i$ reports $a'_i$, $F_1$ is built at $0$, which does not benefit agent $i$. Case 1.2: $y \neq 0$. Thus $d_2 = x_i - y$, there is an agent $i'$ in $H$ at $y - d_2$, and there are no agents in $H$ in $(y - d_2, y + d_2)$. We consider two cases. Case 1.2.1: No agent in $H$ is located to the right of $x_i$. Hence $x_i \ge 1 - d_2$. Thus when agent $i$ reports $a'_i$, $F_1$ is built at $1$, which does not benefit agent $i$. Case 1.2.2: There is an agent in $H$ located to the right of $x_i$. Let $i''$ be the first agent to the right of $x_i$, breaking ties arbitrarily. Then $x_{i''} - x_i \le 2d_2$. Thus when agent $i$ reports $a'_i$, $F_1$ is built in $[y, x_i]$, which does not benefit agent $i$. Case 2: There is an agent in $H - i$ in $[y, x_i]$. Let $i'$ be the first agent to the right of $y$ in $H - i$. Let $d$ denote $d_1 = x_{i'}$ if $y = 0$, and $d_2 = x_{i'} - y$ otherwise. We deduce that $x_i - y \ge d$. We consider two cases. Case 2.1: No agent in $H$ is located to the right of $x_i$. Hence $x_i \ge 1 - d$. Thus when agent $i$ reports $a'_i$, $F_1$ is either built at $y$ or at $1$, neither of which benefits agent $i$. Case 2.2: There is an agent in $H$ located to the right of $x_i$. Let $b$ be the first agent to the right of $x_i$, breaking ties arbitrarily. Let agent $a$ be the agent located in $[0, x_i]$ that is closest to agent $i$, breaking ties arbitrarily. We deduce that $x_i - x_a \le 2d$ and $x_b - x_i \le 2d$. When agent $i$ reports $a'_i$, $F_1$ is built at $y$ or in $[x_i - d, x_i + d]$, neither of which benefits agent $i$. Thus agent $i$ does not benefit by reporting $a'_i$. \end{proof} \begin{lemma} \label{lem:min-min-opt-sfo} Mechanism~\ref{mech:min-min} is egalitarian for single-facility $\OOFLG$. \end{lemma} \begin{proof} Let $I = (n, 1, \mathbf{x}, \mathbf{a})$ denote the reported $\DOFL$ instance and let $H$ denote $\haters(I, 1)$. The welfare of any agent in $[n] \setminus H$ is independent of the location of the facility. Thus, a mechanism is egalitarian if it maximizes the minimum welfare of any agent in $H$. Mechanism~\ref{mech:min-min} ignores the agents that are not in $H$. Thus it is sufficient to show that Mechanism~\ref{mech:min-min} maximizes the minimum welfare on instances where all agents belong to $H$. Hence for the remainder of the proof, we assume that all agents belong to $H$. Let $y^*$ denote an optimal location for the facility and let $\textsc{OPT}$ denote $\MMW(I,y^*)$. Let $y'$ denote the location where Mechanism~\ref{mech:min-min} builds the facility and let $\textsc{ALG}$ denote $\MMW(I,y')$. Below we establish that $\textsc{ALG} \ge \textsc{OPT}$, which implies that Mechanism~\ref{mech:min-min} is egalitarian. If $H$ is empty then trivially Mechanism~\ref{mech:min-min} is egalitarian. For the remainder of the proof, assume that $H$ is non-empty. We say that an agent in $H$ is \emph{tight} if it is as close to $y^*$ as any other agent in $H$. Thus for any tight agent $i$, $\textsc{OPT} = |y^* - x_i|$. Similarly , $\textsc{ALG}$ is the distance between $y'$ and a closest agent in $H$. If $y^* = 0$, consider any tight agent $i$. Then no agent in $H$ is located in $[0, x_i)$. It follows that $d_1 = x_i = \textsc{OPT}$. As $\textsc{ALG} \ge d_1$, we have $\textsc{ALG} \ge \textsc{OPT}$. A symmetric argument can be made for the case $y^* = 1$. It remains to consider the case where $y^*$ does not belong to $\{0,1\}$. Assume that $x_i < y^*$ where $i$ is a tight agent (the other case can be handled symmetrically). We have $\textsc{OPT} = y^* - x_i$. Thus no agent in $H$ is located in $(x_i = y^* - \textsc{OPT}, y^* + \textsc{OPT})$. We consider two cases. Case 1: There is no agent $i'$ to the right of $y^*$. Thus $d_3 \ge \textsc{OPT}$. Since $\textsc{ALG} \ge d_3$, we have $\textsc{ALG} \ge \textsc{OPT}$. Case 2: There is an agent in $H$ to the right of $y^*$. Consider the leftmost such agent $i'$. Since $x_{i'} \ge y^* + \textsc{OPT}$, we have $d_2 \ge \textsc{OPT}$. Since $\textsc{ALG} \ge d_2$, we have $\textsc{ALG} \ge \textsc{OPT}$. \end{proof} We define Mechanism~7 as the $\OOFLG$ mechanism $\Parallel{M}$, where $M$ denotes Mechanism~\ref{mech:min-min}. Using Lemmas~\ref{lem:min-min-sfo-ooflg-sp} through \ref{lem:min-min-opt-sfo}, we immediately obtain Theorem~\ref{thm:min-min-opt-eg} below. \begin{theorem} \label{thm:min-min-opt-eg} Mechanism~7 is SP and egalitarian. \end{theorem} Below we provide a lower bound on the approximation ratio of any WGSP egalitarian mechanism. Theorem~\ref{thm:min-min-lowerbound} implies that Mechanism~7 is not WGSP. \begin{theorem} \label{thm:min-min-lowerbound} Let $M$ be a WGSP $\alpha$-egalitarian mechanism. Then $\alpha$ is $\Omega(\sqrt{n})$, where $n$ is the number of agents. \end{theorem} \begin{proof} Let $q$ be a large even integer, let $p$ denote $q^2 + 1$, and let $U$ (resp., $V$) denote the set of all integers $i$ such that $0<i<q^2/2$ (resp., $q^2/2<i<q^2$). We construct two $(p+3)$-agent two-facility $\OOFLG$ instances $(I,I)$ and $(I,I')$. In both $(I,I)$ and $(I,I')$, there is an agent located at $i/q^2$, called agent $i$, for each $i$ in $U \cup V$, and there are two agents each at $0$, $1/2$, and $1$. In $I$, each agent $i$ such that $i$ is in $U$ dislikes $\{F_2\}$, each agent $i$ such that $i$ is in $V$ dislikes $\{F_1\}$, one agent at $0$ (resp., $1/2$, $1$) dislikes $\{F_1\}$, and the other agent at $0$ (resp., $1/2$, $1$) dislikes $\{F_2\}$. In $I'$, agents $i$ such that $i$ is in $U \setminus \{1, \dots, q-1\}$, have alternating reports: agent $q$ reports $\{F_1\}$, agent $q+1$ reports $\{F_2\}$, agent $q+2$ reports $\{F_1\}$, and so on. Symmetrically, the agents $i$ such that $i$ is in $V \setminus \{q^2-q+1, \dots, q^2-1\}$, have alternating reports: agent $q^2-q$ reports $\{F_2\}$, agent $q^2-q-1$ reports $\{F_1\}$, agent $q^2-q-2$ reports $\{F_2\}$, and so on. All other agents in $I'$ report truthfully. Let the optimal minimum welfare for $\DOFL$ instance $I$ (resp., $I'$) be $\textsc{OPT}$ (resp., $\textsc{OPT}'$). It is easy to see that $\textsc{OPT}=1/4$ and $\textsc{OPT}'=\frac{1}{2q}$ (obtained by building the facilities at $(1/4, 3/4)$ and $(\frac{1}{2q}, 1-\frac{1}{2q})$, respectively). Let $\textsc{ALG}$ (resp., $\textsc{ALG}'$) denote the minimum welfare achieved by $M$ on instance $I$ (resp., $I'$). Below we prove that either $\textsc{OPT}/\textsc{ALG}\ge\frac{q}{4}$ or $\textsc{OPT}'/\textsc{ALG}'\ge q/2$. Let $M$ build facilities at $(y_1, y_2)$ (resp., $(y'_1, y'_2)$) on instance $I$ (resp., $I'$). We consider two cases. Case~1: $0 \le y'_1 < 1/q$ and $1-1/q < y'_2 \le 1$. Let $S$ denote the set of agents who lie in $I'$. If $y'_1 < y_1$ and $y'_2 > y_2$, then all agents in $S$ benefit by lying. Hence for $M$ to be WGSP, either $y'_1 \ge y_1$ or $y'_2 \le y_2$. Let us assume that $y'_1 \ge y_1$; the other case can be handled symmetrically. Since $y'_1 < 1/q$, we have $y_1 < 1/q$. Note that there is an agent at $0$ who reported $\{F_1\}$. Thus $\textsc{ALG} \le y_1 < 1/q$. Hence $\textsc{OPT}/\textsc{ALG}\ge \frac{q}{4}$. Case~2: $y'_1 \ge 1/q$ or $y'_2 \le 1-1/q$. If $y'_1 \ge 1/q$, then at least one agent within distance $1/q^2$ of $y'_1$ reported $\{F_1\}$ in $I'$. A similar observation holds for the case $y'_2 \le 1-1/q$. Thus $\textsc{ALG}' \le 1/q^2$. Hence $\textsc{OPT}' / \textsc{ALG}' \ge q/2$. The preceding case analysis shows that $\alpha \ge q/4$. Since $q = \sqrt{p-1} = \sqrt{n-4}$, the theorem holds. \end{proof} The following variant of Mechanism~7 is SGSP. In this variant, we first replace the reported dislikes of all agents with $\{F_1\}$ and use Mechanism~\ref{mech:min-min} to determine where to build $F_1$. Then we build all of the remaining facilities at the same location as $F_1$. This mechanism is SGSP because it disregards the reported aversion profile. We claim that this mechanism is $2(n+1)$-egalitarian, where $n$ denotes the number of agents. To prove this claim, we first observe that when Mechanism~\ref{mech:min-min} is run as a subroutine within this mechanism, we have $\max(d_1, 2d_2, d_3) \ge 1/(n+1)$. Thus the minimum welfare achieved by the mechanism is at least $1/(2(n+1))$. Since the optimal minimum welfare is at most $1$, the claim holds. \subsection{An egalitarian mechanism for the unit square} \label{subsec:min-min-square} We extend Mechanism~\ref{mech:min-min} to a SP egalitarian mechanism for single-facility $\OOFLG$ when the agents are located in the unit square. Let $S$ denote $[0,1]^2$, let $B$ denote the boundary of $S$, and let $x_i = (a_i, b_i)$ denote the location of agent $i$. For convenience, we assume that all agents are located at distinct points; the results below generalize easily to the case where this assumption does not hold. \begin{custommech}{10} \label{mech:min-min-plane} Let $I = (n, 1, \mathbf{x}, \mathbf{a})$ denote the reported $\DOFL$ instance and let $H$ denote $\haters(I, 1)$. If $H$ is empty, build $F_1$ at $(0,0)$. Otherwise, construct the Voronoi diagram $D$ associated with the locations of the agents in $H$. Let $V$ be the union of the following three sets of vertices: the vertices of $D$ in the interior of $S$; the points of intersection between $B$ and $D$; the four vertices of $S$. For each $v$ in $V$, let $d_v$ denote the minimum distance from $v$ to any agent in $H$. Build $F_1$ at a vertex $v$ maximizing $d_v$, breaking ties first by $x$-coordinate and then by $y$-coordinate. \end{custommech} Toussaint presents an efficient $O(n\log n)$ algorithm to find the optimal $v$ in Mechanism~\ref{mech:min-min-plane} \cite{TOUSSAINT1983}. The following lemma establishes that Mechanism~\ref{mech:min-min-plane} is egalitarian. The lemma is shown using Theorem~2 of \cite{TOUSSAINT1983} for the largest empty circle with location constraints problem. \begin{restatable}{lemma}{minminplaneopt} \label{lem:min-min-plane-opt} Mechanism~\ref{mech:min-min-plane} is egalitarian for single-facility $\OOFLG$. \end{restatable} \begin{proof} Let $I = (n, 1, \mathbf{x}, \mathbf{a})$ denote the reported $\DOFL$ instance and let $H$ denote $\haters(I, 1)$. Using the same arguments as in the proof of Lemma~\ref{lem:min-min-opt-sfo}, we assume that all agents belong to $H$. Let $y^*$ denote an optimal location for the facility and let $\textsc{OPT}$ denote $\MMW(I, y^*)$. Let $y'$ denote the location where Mechanism~\ref{mech:min-min-plane} builds the facility and let $\textsc{ALG}$ denote $\MMW(I, y')$. Below we establish that $\textsc{ALG} = \textsc{OPT}$, which implies that Mechanism~\ref{mech:min-min-plane} is egalitarian. If $H$ is empty, then clearly $\textsc{ALG} = \textsc{OPT}$. Otherwise, finding the optimal location at which to build facility $F_1$ is equivalent to finding the maximum-radius circle centered in the interior or on the boundary of $S$ such that the interior of the circle has no points from $\{x_i \mid i \in H\}$. This problem is known as Largest Empty Circle with Location Constraint \cite{TOUSSAINT1983}. Toussaint [\cite{TOUSSAINT1983}, Theorem 2]\footnote{Toussiant assumes that no three points are collinear and no four points are cocircular, but the result coninues to hold without these assumptions.} shows that the optimal center for the circle is either a vertex of the Voronoi diagram of $S$, a point of intersection of $D$ with $B$, or a vertex of $S$. Hence $\textsc{ALG} = \textsc{OPT}$. \end{proof} We use a case analysis to establish Lemma~\ref{lem:min-min-opt-sfo-plane} below. The most interesting case deals with an agent $i$ who dislikes $F_1$ but does not report it. In this case, the key insight is that when agent $i$ misreports, facility $F_1$ is built either (1) at the same location as when agent $i$ reports truthfully, or (2) inside or on the boundary of the Voronoi region that contains $x_i$ when agent $i$ reports truthfully. \begin{restatable}{lemma}{minminoptsfoplane} \label{lem:min-min-opt-sfo-plane} Mechanism~\ref{mech:min-min-plane} is SP for single-facility $\OOFLG$. \end{restatable} \begin{proof} Let $(I,I')$ denote a single-facility $\OOFLG$ instance with $I = (n, 1, \mathbf{x}, \mathbf{a})$, $I' = (n, 1, \mathbf{x}, \mathbf{a}')$, and let $i$ be an agent such that $\mathbf{a}' = (\mathbf{a}_{-i}, a_i')$. Using the same arguments as in the proof of Lemma~\ref{lem:min-min-sp-sfo}, we restrict our attention to the case where $F_1$ is in $a_i \setminus a'_i$. Let Mechanism~\ref{mech:min-min-plane} build $F_1$ at $y$ ($y'$, resp.) when agent $i$ reports $a_i$ ($a'_i$, resp.). Let $H = \haters(I, 1)$ denote the set of agents who dislike $\{F_1\}$. Note that Mechanism~\ref{mech:min-min-plane} does not build $F_1$ at the location of any agent in $H$, that is, $y \neq x_{i'}$ for all $i'$ in $H$. When all agents report truthfully, the Voronoi diagram of $S$ consists of $|H|$ non-overlapping polygons with each polygon containing one agent. Let $P$ be the polygon containing agent $i$ when all agents report truthfully. When agent $i$ reports $a_i'$, the only change to the Voronoi diagram is in the interior and on the boundary of $P$. So when agent $i$ reports $a_i'$, $F_1$ is built either at $y$ or inside $P$ (boundary inclusive). If it is built at $y$, agent $i$ does not benefit. Thus, for the remainder of the proof, we assume that $y'$ belongs to the interior of $P$. Let $\textsc{OPT}$ (resp., $\textsc{OPT}'$) be the closest distance of any agent from $H$ (resp., $H - i$) to the point $y$ (resp., $y'$). Let $d$ and $d'$ denote $\Delta(x_i, y)$ and $\Delta(x_i, y')$, respectively. Hence $d \ge \textsc{OPT}$. Since the distance from $y$ to any agent in $H - i$ is at least $\textsc{OPT}$, we have $\textsc{OPT}' \ge \textsc{OPT}$ . Assume for the sake of contradiction that Mechanism~\ref{mech:min-min-plane} is not SP. Hence $d' > d$. We begin by showing that $\textsc{OPT} = \textsc{OPT}'$. Suppose $\textsc{OPT} \neq \textsc{OPT}'$. Since $\textsc{OPT}' \ge \textsc{OPT}$, we have $\textsc{OPT}' > \textsc{OPT}$. Let us examine the situation when $F_1$ is built at $y'$ when agent $i$ reports truthfully. We have $d' > d$. Moreover, the agent in $H - i$ closest to $y'$ is at distance $\textsc{OPT}'$ from $y'$. Since $d' > d$ and $\textsc{OPT}' > \textsc{OPT}$, we have $\MMW(I, y') > \MMW(I, y)$. This contradicts Lemma~\ref{lem:min-min-plane-opt}, since it implies that Mechanism~\ref{mech:min-min-plane} is egalitarian. Thus $\textsc{OPT} = \textsc{OPT}'$. Recall that $y'$ belongs to $P$. Hence the closest agent in $H$ to $y'$ is agent $i$. Thus $d' \le \textsc{OPT}'$. We have established that $\textsc{OPT} \le d$. Since $\textsc{OPT} \le d$, $d < d'$, and $d' \le \textsc{OPT}'$, we obtain $\textsc{OPT} < \textsc{OPT}'$, which contradicts $\textsc{OPT} = \textsc{OPT}'$. Thus $d' \le d$, and hence agent $i$ does not benefit by reporting $a_i'$. \end{proof} We define Mechanism~11 as the $\OOFLG$ mechanism $\Parallel{M}$, where $M$ denotes Mechanism~\ref{mech:min-min-plane}. Using Lemmas~\ref{lem:min-min-sfo-ooflg-sp}, \ref{lem:min-min-sfo-ooflg-opt}, \ref{lem:min-min-plane-opt}, and~\ref{lem:min-min-opt-sfo-plane}, we immediately obtain Theorem~\ref{thm:min-min-opt-eg-plane} below. \begin{theorem} \label{thm:min-min-opt-eg-plane} Mechanism~11 is SP and egalitarian. \end{theorem} \section{Introduction} The facility location game ($\FLG$) was introduced by Procaccia and Tannenholtz~\cite{PROCACCIA2009}. In this setting, a central planner wants to build a facility that serves agents located on a path. The agents report their locations, which are fed to a mechanism that decides where the facility should be built. Procaccia and Tannenholtz studied two different objectives that the planner seeks to minimize: the sum of the distances from the facility to all agents and the maximum distance of any agent to the facility. Every agent aims to maximize their welfare, which increases as their distance to the facility decreases. An agent or a coalition of agents can misreport their location(s) to try to increase their welfare. It is natural to seek strategyproof~(SP) or group-strategyproof (GSP) mechanisms, which incentivize truthful reporting. Often such mechanisms cannot simultaneously optimize the planner's objective. In these cases, it is desirable to approximately optimize the planner's objective. In real scenarios, an agent might dislike a certain facility, such as a power plant, and want to stay away from it. This variant, called the obnoxious facility location game ($\OFLG$), was introduced by Cheng et al., who studied the problem of building an obnoxious facility on a path~\cite{CHENG2011}. In the present paper, we consider the problem of building multiple obnoxious facilities on a path. With multiple facilities, there are different ways to define the welfare function. For example, in the case of two facilities, the welfare of the agent can be the sum, minimum, or maximum of the distances to the two facilities. In our work, as all the facilities are obnoxious, a natural choice for welfare is the minimum distance to any obnoxious facility: the closest facility to an agent causes them the most annoyance, and if it is far away, then the agent is satisfied. A facility might not be universally obnoxious. Consider, for example, a school or sports stadium. An agent with no children might consider a school to be obnoxious due to the associated noise and traffic, while an agent with children might not consider it to be obnoxious. Another agent who is not interested in sports might similarly consider a stadium to be obnoxious. We assume that each agent has dichotomous preferences; they dislike some subset of the facilities and are indifferent to the others. Each agent reports a subset of facilities to the planner. As the dislikes are private information, the reported subset might not be the subset of facilities that the agent truly dislikes. On the other hand, we assume that the agent locations are public and cannot be misreported. In this paper, we study a variant of $\FLG$, which we call $\OOFLG$ (Dichotomous Obnoxious Facility Location Game), that combines the three aspects mentioned above: multiple (heterogeneous) obnoxious facilities, minimum distance as welfare, and dichotomous preferences. We seek to design mechanisms that perform well with respect to either a utilitarian or egalitarian objective. The utilitarian objective is to maximize the social welfare, that is, the total welfare of all the agents. A mechanism that maximizes social welfare is said to be efficient. The egalitarian objective is to maximize the minimum welfare of any agent. For both objectives, we seek mechanisms that are SP, or better yet, weakly or strongly group-strategyproof (WGSP / SGSP). \subsection{Our contributions} We study $\OOFLG$ with $n$ agents. In Section~\ref{sec:sum-min}, we consider the utilitarian objective. We present $2$-approximate SGSP mechanisms for any number of facilities when the agents are located on a path, cycle, or square. We obtain the following two additional results for the path setting. In the first main result of the paper, we obtain a mechanism that is WGSP for any number of facilities and efficient for up to three facilities. To show that this mechanism is WGSP, we relate it to a weighted approval voting mechanism. To prove its efficiency, we identify two crucial properties that the welfare function satisfies, and we use an exchange argument. For the path setting, we also show that no SGSP mechanism can achieve an approximation ratio better than $5/4$, even for one facility. In Section~\ref{sec:min-min}, we consider the egalitarian objective. We provide SP mechanisms for any number of facilities when the agents are located on a path, cycle, or square. In the second main result of the paper, we prove that the approximation ratio achieved by any WGSP mechanism is $\Omega(\sqrt{n})$, even for two facilities. Also, we present a straightforward $O(n)$-approximate WGSP mechanism. Both of the results for WGSP mechanisms hold for $\OOFLG$ when the agents are located on a path or cycle. Table~\ref{tab:results} summarizes our results. \begin{table} \centering \caption{Summary of our results for $\OOFLG$ when the agents are located on a path. The heading LB (resp., UB) stands for lower (resp., upper) bound. The results in the egalitarian column also hold when the agents are located on a cycle. Boldface results hold when the agents are located on a path, cycle, or square.} \begin{tabular}{ l | c c | c c |} \cline{2-5} & \multicolumn{2}{c|}{Utilitarian} & \multicolumn{2}{c|}{Egalitarian} \\ \cline{2-5} & LB & UB & LB & UB \\ \hline \multicolumn{1}{|l|}{SP} & \multirow{2}{*}{$\mathbf{1}$} & \multirow{2}{*}{$1$ for $k \le 3$} & $\mathbf{1}$ & $\mathbf{1}$\\ \cline{1-1} \cline{4-5} \multicolumn{1}{|l|}{WGSP} & & & \multirow{2}{*}{$\Omega(\sqrt{n})$} & \multirow{2}{*}{$O(n)$}\\ \cline{1-3} \multicolumn{1}{|l|}{SGSP} & $5/4$ & $\mathbf{2}$ & & \\ \hline \end{tabular} \label{tab:results} \end{table} \section{Preliminaries} \label{sec:preliminaries} The problems considered in this paper involve a set of agents located on a path, cycle, or square. In the path (resp., cycle, square) setting, we assume without loss of generality that the path (resp., cycle, square) is the unit interval (resp., unit-circumference circle, unit square). We map the points on the unit-circumference circle to $[0,1)$, in the natural manner. Thus, in the path (resp., cycle, square) setting, each agent $i$ is located in $[0,1]$ (resp., $[0,1)$, $[0,1]^2$). The distance between any two points $x$ and $y$ is denoted $\Delta(x,y)$. In the path and square settings, $\Delta(x,y)$ is defined as the Euclidean distance between $x$ and $y$. In the cycle setting, $\Delta(x,y)$, is defined as the length of the shorter arc between $x$ and $y$. In all settings, we index the agents from $1$. Each agent has a specific location in the path, cycle, or square. A \emph{location profile} $\mathbf{x}$ is a vector $(x_1,\ldots,x_n)$ of points, where $n$ denotes the number of agents and $x_i$ is the location of agent $i$. Sections~\ref{subsec:sum-min-interval} and~\ref{subsec:min-min-interval} (resp., Sections~\ref{subsec:sum-min-cycle} and~\ref{subsec:min-min-cycle}, Sections~\ref{subsec:sum-min-square} and~\ref{subsec:min-min-square}) present our results for the path (resp., cycle, square) setting. Consider a set of agents $1$ through $n$ and a set of facilities $\mathcal{F}$, where we assume that each agent dislikes (equally) certain facilities in $\mathcal{F}$ and is indifferent to the rest. In this context, we define an \emph{aversion profile} $\mathbf{a}$ as a vector $(a_1,\ldots,a_n)$ where each component $a_i$ is a subset of $\mathcal{F}$. We say that such an aversion profile is \emph{true} if each component $a_i$ is equal to the subset of $\mathcal{F}$ disliked by agent $i$. In this paper, we also consider \emph{reported} aversion profiles where each component $a_i$ is equal to the set of facilities that agent $i$ claims to dislike. Since agents can lie, a reported aversion profile need not be true. For any aversion profile $\mathbf{a}$ and any subset $C$ of agents $[n]$, $\mathbf{a}_C$ (resp., $\mathbf{a}_{-C}$) denotes the aversion profile for the agents in (resp., not in) $C$. For a singleton set of agents $\{i\}$, we abbreviate $\mathbf{a}_{-\{i\}}$ as $\mathbf{a}_{-i}$. An instance of the dichotomous obnoxious facility location ($\DOFL$) problem is given by a tuple $(n,k,\mathbf{x},\mathbf{a})$ where $n$ denotes the number of agents, there is a set of $k$ facilities $\mathcal{F}=\{F_1,\ldots,F_k\}$ to be built, $\mathbf{x}=(x_1,\ldots,x_n)$ is a location profile for the agents, and $\mathbf{a}=(a_1,\ldots,a_n)$ is an aversion profile (true or reported) for the agents with respect to $\mathcal{F}$. A solution to such a $\DOFL$ instance is a vector $\mathbf{y}=(y_1,\ldots,y_k)$ where component $y_j$ specifies the point at which to build $F_j$. We say that a $\DOFL$ instance is true (resp., reported) if the associated aversion profile is true (resp., reported). For any $\DOFL$ instance $I = (n,k,\Location, \Aversion)$ and any $j$ in $[k]$, we define $\haters(I, j)$ as $\{i \in [n] \mid F_j \in a_i\}$, and $\indiff(I)$ as $\{ i \in [n] \mid a_i = \emptyset \}$. For any $\DOFL$ instance $I=(n,k,\mathbf{x},\mathbf{a})$ and any associated solution $\mathbf{y}$, we define the \emph{welfare} of agent $i$, denoted $w(I,i,\mathbf{y})$, as $\min_{j:F_j \in a_i} \Delta(x_i, y_j)$, i.e., the minimum distance from $x_i$ to any facility in $a_i$. Remark: If $a_i$ is empty, we define $w(I,i,\mathbf{y})$ as $1/2$ in the cycle setting, $\max(\Delta(x_i, 0), \Delta(x_i, 1))$ in the path setting, and the maximum distance from $x_i$ to a corner in the square setting. The foregoing definition of agent welfare is suitable for true $\DOFL$ instances, and is only meaningful for reported $\DOFL$ instances where the associated aversion profile is close to true. In this paper, reported aversion profiles arise in the context of mechanisms that incentivize truthful reporting, so it is reasonable to expect such aversion profiles to be close to true. We define the \emph{social welfare} (resp., \emph{minimum welfare}) as the sum (resp., minimum) of the individual agent welfares. When the facilities are built at $\mathbf{y}$, the social welfare and minimum welfare are denoted by $\SSW(I,\mathbf{y})$ and $\MMW(I,\mathbf{y})$, respectively. Thus $\SSW(I,\mathbf{y})=\sum_{i \in [n]}w(I,i,\mathbf{y})$ and $\MMW(I,\mathbf{y})=\min_{i \in [n]}w(I,i,\mathbf{y})$. \begin{definition} For $\alpha \ge 1$, a $\DOFL$ algorithm $A$ is $\alpha$-efficient if for any $\DOFL$ instance $I$, \begin{equation*} \max_{\mathbf{y}} \SSW(I, \mathbf{y}) \le \alpha \SSW (I, A(I)). \end{equation*} Similarly, $A$ is $\alpha$-egalitarian if for any $\DOFL$ instance $I$, \begin{equation*} \max_{\mathbf{y}} \MMW(I, \mathbf{y}) \le \alpha \MMW (I, A(I)). \end{equation*} \end{definition} A $1$-efficient (resp., $1$-egalitarian) $\DOFL$ algorithm, is said to be efficient (resp., egalitarian). We are now ready to define a $\DOFL$-related game, which we call $\OOFLG$. It is convenient to describe a $\OOFLG$ instance in terms of a pair $(I,I')$ of $\DOFL$ instances where $I=(n,k,\mathbf{x},\mathbf{a})$ is true and $I'=(n,k,\mathbf{x},\mathbf{a}')$ is reported. There are $n$ agents indexed from $1$ to $n$, and a planner. There is a set of $k$ facilities $\mathcal{F}=\{F_1,\ldots,F_k\}$ to be built. The numbers $n$ and $k$ are publicly known, as is the location profile $\mathbf{x}$ of the agents. Each component $a_i$ of the true aversion profile $\mathbf{a}$ is known only to agent $i$. Each agent $i$ submits component $a_i'$ of the reported aversion profile $\mathbf{a}'$ to the planner. The planner, who does not have access to $\mathbf{a}$, runs a $\DOFL$ algorithm, call it $A$, to map $I'$ to a solution. The input-output behavior of $A$ defines a $\OOFLG$ mechanism, call it $M$; in the special case where $k=1$, we say that $M$ is a single-facility $\OOFLG$ mechanism. We would like to choose $A$ so that $M$ enjoys strong game-theoretic properties. We say that $M$ is $\alpha$-efficient (resp., $\alpha$-egalitarian, efficient, egalitarian) if $A$ is $\alpha$-efficient (resp., $\alpha$-egalitarian, efficient, egalitarian). As indicated earlier, such properties (which depend on the notion of agent welfare) are only meaningful if the reported aversion profile is close to true. To encourage truthful reporting, we require our mechanisms to be SP, as defined below; we also consider the stronger properties WGSP and SGSP. The SP property says that no agent can increase their welfare by lying about their dislikes. \begin{definition} A $\OOFLG$ mechanism $M$ is SP if for any $\OOFLG$ instance $(I, I')$ with $I = (n,k,\Location, \Aversion)$, and $I' = (n,k,\Location,\LieAversion)$, and any agent $i$ in $[n]$ such that $\mathbf{a}' = (\mathbf{a}_{-i}, a_i')$, we have \begin{equation*} w(I, i, M(I)) \ge w(I, i, M(I')). \end{equation*} \end{definition} The WGSP property says that if a non-empty coalition $C \subseteq [n]$ of agents lies, then at least one agent in $C$ does not increase their welfare. \begin{definition} A $\OOFLG$ mechanism $M$ is WGSP if for any $\OOFLG$ instance $(I, I')$ with $I = (n,k,\Location, \Aversion)$, and $I' = (n,k,\Location,\LieAversion)$, and any non-empty coalition $C \subseteq [n]$ such that $\mathbf{a}' = (\mathbf{a}_{-C}, \mathbf{a}'_C)$, there exists an agent $i$ in $C$ such that \begin{equation*} w(I, i, M(I)) \ge w(I, i, M(I')). \end{equation*} \end{definition} The SGSP property says that if a coalition $C \subseteq [n]$ of agents lies and some agent in $C$ increases their welfare then some agent in $C$ decreases their welfare. \begin{definition} A $\OOFLG$ mechanism $M$ is SGSP if for any $\OOFLG$ instance $(I, I')$ with $I = (n,k,\Location, \Aversion)$, and $I' = (n,k,\Location,\LieAversion)$, and any coalition $C \subseteq [n]$ such that $\mathbf{a}' = (\mathbf{a}_{-C}, \mathbf{a}'_C)$, if there exists an agent $i$ in $C$ such that \begin{equation*} w(I, i, M(I)) < w(I, i, M(I')), \end{equation*} then there exists an agent $i'$ in $C$ such that \begin{equation*} w(I, i', M(I)) > w(I, i', M(I')). \end{equation*} \end{definition} Every SGSP mechanism is WGSP and every WGSP mechanism is SP. \subsection{Related work} \label{sec:related-works} $\FLG$ was introduced by Procaccia and Tannenholtz \cite{PROCACCIA2009}. Many generalizations and extensions of $\FLG$ have been studied \cite{ALON2010,DOKOW2012,FELDMAN2013,FILOS0217,FOTAKIS2010,FOTAKIS2014,LU2010,ZHANG2014}; here we highlight some of the most relevant work. Cheng et al.\ introduced $\OFLG$ and presented a WGSP mechanism to build a single facility on a path \cite{CHENG2011}. Later they extended the model to cycles and trees \cite{CHENG2013}. A complete characterization of single-facility SP/WGSP mechanisms for paths has been developed \cite{HAN2012,IBARA2012}. Duan et al.\ studied the problem of locating two obnoxious facilities at least distance $d$ apart \cite{DUAN2019}. Other variants of $\OFLG$ have been considered \cite{CHENG2013BOUNDEDSERVICE,FUKUI2019,OOMINE2016,YE2015}. Agent preferences over the facilities were introduced to $\FLG$ in \cite{FEIGENBAUM2015} and \cite{ZOU2015}. Serafino and Ventre studied $\FLG$ for building two facilities where each agent likes a subset of the facilities \cite{SERAFINO201627}. Anastasiadis and Deligkas extended this model to allow the agents to like, dislike, or be indifferent to the facilities \cite{ANASTASIADIS2018}. The aforementioned works address linear (sum) welfare function. Yuan et al.\ studied non-linear welfare functions (max and min) for building two non-obnoxious facilities \cite{YUAN2016}; their results have subsequently been strengthened \cite{CHEN2020,LI2020}. In the present paper, we initiate the study of a non-linear welfare function (min) for building multiple obnoxious facilities. \subsection{Efficient mechanism for the cycle} \label{subsec:sum-min-cycle} Now we present a simple adaptation of Mechanism~\ref{mech:sum-min-sgsp} to the case where the agents are located on a cycle. \begin{custommech}{4} \label{mech:sum-min-sgsp-circle} Let $(n,k,\Location, \Aversion)$ denote the reported $\DOFL$ instance. Build all facilities at $0$ if \begin{equation*} \sum_{i\in [n]} \Delta(x_i,0) \ge \sum_{i \in [n]} \Delta(x_i, 1/2); \end{equation*} otherwise, build all facilities at $1/2$. \end{custommech} As with Mechanism~\ref{mech:sum-min-sgsp}, reported dislikes do not affect the locations at which Mechanism~\ref{mech:sum-min-sgsp-circle} builds the facilities. Hence Mechanism~\ref{mech:sum-min-sgsp-circle} is SGSP. \begin{theorem} \label{thm:sum-min-sgsp-circle-sgsp} Mechanism~\ref{mech:sum-min-sgsp-circle} is SGSP. \end{theorem} \begin{theorem} \label{thm:sum-min-sgsp-circle-opt} Mechanism~\ref{mech:sum-min-sgsp-circle} is $2$-efficient. \end{theorem} \begin{proof} We sketch a proof that is similar to our proof of Theorem~\ref{thm:opt-sum-min-sgsp}. Let $I = (n,k,\Location, \Aversion)$ denote the reported $\DOFL$ instance. Let $\textsc{ALG}$ denote the social welfare obtained by Mechanism~\ref{mech:sum-min-sgsp-circle} on this instance, and let $\textsc{OPT}$ denote the maximum possible social welfare on this instance. We need to prove that $2\cdot\textsc{ALG}\geq\textsc{OPT}$. Assume without loss of generality that Mechanism~\ref{mech:sum-min-sgsp-circle} builds all facilities at $0$. (A symmetric argument handles the case where all facilities are built at $1/2$). Using similar arguments, we obtain $\textsc{ALG} \ge \sum_{i\in [n]} \Delta(x_i,0)$. Also, we have $\sum_{i\in [n]} \Delta(x_i,0) \ge \sum_{i \in [n]} \Delta(x_i, 1/2)$, and $\Delta(x_i, 0) + \Delta(x_i, 1/2) \ge 1/2$ for all agents $i$, implying that $\sum_{i\in [n]} \Delta(x_i, 0) \ge n/4$. Thus $\textsc{ALG} \ge n/4$. Since no agent has welfare greater than $1/2$, we have $n/2 \ge \textsc{OPT}$. Thus, $2 \cdot \textsc{ALG} \ge n/2 \ge \textsc{OPT}$, as required. \end{proof} \subsection{Efficient mechanism for the unit square} \label{subsec:sum-min-square} We now show how to adapt Mechanism~\ref{mech:sum-min-sgsp} to the case where the agents are located in the unit square. \begin{custommech}{5} \label{mech:sum-min-sgsp-square} Let $(n,k,\Location, \Aversion)$ denote the reported $\DOFL$ instance. For each point $p$ in $\{0,1\}^2$, let $d_p$ denote $\sum_{i\in [n]} \Delta(x_i,p)$. Let $q$ be the point in $\{0,1\}^2$ that maximizes $d_q$, breaking ties lexicographically. Build all facilities at $q$. \end{custommech} As in the case of Mechanism~\ref{mech:sum-min-sgsp}, reported dislikes do not affect the locations at which Mechanism~\ref{mech:sum-min-sgsp-square} builds the facilities. Hence Mechanism~\ref{mech:sum-min-sgsp-square} is SGSP. \begin{theorem} \label{thm:sum-min-sgsp-square-sgsp} Mechanism~\ref{mech:sum-min-sgsp-square} is SGSP. \end{theorem} \begin{theorem} \label{thm:sp-sum-min-sgsp-square-opt} Mechanism~\ref{mech:sum-min-sgsp-square} is $2$-efficient. \end{theorem} \begin{proof} We sketch a proof that is similar to our proof of Theorem~\ref{thm:opt-sum-min-sgsp}. Let $I = (n,k,\Location, \Aversion)$ denote the reported $\DOFL$ instance. Let $\textsc{ALG}$ denote the social welfare obtained by Mechanism~\ref{mech:sum-min-sgsp-square} on this instance, and let $\textsc{OPT}$ denote the maximum possible social welfare on this instance. We need to prove that $2\cdot\textsc{ALG}\geq\textsc{OPT}$. Assume without loss of generality that Mechanism~\ref{mech:sum-min-sgsp-square} builds all facilities at $(0, 0)$. (A symmetric argument handles other cases). Using similar arguments, we obtain $\textsc{ALG} \ge \sum_{i\in [n]} \Delta(x_i,(0,0))$. Also, we have $$\sum_{i\in [n]} \Delta(x_i,(0,0)) \ge \max_{p\in \{(0,1), (1,0), (1,1)\}} \sum_{i \in [n]} \Delta(x_i, p),$$ and $$\Delta(x_i, (0,0)) + \Delta(x_i, (0,1)) + \Delta(x_i, (1,0)) + \Delta(x_i, (1,1))\ge 2\sqrt{2}$$ for all agents $i$, implying that $\sum_{i\in [n]} \Delta(x_i, (0,0)) \ge n/\sqrt{2}$. Thus $\textsc{ALG} \ge n/\sqrt{2}$. Since no agent has welfare greater than $\sqrt{2}$, we have $\sqrt{2}n \ge \textsc{OPT}$. Thus, $2 \cdot \textsc{ALG} \ge \sqrt{2}n \ge \textsc{OPT}$, as required. \end{proof} \section{Efficient Mechanisms} \label{sec:sum-min} \subsection{Efficient mechanisms for the unit interval} \label{subsec:sum-min-interval} We now present our efficient mechanism for $\OOFLG$. \begin{mechanism} \label{mech:sum-min} For a given reported $\DOFL$ instance $I = (n,k,\Location, \Aversion)$, output the lexicographically least solution $\mathbf{y}$ in $\{0, 1\}^k$ that maximizes the social welfare $\SSW (I,\mathbf{y})$. \end{mechanism} \begin{theorem} \label{thm:sp-sum-min} Mechanism~\ref{mech:sum-min} is WGSP. \end{theorem} \begin{proof} To establish this theorem, we show that Mechanism~\ref{mech:sum-min} can be equivalently expressed in terms of the approval voting mechanism. Hence Theorem~\ref{thm:wgsp-app-vote} implies the theorem. Let $(I,I')$ denote a $\OOFLG$ instance where $I=(n,k,\Location, \Aversion)$ and $I'=(n,k,\Location,\LieAversion)$. We view each agent $i \in [n]$ as a voter, and each $\mathbf{y}$ in $\{0,1\}^k$ as a candidate. We obtain the top-tier candidates $C_i$ of voter $i$, and their reported top-tier candidates $C'_i$, from $a_i$ and $a'_i$, respectively. Assume without loss of generality that $x_i \le 1/2$ (the other case can be handled similarly). Set $C_i = \{\mathbf{y} = (y_1, \dots, y_k) \in \{0,1\}^k \mid y_j = 1 \text{ for all } F_j \in a_i\}$ and similarly $C'_i = \{\mathbf{y} = (y_1, \dots, y_k) \in \{0,1\}^k \mid y_j = 1 \text{ for all } F_j \in a'_i\}$. Also set $w^+_i = 1-x_i$ and $w_i^- = x_i$. With this notation, it is easy to see that $A(\mathbf{y}) = \SSW (I', \mathbf{y})$, and that choosing the $\mathbf{y}$ with the highest social welfare in Mechanism~\ref{mech:sum-min} is the same as electing the candidate with the highest approval in Mechanism~\ref{mech:weighted-approval-voting}. \end{proof} We show that Mechanism~\ref{mech:sum-min} is efficient for $k = 3$. First, we note a well-known result about the 1-Maxian problem. In this problem, there are $n$ points located at $z_1, \dots, z_n$ in the interval $[a,b]$, and the task is to choose a point in $[a,b]$ such that the sum of the distances from that point to all $z_i$s is maximized. \begin{lemma}[Optimality of the 1-Maxian Problem] \label{lem:1-maxian} Let $[a,b]$ be a real interval, let $z_1, \dots, z_n$ belong to $[a,b]$, and let $f(z)$ denote $\sum_{i\in [n]} |z-z_i|$. Then $\max_{z\in [a,b]} f(z)$ belongs to $\{f(a), f(b)\}$. \end{lemma} Before proving the main theorem, we establish Lemma~\ref{lem:opt-sum-min}, which follows from Lemma~\ref{lem:1-maxian}. \begin{restatable}{lemma}{optsummin} \label{lem:opt-sum-min} Let $I = (n, k, \mathbf{x}, \mathbf{a})$ denote the reported $\DOFL$ instance, let $Y$ denote the set of all $y$ in $[0,1]$ such that it is efficient to build all $k$ facilities at $y$, and assume that $Y$ is non-empty. Then $Y \cap \{0,1\}$ is non-empty. \end{restatable} \begin{proof} Let $U$ denote $\indiff(I)$. When all of the facilities are built at $y$, \begin{equation*} \SSW (I, (y, \dots, y)) = \sum_{i\in [n] \setminus U} |x_i - y| + \sum_{i \in U} w(I, i, y). \end{equation*} Since $Y$ is non-empty, $\max_y \SSW (I, (y, \dots, y)) = \max_\mathbf{y} \SSW(I, \mathbf{y})$. Moreover, since $\sum_{i \in U} w(I, i, y)$ does not depend on $y$, Lemma~\ref{lem:1-maxian} implies that \begin{equation*} \max(\SSW (I, (0, \dots, 0)), \SSW (I, (1, \dots, 1))) = \max_y \SSW (I, (y, \dots, y)). \end{equation*} Thus, if $\SSW (I, (0, \dots, 0)) \ge \SSW (I, (1, \dots, 1))$, it is efficient to build all $k$ facilities at $0$. Otherwise, it is efficient to build all $k$ facilities at $1$. \end{proof} \begin{theorem} \label{thm:opt-sum-min} Mechanism~\ref{mech:sum-min} is efficient for $k=3$. \end{theorem} \newcommand{ y_{1}^*,y_{3}^* }{ y_{1}^*,y_{3}^* } \newcommand{\ensuremath{[\tuple ]}}{\ensuremath{[ y_{1}^*,y_{3}^* ]}} \newcommand{|_{y_1 = y_1^*, y_3 =y_3^*}}{|_{y_1 = y_1^*, y_3 =y_3^*}} \newcommand{|_{y_2 = y_2^*, y_3 =y_2^*}}{|_{y_2 = y_2^*, y_3 =y_2^*}} \newcommand{|_{y_1=0, y_2 = y_3=y}}{|_{y_1=0, y_2 = y_3=y}} \begin{proof} Let $I = (n,k,\Location, \Aversion)$ denote the reported $\DOFL$ instance and let $\mathbf{y}^* = (y_1^*,y_2^*, y_3^*)$ be an efficient solution for $I$ such that $y_1^*\leq y_2^*\leq y_3^*$. Consider fixing variables $y_1$ and $y_3$ in the social welfare function $\SSW(I, \mathbf{y})$. That is, we have \begin{equation*} \SSW(I, \mathbf{y})|_{y_1 = y_1^*, y_3 =y_3^*} = \sum_{i\in [n]} w(I,i, \mathbf{y})|_{y_1 = y_1^*, y_3 =y_3^*}. \end{equation*} For convenience, let $\SSW(y_2)$ denote $\SSW(I,\mathbf{y})|_{y_1 = y_1^*, y_3 =y_3^*} $ and let $w_i(y_2)$ denote $w(I,i, \mathbf{y})|_{y_1 = y_1^*, y_3 =y_3^*}$ for each agent $i$. Claim~1: For each agent $i$, the welfare function $w_i(y_2)$ with $y_2 \in \ensuremath{[\tuple ]}$ satisfies at least one of the following two properties: \begin{enumerate} \item $w_i(y_2) = |y_2-x_i|$; \item $w_i(y_1^*) = w_i(y_3^*) = \max_{y\in \ensuremath{[\tuple ]}} w_i(y)$. \end{enumerate} Proof: Consider an agent $i$. We consider five cases. Case~1: $F_2 \notin a_i$. Since the welfare of agent $i$ is independent of the location of $F_2$, $w_i$ is a constant function. Hence property~2 is satisfied. Case~2: $a_i = \{F_2\}$. By definition, we have $w_i(y_2) = |y_2-x_i|$. Hence property~1 is satisfied. Case~3: $a_i= \{F_1,F_2\}$. By definition, we have $w_i(y_2) = \min(|y_1^*-x_i|,|y_2-x_i|)$. Notice that $w_i(y_1^*) = \min(|y_1^*-x_i|,|y_1^*-x_i|) = |y_1^*-x_i|= \max_{y\in \ensuremath{[\tuple ]}} w_i(y)$. Moreover, $w_i(y_3^*) = \min(|y_1^*-x_i|,|y_3^*-x_i|)$. We consider two cases. Case~3.1: $|y_1^*-x_i| > |y_3^*-x_i|$. Then $w_i(y_3^*)= |y_3^*-x_i|$ and hence $w_i(y_2) = |y_2- x_i|$ for all $y_2$ in $\ensuremath{[\tuple ]}$, that is, $w_i(y_2)$ satisfies property~1. Case~3.2: $|y_1^*-x_i|\le |y_3^*-x_i|$. Then $w_i(y_3^*)= |y_1^*-x_i|=\max_{y\in \ensuremath{[\tuple ]}} w_i(y) = w_i(y_1^*)$ and hence $w_i(y_2)$ satisfies property~2. Case~4: $a_i= \{F_2,F_3\}$. This case is symmetric to Case~3 and can be handled similarly. Case~5: $a_i= \{F_1,F_2,F_3\}$. By definition, we have $w_i(y_2) = \min(|y_1^*-x_i|,|y_2-x_i|,|y_3^*-x_i|)$. Notice that $w_i(y_1^*) = w_i(y_3^*) = \min(|y_1^*-x_i|,|y_3^*-x_i|)$. Also notice that for any $y_2$ in $\ensuremath{[\tuple ]}$, $w_i(y_2) = \min(|y_1^*-x_i|,|y_2-x_i|,|y_3^*-x_i|) \le \min(|y_1^*-x_i|,|y_3^*-x_i|) = w_i(y_1^*)$. Hence property~1 holds. This concludes our proof of Claim~1. Claim~2: There is a solution that optimizes $\max_\mathbf{y} \SSW(I, \mathbf{y})$ and builds facilities in at most two locations. Proof: We establish the claim by proving that either $\SSW(I,(y_1^*,y_{1}^*, y_{3}^*)) \ge \SSW(I,\mathbf{y}^*) $ or $\SSW(I, (y_1^*,y_{3}^*, y_{3}^*)) \ge \SSW(I, \mathbf{y}^*)$. Claim~1 implies that the set of agents $[n]$ can be partitioned into two sets $(S,\overline{S})$ such that $w_i(y_2)$ satisfies property~1 for all $i$ in $S$, and $w_i(y_2)$ satisfies property~2 for all $i$ in $\overline S$. Thus, we have $\SSW(y_2) = \sum_{i\in [n]} w_i(y_2) = \sum_{i\in S} w_i(y_2) + \sum_{i\in \overline S} w_i(y_2)$. By Lemma~\ref{lem:1-maxian}, there is a $b$ in $\{ y_{1}^*,y_{3}^* \}$ such that $\sum_{i\in S} w_i(b)\ge \sum_{i\in S} w_i(y_2)$ for all $y_2$ in \ensuremath{[\tuple ]}. For any $i$ in $\overline{S}$, we deduce from property~2 that $w_i(b)\ge w_i(y_2)$ for all $y_2$ in \ensuremath{[\tuple ]}. Therefore, $\SSW(b)\ge \SSW(y_2)$ for all $y_2$ in $\ensuremath{[\tuple ]}$. This completes our proof of Claim~2. Having established Claim~2, we can assume without loss of generality that $y_2^*=y_3^*$. A similar argument as above can be used to prove that either $(0, y_2^*,y_2^*)$ or $(y_2^*, y_2^*,y_2^*)$ is an efficient solution. Now if $(0, y_2^*,y_2^*)$ is efficient, then one can use a similar argument to prove that either $(0,0,0)$ or $(0,1,1)$ is efficient. And if $(y_2^*, y_2^*,y_2^*)$ is efficient, then by applying Lemma~\ref{lem:opt-sum-min} with $k=3$, we deduce that either $(0,0,0)$ or $(1,1,1)$ is efficient. Thus, there is a $0$-$1$ efficient solution. The efficiency of Mechanism~\ref{mech:sum-min} follows. \end{proof} When $k=2$ (resp., $1$), we can add one (resp., two) dummy facilities and use Theorem~\ref{thm:opt-sum-min} to establish that Mechanism~\ref{mech:sum-min} is efficient for $k = 2$ (resp., $1$). Theorem~\ref{thm:sum-min-sgsp-lower-bound} below provides a lower bound on the approximation ratio of any SGSP efficient mechanism; this result implies that Mechanism~\ref{mech:sum-min} is not SGSP. \begin{restatable}{theorem}{summinsgsplowerbound} \label{thm:sum-min-sgsp-lower-bound} There is no SGSP $\alpha$-efficient $\OOFLG$ mechanism with $\alpha<5/4$. \end{restatable} \begin{proof} Let $n$ be a large even integer. We construct two $\left(\frac{3n}{2} + 1\right)$-agent single-facility $\OOFLG$ instances $(I,I)$ and $(I,I')$. In both $(I,I)$ and $(I,I')$, agent $1$ is located at $0$ and dislikes $\{F_1\}$, $n/2$ agents are located at $1$ and dislike $\{F_1\}$, and the remaining $n$ agents, which we denote by the set $U$, are located at $0$ and dislike $\emptyset$. In $I$, all agents report truthfully, while in $I'$, all agents in $U$ report $\{F_1\}$ and the remaining agents report truthfully. Let the maximum social welfare for instances $I$ and $I'$ be $\textsc{OPT}$ and $\textsc{OPT}'$, respectively. It is easy to see that $\textsc{OPT} = 3n/2$ and $\textsc{OPT}' = n+1$ (obtained by building $F_1$ at $0$ and $1$, respectively). Let the social welfare achieved by some SGSP $\OOFLG$ mechanism $M$ on these instances be $\textsc{ALG}$ and $\textsc{ALG}'$, respectively. Let $M$ build $F_1$ at $y$ on $I$. It follows that $\textsc{ALG} = y + \frac{3n}{2} - \frac{ny}{2}$. If the agents in $U$ and agent $1$ form a coalition in $I$ and the agents in $U$ report $\{F_1\}$, then the instance becomes $I'$. Thus, as $M$ is SGSP, $M$ cannot build $F_1$ to the right of $y$ in $I'$. Using this fact, it is easy to see that $\textsc{ALG}' \le (n+1)y + \frac{n}{2}(1-y) = \frac{ny}{2} + \frac{n}{2} + y$. Using $\textsc{OPT} = \frac{3n}{2}$ and $\textsc{ALG} = y + \frac{3n}{2} - \frac{ny}{2}$, we obtain \begin{equation} \label{eqn:alpha-bound-one} \alpha \ge \frac{\frac{3n}{2}}{y + \frac{3n}{2} - \frac{ny}{2}}. \end{equation} Similarly, using $\textsc{OPT}' = n + 1$ and $\textsc{ALG}' \le \frac{ny}{2} + \frac{n}{2} + y$, we obtain \begin{equation} \label{eqn:alpha-bound-two} \alpha \ge \frac{n + 1}{\frac{ny}{2} + \frac{n}{2} + y}. \end{equation} Let $f(y)$ denote \begin{equation*} \max\left( \frac{\frac{3n}{2}}{y + \frac{3n}{2} - \frac{ny}{2}}, \frac{n + 1}{\frac{ny}{2} + \frac{n}{2} + y} \right). \end{equation*} From \eqref{eqn:alpha-bound-one} and \eqref{eqn:alpha-bound-two} we deduce that $\alpha \ge f(y)$. Let $y^*$ denote a value of $y$ in $[0,1]$ minimizing $f(y)$. It is easy to verify that $y^*$ satisfies $f(y^*) = \frac{5n^2 + 4n - 4}{4n(n+1)}$. Thus, $\alpha \ge f(y^*)$. As $n$ approaches infinity, $f(y^*)$ approaches $5/4$. Thus, for any SGSP $\alpha$-efficient mechanism, we have $\alpha \ge 5/4$. \qed \end{proof} In view of Theorem~\ref{thm:sum-min-sgsp-lower-bound}, it is natural to try to determine the minimum value of $\alpha$ for which an SGSP $\alpha$-efficient $\OOFLG$ mechanism exists. Below we present a $2$-efficient SGSP mechanism. It remains an interesting open problem to improve the approximation ratio of $2$, or to establish a tighter lower bound for the approximation ratio. \begin{mechanism} \label{mech:sum-min-sgsp} Let $(n,k,\Location, \Aversion)$ denote the reported $\DOFL$ instance. Build all facilities at $0$ if $\sum_{i\in [n]} x_i \ge \sum_{i \in [n]} (1-x_i)$; otherwise, build all facilities at $1$. \end{mechanism} \begin{theorem} \label{thm:sp-sum-min-sgsp} Mechanism~\ref{mech:sum-min-sgsp} is SGSP. \end{theorem} \begin{proof} Reported dislikes do not affect the locations at which the facilities are built. Hence the theorem follows. \end{proof} \begin{restatable}{theorem}{optsumminsgsp} \label{thm:opt-sum-min-sgsp} Mechanism~\ref{mech:sum-min-sgsp} is 2-efficient. \end{restatable} \begin{proof} Let $I = (n,k,\Location, \Aversion)$ denote the reported $\DOFL$ instance. Let $\textsc{ALG}$ denote the social welfare obtained by Mechanism~\ref{mech:sum-min-sgsp} on this instance, and let $\textsc{OPT}$ denote the maximum possible social welfare on this instance. We need to prove that $2\cdot\textsc{ALG}\geq\textsc{OPT}$. Assume without loss of generality that Mechanism~\ref{mech:sum-min-sgsp} builds all facilities at $0$. (A symmetric argument handles the case where all facilities are built at $1$). Then the welfare of an agent $i$ not in $\indiff(I)$ is $x_i$ and the welfare of an agent $i'$ in $\indiff(I)$ is $\max(x_{i'}, 1-x_{i'}) \ge x_{i'}$. Thus, $\textsc{ALG} \ge \sum_{i\in [n]} x_i$. As Mechanism~\ref{mech:sum-min-sgsp} builds the facilities at $0$ and not $1$, we have $\sum_{i\in [n]} x_i \ge \sum_{i \in [n]} (1-x_i)$, which implies that $\sum_{i\in [n]} x_i \ge n/2$. Combining the above two inequalities, we have $\textsc{ALG} \ge n/2$. Since no agent has welfare greater than $1$, we have $n \ge \textsc{OPT}$. Thus, $2 \cdot \textsc{ALG} \ge n \ge \textsc{OPT}$, as required. \end{proof} We now establish that the analysis of Theorem~\ref{thm:opt-sum-min-sgsp} is tight by exhibiting a two-facility $\DOFL$ instance on which Mechanism~\ref{mech:sum-min-sgsp} achieves half of the optimal social welfare. For the reported $\DOFL$ instance $I = (2, 2, (0, 1), (\{F_1\}, \{F_2\}))$, it is easy to verify that the optimal social welfare is $\SSW(I, (1,0)) = 2$, while the social welfare obtained by Mechanism~\ref{mech:sum-min-sgsp} is $\SSW (I, (0,0))=1$. \section{Weighted Approval Voting} \label{sec:weight-app-vote} Before studying efficient mechanisms for our problem, we review a variant of the approval voting mechanism \cite{BRAMS1978}. An instance of Dichotomous Voting (DV) is a tuple $(m, n, \mathbf{C}, \mathbf{w}^+, \mathbf{w}^-)$ where $m$ voters $1, \dots, m$ have to elect a candidate among the set of candidates $C = \{c_1, \dots, c_n\}$. Each voter $i$ has dichotomous preferences, that is, voter $i$ partitions all of the candidates into two equivalence classes: a top (most preferred) tier $C_i$ and a bottom tier $\overline{C_i} = C \setminus C_i$. Each voter $i$ has associated (and publicly known) weights $w_i^+ \ge w_i^- \ge 0$. The symbols $\mathbf{C}$, $\mathbf{w}^+$, and $\mathbf{w}^-$ denote length-$m$ vectors with $i$th element $C_i$, $w^+_i$, and $w^-_i$, respectively. We now present our weighted approval voting mechanism.\footnote{Our mechanism differs from the homonymous mechanism of Massó et al., which has weights for the candidates instead of the voters \cite{MASSO2008}.} \begin{mechanism} \label{mech:weighted-approval-voting} Given a $\DV$ instance $(m, n,\mathbf{C}, \mathbf{w}^+, \mathbf{w}^-)$, every voter $i$ votes by partitioning $C$ into $C'_i$ and $\overline{C'_i}$. Let the weight function $w$ be such that for voter $i$ and candidate $c_j$, $w(i, j) = w_i^+$ if $c_j$ is in $C'_i$ and $w(i, j) = w_i^-$ otherwise. For any $j$ in $[n]$, we define $A(j) = \sum_{i \in [m]} w(i, j)$ as the approval of candidate $c_j$. The candidate $c_j$ with highest approval $A(j)$ is declared the winner. Ties are broken according to a fixed ordering of the candidates (e.g., in favor of lower indices). \end{mechanism} We note that the approval voting mechanism can be obtained from the weighted approval voting mechanism by setting weights $w_i^+$ to $1$ and $w_i^-$ to $0$ for all voters $i$. In Section~\ref{sec:preliminaries}, we defined SP, WGSP, and SGSP in the $\OOFLG$ setting. These definitions are easily generalized to the voting setting. Brams and Fishburn proved that the approval voting mechanism is SP~\cite{BRAMS1978}. Below we prove that our weighted approval voting mechanism is WGSP (and hence also SP). \begin{restatable}{theorem}{wgspappvote} \label{thm:wgsp-app-vote} Mechanism~\ref{mech:weighted-approval-voting} is WGSP. \end{restatable} \begin{proof} Assume for the sake of contradiction that there is an instance in which a coalition of voters $U$ with true preferences $\{(C_i,\overline{C_i})\}_{i\in U}$ all benefit by misreporting their preferences as $\{(C'_i,\overline{C'_i})\}_{i\in U}$. For any candidate $c_j$, let $A(j)$ denote the approval of $c_j$ when coalition $U$ reports truthfully, and let $A'(j)$ denote the approval of $c_j$ when coalition $U$ misreports. Let $c_k$ be the winning candidate when coalition $U$ reports truthfully, and let $c_\ell$ be the winning candidate when coalition $U$ misreports. Since every voter in $U$ benefits when the coalition misreports, we know that $c_k$ belongs to $\bigcap_{i\in U}\overline{C_i}$ and $c_\ell$ belongs to $\bigcap_{i\in U}C_i$. Since $c_k$ belongs to $\bigcap_{i\in U}\overline{C_i}$, we deduce that $A'(k)=A(k)+\sum_{i\in U:c_k\in C'_i}w_i^+-w_i^-$ and hence $A'(k)\geq A(k)$. Similarly, since $c_\ell$ belongs to $\bigcap_{i\in U}C_i$, we deduce that $A'(\ell)=A(\ell)+\sum_{i\in U:c_\ell\in\overline{C'_i}}w_i^--w_i^+$ and hence $A(\ell)\geq A(\ell')$. Since $c_k$ wins when coalition $U$ truthfully, one of the following two cases is applicable. Case~1: $A(k)>A(\ell)$. Since $A'(k)\geq A(k)$ and $A(\ell)\geq A'(\ell)$, the case condition implies that $A'(k)>A'(\ell)$. Hence $c_\ell$ does not win when coalition $U$ misreports, a contradiction. Case~2: $A(k)=A(\ell)$ and $c_k$ has higher priority than $c_\ell$. Since $A'(k)\geq A(k)$ and $A(\ell)\geq A(\ell')$, the case condition implies that $A'(k)\geq A(\ell')$ and $c_k$ has higher priority than $c_\ell$. Hence $c_\ell$ does not win when coalition $U$ misreports, a contradiction. \end{proof} \begin{theorem} Mechanism~\ref{mech:weighted-approval-voting} is not SGSP. \end{theorem} The above theorem can be established by adapting the instance shown in Section~\ref{sec:sum-min} to prove that Mechanism~\ref{mech:sum-min} is not SGSP.
{'timestamp': '2021-09-14T02:18:04', 'yymm': '2109', 'arxiv_id': '2109.05396', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05396'}
arxiv
\section{Introduction}\label{sec:introduction} Deep neural networks (DNNs) have advanced many tasks of artificial intelligence. Traditional DNNs are designed with a fixed network structure, where the hardware resources, such as computation ability and memory footprint, have to be allocated in advance to enable the running of DNNs. Unfortunately, the equipped resources are greatly different among heterogeneous devices. Even for the same device, the availability of hardware resources varies over time. These limitations considerably barricade DNNs to be deployed. Though many works obtain a compact network via model compression~\cite{ruan2021dpfps,wang2020pruning,liu2019metapruning}, network architecture search (NAS)~\cite{cai2019once,dai2019chamnet}, \emph{etc.}, the resulting model structures are still fixed, making it hard to make full use of hardware resources. \begin{figure}[!t] \centering \includegraphics[width=0.99\columnwidth]{figs/moti.pdf} \caption{\textbf{Left}: Performance of SlimmableNetwork~\cite{yu2018slimmable} with uniform width and non-uniform width~\cite{liu2019metapruning}. \textbf{Right}: Performance of MutualNet~\cite{yang2020mutualnet} with fixed and reduced search spaces.} \label{fig:moti} \vspace{-1.5em} \end{figure} By adjusting the runtime subnets to fit the dynamically available resources, designing resource-adaptive supernets has attracted increasing attention from the research community. According to the subnet sampling strategy during supernet training, traditional resource-adaptive supernets can be generally divided into two groups including uniform subnet sampling and random subnet sampling. For uniform subnet sampling, some fixed multipliers are applied to all layers to scale the network width, thus enabling to switch subnets with different uniform widths at runtime~\cite{yu2018slimmable, yu2019universally}. In addition to uniform width,~\cite{yang2020mutualnet} further considered the resolution of input images to enhance subnet performance. As for random subnet sampling, these methods~\cite{cai2019once, lou2021dynamic, yu2020bignas, wang2021attentivenas} randomly sample subnets from a supernet for training in each iteration, and then search for optimal subnets of different sizes from the pre-trained supernet using heuristics algorithms. The learning is also known as one-shot NAS. Nevertheless, the performance is still far from satisfactory for real-world applications. We attribute it to three open issues, \emph{i.e.}, \textit{homogeneity of subnets}, \textit{search overhead}, and \textit{subnet mismatch}. In terms of homogeneity of subnets, uniform subnet sampling \cite{yu2018slimmable, yu2019universally, yang2020mutualnet} simply enforces shared multipliers to all layers without investigating the diversity of layer-wise width. Consequently, only one subnet structure can be made given a particular resource constraint such as FLOPs, latency, \emph{etc}. As previously studied in network pruning~\cite{yu2019autoslim, lin2020channel, liu2019metapruning} and NAS~\cite{guo2020single, cai2019once}, the optimal subnet at a particular size often results from the non-uniform sampling. To verify this, we perform a validation experiment on ImageNet by replacing the uniform width of MobileNetV1~\cite{yu2018slimmable} with a non-uniform form from~\cite{liu2019metapruning}. Fig.~\ref{fig:moti}(\textbf{Left}) shows a better trade-off between accuracy and FLOPs from the non-uniform strategy. Thus, the homogeneity of subnets, if not well addressed, often results in suboptimal performance. In terms of search overhead, though random subnet sampling may produce different subnet structures over supernet training with respect to a particular resource, which partially alleviates the homogeneity of subnets, additional overheads are required to search for the optimal subnet of a particular size for inference. As reported by~\cite{cai2019once}, it takes around 40 GPU hours to find out each target subnet in the trained supernet. Though this additional cost is acceptable in offline environment, it greatly prevents resource-adaptive supernet from real-time running environment where the available hardware resources frequently vary a lot due to the concurrently running applications. Subnet mismatch refers to that the sampled subnets during training deviate considerably from the target subnets in inference~\cite{yang2020mutualnet,cai2019once,lou2021dynamic}. For example,~\cite{yang2020mutualnet} observed that only around 30\% of sampled subnets fall into the trade-off curve of accuracy \emph{v.s.} FLOPs. This indicates that a large amount of computation is wasted on training these low-quality subnets that would not be considered in inference. Besides, without sufficient training, these high-quality subnets may result in suboptimal performance in the real-world applications as shown in Fig.\,\ref{fig:moti}(\textbf{Right}). Thus, it is necessary to gradually reduce the subnet structure space during the network training, so as to concentrate more on these high-quality subnets, which is also discussed by~\cite{sahni2021compofa}. Overall, challenges still remain in training a resource-adaptive supernet. On one hand, we pursue high-performing DNNs for practical deployment. On the other hand, the deployed model should be switchable instantly if the available hardware resources are changed. Reflecting upon the subnet mismatch problem mentioned above, we can know that uniform subnet sampling and random subnet sampling fail to accurately model subnets towards the available resources. Therefore, a tedious search process has to be executed to find out the target subnet each time the available resources vary. \begin{figure}[t] \centering \includegraphics[width=0.91\columnwidth]{figs/framework.pdf} \vspace{-0.5em} \caption{PSS-Net training framework. (a) Initializing the subnet structure space $\mathcal{S}$. (b) Setting up a set of subnet pools $\Theta = \{\pi^1, \pi^2, ..., \pi^T\}$. (c) Given a resource constraint $\theta^t$, sampling a medium-sized subnet structure $\phi^t$ either from the subnet structure space $\mathcal{S}$, or from the corresponding subnet pool $\pi^t$. (d) Slimmable training for $\mathcal{N}_{\phi^{max}}, \mathcal{N}_{\phi^{t}}, \mathcal{N}_{\phi^{min}}$. } \label{fig:framework} \vspace{-1.0em} \end{figure} To solve the aforementioned problems, in this paper, we propose prioritized subnet sampling to train a resource-adaptive supernet, termed PSS-Net, as illustrated in Fig.\,\ref{fig:framework}. We first build a subnet structure space by applying varying multipliers to different layers, which eliminates the homogeneity of subnets resulting from uniform subnet sampling. Then, we set up a group of subnet pools, each of which stores the information of these high-quality subnets conditioned on the same resource constraint. In the early training batches of our PSS-Net, we sample a medium-sized subnet from a pre-built subnet structure space according to the structure distribution~\cite{wang2021attentivenas}. To measure the quality of a sampled subnet, we consider its batch loss as the performance metric, alternative to validation accuracy which requires a computationally heavy subnet training. We update the performance metric using moving average if the same subnet structure is sampled multiple times. For each high-quality subnet, its information is inserted into the corresponding subnet pool. When the subnet pool is full, subnet sampling will gradually shift from the subnet structure space to each subnet pool to ensure that high-quality subnets are entitled with sufficient training, which solves the problem of subnet mismatch. Moreover, when sampling is from a subnet pool, the one with a better performance metric than other high-quality subnets is given with higher priority to being sampled to train PSS-Net. At the end of PSS-Net training, we only need to preserve the best subnet in each pool. Consequently, PSS-Net results in a set of subnets that can be alternatively deployed to adapt to the currently available resources, without additional overhead for subnet search. We use the challenging MobileNetV1~\cite{howard2017mobilenets} and MobileNetV2~\cite{sandler2018mobilenetv2} as our supernets, and the experiments are conducted on ImageNet. The results show that our PSS-Net significantly outperforms the state-of-the-arts under different resource constraints including FLOPs, CPU latency and GPU latency. \section{Related Work} We briefly discuss the major topics that are most related to resource-adaptive supernets. \textbf{Compact Networks}. To overcome the hurdle of deploying models on resource-limited devices, many previous works focus on obtaining compact networks, typically through model compression \cite{guo2020channel,ruan2021dpfps,wang2020pruning,li2020eagleeye,liu2019metapruning}, network architecture search (NAS) \cite{wang2021attentivenas,cai2019once,he2018amc}, \emph{etc}. Network pruning, a form of model compression, removes redundant weights/filters to satisfy resource constraints in general hardware. \cite{han2015learning} proposed to recursively remove small-magnitude weights and retrain the $\ell_2$-regularized subnetwork to recover accuracy. \cite{lin2020hrank} discarded filters with low-rank feature map outputs. The lottery ticket hypothesis~\cite{frankle2018lottery} randomly initializes a dense network and trains it from scratch. The subnets with high-weight values are extracted, and retrained with the initial weight values of the original dense model. \cite{guo2020multi} also considered multi-dimension pruning including output channels, model depth, input resolution, \emph{etc}. Different from model compression operating upon an existing backbone network, NAS~\cite{zoph2017neural, wang2021attentivenas, cai2019once, yu2020bignas} conducts search on a space of network structures including operations, width, depth, \emph{etc.}, to obtain a compact model. The broader search space brings about better performance as reported in existing studies. \textbf{Sample-Adaptive Networks}. A sample-adaptive network adapts its structure according to the input image samples. \cite{lin2017runtime} modeled the adaption of network width as a Markov decision process, and measured the convolutional kernel importance conditioned on different samples. \cite{bejnordi2019batch} adjusted the network width via a gating module conditioned on the current input. To this end, a ``batch-shaping'' is introduced to match the marginal aggregated posterior distribution over any intermediate features to a pre-specified prior distribution. Except for adjusting network width, another group realizes sample-adaptive network from the perspective of depth adaption. For instance, \cite{huang2017multi} proposed to early exist from the inference at shallow layers of the network through training multiple classifiers upon intermediate features. SkipNet~\cite{wang2018skipnet} skips convolutional blocks via a gating network that maps the last-layer outputs to a binary decision to execute or bypass the current layer. Traditional compact networks are fixed for deployment. A sample-adaptive network allocates more computational resources to complex images, and fewer to images that are easier for the task. As a core distinction, our PSS-Net produces multiple subnets and switches these subnets for deployment according to available hardware resources. \section{Methodology} \subsection{Preliminary} Our PSS-Net is an $L$-layers supernet $\mathcal{N}_{\phi^{max}, \mathbf{W}}$ with structure $\phi^{max}=(\{{o_i^{max}\}_{i=1}^{L}, r^{max}})$ and weights $\mathbf{W}=\{\mathbf{W}_i\}_{i=1}^L$, where $o_i^{max}$, $r^{max}$ and $\mathbf{W}_i$ are the number of output channels in the $i$-th layer, the supernet input resolution, and the weights of the $i$-th layer, respectively. The supernet $\mathcal{N}_{\phi^{max}, \mathbf{W}}$ contains subnets of multiple sizes, and each subnet $\mathcal{N}_{\phi^t, \mathbf{W}^t}$ is allowed to use a different subnet structure $\phi^{t}=(\{{o_i^{t}\}_{i=1}^{L}, r^{t}})$ and subnet weights ${\mathbf{W}^t}=\{\mathbf{W}_i[1:o_i^{t}]\}_{i=1}^L$, similarly, where $o_i^{t}$ and $r^{t}$ are the number of output channels in the $i$-th layer and the subnet input resolution, respectively. $\mathbf{W}_i[1:o_i^{t}]$ means the subnet weights of the $i$-th layer are the weights of the first $o_i^t$ channels in $\mathbf{W}_i$. Therefore, any two subnets share partial weights. Then we set separate lower bounds for each layer of the subnet structure $\{{o_i^{t}\}_{i=1}^{L}}$ and $r^{t}$ as $\{{o_i^{min}\}_{i=1}^{L}}$ and $r^{min}$, \emph{i.e.}, the structure of the smallest subnet can be represented as $\phi^{min}=(\{{o_i^{min}\}_{i=1}^{L}}, r^{min})$. Finally, we can represent the subnet structure space as $\mathcal{S}=\{\phi^1=(\{o_i^1\}_{i=1}^L, r^1), \phi^2=(\{o_i^2\}_{i=1}^L, r^2), ...\}$, where $o_i^{min} \leq o_i^t \leq o_i^{max}$, $r^{min} \leq r^t \leq r^{max}$. In practice, for any subnet $\mathcal{N}_{\phi^t,\mathbf{W}^t}$, where the structure $\phi^t= \{ \{o^t_i \}_{i=1}^L, r^t \} \in \mathcal{S}$, we sample $o^t_i$ from $\{o^{min}_i,~o^{min}_i+1,~o^{min}_i+2,~...,~o^{max}_i\}$ and then round to its nearest multiple of $8$ to obtain a hardware friendly channel number, and $r^t$ is sample from $\{r^{min},~r^{min}+8,~r^{min}+16,~...,~r^{max}\}$. Given a set of resource constraints $\Theta = \{\theta^t\}_{t=1}^T$, our goal is to train $\mathcal{N}_{\phi^{max}, \mathbf{W}}$ such that $T$ subnets $\{ \mathcal{N}_{\phi^t, \mathbf{W}^t} | \phi^t \in \mathcal{S}, \mathbf{W}^t \in \mathbf{W}\}_{t=1}^T$ conditioned on $\Theta$ can be obtained from this supernet. We define this problem as: \begin{equation}\label{eq:definition} \begin{split} \{ (\phi^t)_{best} &\}_{t=1}^T, \{(\mathbf{W}^t)_{best}\}_{t=1}^T \\& = \underset{\{ \phi^t \}_{t=1}^T, \{\mathbf{W}^t\}_{t=1}^T}{\arg\max}\sum_{t=1}^T Acc(\mathcal{N}_{\phi^t, \mathbf{W}^t}), \\ \text{s.t.} \quad \phi^t \in & \mathcal{S}, \theta^t \in \Theta, \mathcal{C}(\mathcal{N}_{\phi^t, \mathbf{W}^t}) \in [\theta^t - \delta, \theta^t + \delta], \end{split} \end{equation} where $\mathcal{C}(\mathcal{N}_{\phi^t, \mathbf{W}^t})$ is a function to calculate the resource consumption of subnet $\mathcal{N}_{\phi^t, \mathbf{W}^t}$, $\delta$ is a bias tolerance between actual resource consumption and the given resource constraint $\theta^t$, and $Acc(\mathcal{N}_{\phi^t, \mathbf{W}^t})$ returns the accuracy of $\mathcal{N}_{\phi^t, \mathbf{W}^t}$ on the validation set. Note that, each subnet weights are a subset of the supernet weights, \emph{i.e.}, $\mathbf{W}^t \in \mathbf{W}$. Thus, to update $\mathbf{W}^t$ is to update $\mathbf{W}$ in essence. For simplicity, we remove the superscript ``$t$'' in $\mathbf{W}^t$ and Eq.\,(\ref{eq:definition}) can be simplified as: \begin{equation}\label{eq:sim_definition} \begin{split} &\{ (\phi^t)_{best} \}_{t=1}^T, (\mathbf{W})_{best} = \underset{\{ \phi^t \}_{t=1}^T, \mathbf{W}}{\arg\max}\sum_{t=1}^T Acc(\mathcal{N}_{\phi^t, \mathbf{W}}), \\ & \text{s.t.} \quad \phi^t \in \mathcal{S}, \theta^t \in \Theta,\ \mathcal{C}(\mathcal{N}_{\phi^t, \mathbf{W}}) \in [\theta^t - \delta, \theta^t + \delta]. \end{split} \end{equation} \begin{algorithm}[!t] \caption{PSS-Net Training} \label{alg:PSS-Net} \textbf{Input}: Supernet weight $\mathbf{W}$, supernet structure $\phi^{max}$, minimal subnet structure $\phi^{min}$, resource constraints $\Theta=\{ \theta^t \}_{t=1}^T$, subnet structure space $\mathcal{S}$.\\ \textbf{Output}: best subnet structures $\{ (\phi^t)_{best}\}_{t=1}^T$, Trained supernet weights $(\mathbf{W})_{best}$. \begin{algorithmic}[1] \STATE Initialize subnet pools set: $\Pi=\{\pi^t=\{\}\}_{t=1}^T$. {\scriptsize \# $e$: training epoch number, $b$: training batch number.} \FOR{$e = 1, ..., E$} \FOR{$b=1, ..., B$} \STATE $subnet\_list$ = $\{\phi^{max}\}$; \STATE Randomly sample $t$ from $\{1,2, ..., T\}$; \STATE $\phi^t, \pi^t$ = Alg.~\ref{alg:sampling}($\theta^t, \pi^t, \mathcal{S}, e, E$); \STATE $subnet\_list$ = $subnet\_list$ $\cup\ \{\phi^t, \phi^{min}\}$; \STATE $\mathbf{W}$ = slimmable\_training($\mathbf{W}$, $subnet\_list$); \\{\scriptsize \# Details of slimmable\_training can be found in the appendix.} \ENDFOR \ENDFOR \FOR{$t$ in $1,...,T$} \FOR{$j$ in $1,...,M$} \STATE Calibrate BN statistics of subnet $\mathcal{N}_{\phi^t_j, \mathbf{W}}$; \STATE Compute $Acc(\mathcal{N}_{\phi^t_j, \mathbf{W}})$ on the validation set; \ENDFOR \STATE $(\phi^t)_{best}, (\mathbf{W})_{best} = \underset{(\phi^t)_j, \mathbf{W}}{\arg\max}Acc(\mathcal{N}_{(\phi^t)_j, \mathbf{W}})$. \ENDFOR \STATE \textbf{return} $\{ (\phi^t)_{best}\}_{t=1}^T, (\mathbf{W})_{best}$. \end{algorithmic} \end{algorithm} To train each subnet $\mathcal{N}_{\phi^t, \mathbf{W}}$ in Eq.\,(\ref{eq:definition}), \cite{yu2019universally} proposed a three-step slimmable training paradigm: The ``sandwich rule'' is firstly adopted to select three subnet types of one maximal size (\emph{i.e.}, the supernet, $\mathcal{N}_{\phi^{max}, \mathbf{W}}$), several medium sizes and one minimal size (\emph{i.e.}, the minimal subnet $\mathcal{N}_{\phi^{min}, \mathbf{W}}$). Then, the inplace distillation is conducted between the supernet and other subnets. Finally, the parameters in the batch normalization layers of the subnets are recalibrated after training. This paradigm has inspired many subsequent researches to train resource-adaptive supernets or compact networks~\cite{yang2020mutualnet,cai2019once, lou2021dynamic, yu2020bignas, wang2021attentivenas}. The main difference between these approaches lies in the selection of the medium-sized subnets in the ``sandwich rule'' step. Traditional approaches~\cite{yu2019universally, yang2020mutualnet} obtain a medium-sized subnet using uniform subnet sampling, \emph{i.e.}, applying a fixed width multiplier to all layers in each batch training. However, such a manner causes suboptimal performance due to the homogeneity of subnets. The one-shot NAS~\cite{lou2021dynamic, yu2020bignas, wang2021attentivenas} randomly samples medium-sized subnets from the pre-defined subnet structure space $\mathcal{S}$ to train the supernet. However, heavy cost is inevitable to search for the target subnet each time the available hardware resources change. \subsection{PSS-Net Training}\label{sec:PSS-Net} To solve the above problems, we propose prioritized subnet sampling to sample the medium-sized subnet for training our supernet, termed PSS-Net in this paper. Our PSS-Net training generally follows the three-step slimmable training paradigm as shown in Fig.\,\ref{fig:framework}. We first outline our PSS-Net training in Alg.~\ref{alg:PSS-Net}, which is then detailed below. \subsubsection{Subnet Pools (Line 1, Alg.~\ref{alg:PSS-Net}).} Different from traditional slimmable training paradigm, our PSS-Net training maintains a set of subnet pools, denoted as $\Pi=\{\pi^t=\{\}\}_{t=1}^T$. The $t$-th subnet pool $\pi^t$ is used to collect the information of $M$ high-quality subnets conditioned on the resource constraint $\theta^t$ in Eq.\,(\ref{eq:sim_definition}). The information of each subnet includes its network structure $\phi^t$ and performance metric $m^t$, which will be detailed in the next section. \subsubsection{Slimmable Training (Line 2 -- Line 10, Alg.~\ref{alg:PSS-Net}).} In each training batch, we select three subnet types of one maximal size (\emph{i.e.}, the supernet, $\mathcal{N}_{\phi^{max}, \mathbf{W}}$), one medium size and one minimal size (\emph{i.e.}, the minimal subnet $\mathcal{N}_{\phi^{min}, \mathbf{W}}$). The ``slimmable\_training'' in Line 8 of Alg.~\ref{alg:PSS-Net} is the same as Line 3 -- Line 16 of Alg.1 in USNet~\cite{yu2019universally} and is elaborated in the appendix. To obtain a medium-sized subnet $\phi^t$, USNet applies a fixed width multiplier to uniformly reduce the width of the supernet, whereas with the aid of the introduced subnet pools, our PSS-Net gives priority to high-quality subnets, as outlined in Alg.~\ref{alg:sampling} and detailed in the next section. \subsubsection{BN Calibration (Line 11 -- Line 17, Alg.~\ref{alg:PSS-Net}).} After the slimmable training, each subnet pool $\pi^t \in \Pi$ will be filled with these high-quality subnets conditioned on its corresponding resource constraint $\theta^t$. However, the statistics in the batch normalization (BN) layers of these high-quality subnets are not accurately estimated since the forward propagated subnets vary during training our PSS-Net. As a consequence, BN calibration is indispensable in order to evaluate the performance of each subnet. To this end, following~\cite{yu2019universally,yang2020mutualnet}, we feed each subnet with a small training set of $8,192$ images in this paper to update the BN statistics of each subnet in $\pi^t$. Then, the calibrated subnet with the best accuracy is regarded as the optimal subnet $\mathcal{N}_{(\phi^t)_{best},(\mathbf{W})_{best}}$ under the resource constraint of $\theta^t$. At the end of training, the subnet pool has collected a sufficient number of high-quality subnet structures for each resource constraint and the corresponding performance metrics detailed in the next section. Thus, we only need to calibrate $k$ subnets within top-$k$ performance metrics, and then pick the one with the best accuracy. \begin{algorithm}[!t] \caption{Prioritized Subnet Sampling} \label{alg:sampling} \textbf{Input}: Subnet pool $\pi^t$ conditioned on resource constraint $\theta^t$, subnet structure space $\mathcal{S}$, current epoch $e$, and total epochs $E$. \\ \textbf{Output}: Subnet structure $\phi^t$, and subnet pool $\pi^t$ \begin{algorithmic}[1] \STATE $p = {p_{end}}^{\mathcal{I}(|\pi^t|< M)\cdot(e - 1)/E}$; \IF{$rand(0, 1)<p$} \STATE Sample a subnet structure $\phi^t \in \mathcal{S}$, s.t.$\ \mathcal{C}(\mathcal{N}_{\phi^t, \mathbf{W}}) \in [\theta^t-\delta, \theta^t+\delta]$ using Eq.\,(\ref{prob}); \ELSE \STATE $\eta = {\eta_{end}}^{\mathcal{I}(|\pi^t|< M)\cdot(e - 1)/E}$; \STATE Sample a subnet structure $\phi^t \in \pi^t$ using Eq.\,(\ref{pool_p}); \ENDIF \IF{$\phi^t$ not in $\pi^t$ } \STATE $m^t = -batch\_loss$; \STATE Insert ($\phi^t, m^t$) into $\pi^t$; \IF{$|\pi^t| > M$} \STATE Remove $\big( (\phi^t)_M, (m^t)_M \big)$; \ENDIF \ELSE \STATE $m^t = \lambda \cdot m^t + (1-\lambda)\cdot(-batch\_loss)$; \STATE Update $m^t$ of $\phi^t$ in $\pi^t$. \ENDIF \STATE \textbf{return} $\phi^t$, $\pi^t$ \end{algorithmic} \end{algorithm} \subsection{Prioritized Subnet Sampling}\label{sec:Prioritized} We outline our prioritized subnet sampling in Alg.~\ref{alg:sampling}, which serves as a core distinction of our work from the previous studies. More details are given below. \subsubsection{Subnet Sampling (Line 1 -- Line 7, Alg.~\ref{alg:sampling}).} As mentioned above, we intend to sample a medium-sized subnet $\phi^t$ to train our PSS-Net in each training batch. Instead of simply sampling subnets from the subnet structure space $\mathcal{S}$, we also conduct subnet sampling from the subnet pool $\pi^t$ given the resource constraint $\theta^t$. To this end, we introduce a factor $p \in (0, 1)$ to indicate the probability of sampling from the subnet structure space $\mathcal{S}$. At the beginning of PSS-Net training, we sample subnets from $\mathcal{S}$ until $\pi^t$ is full. In this situation, we expect $p = 1$. As the training of PSS-Net, more high-quality structures of subnets will be inserted into $\pi^t$, and we expect to give priority to sampling from $\pi^t$, which indicates a small value of $p$. To this end, we formalize $p$ as: \begin{equation}\label{p} p = {p_{end}}^{\mathcal{I}(|\pi^t|< M)\cdot(e - 1)/E}, \end{equation} where $p_{end}$ is a pre-given parameter indicating the probability of sampling from the subnet structure space $\mathcal{S}$ when PSS-Net training ends. In our implementation, we set $p_{end} = 0.01$. $\mathcal{I}(\cdot)$ is an indicator which returns 1 if the input is true, and 0 otherwise. The $e \in [1, E]$ and $E$ respectively denote the current training epoch and the total training epochs. As can be seen, starting from $1$, the probability of sampling from $\mathcal{S}$ decreases to $p_{end}$ gradually. Consequently, the priority will be entitled to the high-quality subnets. \textit{Case 1: Sampling from the subnet structure space $\mathcal{S}$ (Line 3 -- Line 4, Alg.~\ref{alg:sampling})}. To sample a subnet $\mathcal{N}_{\phi^t, \mathbf{W}}$ conditioned on $\theta^t$, one naive solution is to go through trial and error until an eligible subnet is found. However, this strategy brings heavy cost. Usually, thousands of sampling are inevitable each time according to our experimental observation. Inspired by~\cite{wang2021attentivenas}, we resort to the probability distribution of subnets conditioned on the given resource constraint $\theta^t$, denoted as $\tau(\phi = \{o_i\}_{i=1}^L | \theta^t)$. However, the practical distribution is extremely complex to describe. While the Monte-Carlo approximation can be adopted, it is still intractable since multiple approximations have to be repeatedly constructed for each resource constraint $\theta^t \in \Theta$. To overcome this, we first generate a large-scale set of subnet structures $\mathcal{G}$ , and then compute the practical resource consumption of each structure $\phi \in \mathcal{G}$ as $\mathcal{C}(\mathcal{N}_{\phi, \mathbf{W}})$. Finally, we split $\mathcal{G}$ into $T$ non-overlapping subsets with $\mathcal{G}^1 \cup \mathcal{G}^2 \cup ... \cup \mathcal{G}^T = \mathcal{G}$ . For each subnet structure $\phi^t \in \mathcal{G}^t$, its resource consumption satisfies that $\mathcal{C}(\mathcal{N}_{\phi^t, \mathbf{W}}) \in [\theta^t - \sigma, \theta^t + \sigma]$. To model $\tau(\phi^t = \{o_i^t\}_{i=1}^L | \theta^t)$, we directly estimate the marginal probability of $\tau(o_i^t | \theta^t)$ as: \begin{equation}\label{prob} \tau(o_i^t | \theta^t) \approx \frac{\sum_{\phi^t = \{o^t_k\}_{k=1}^L \in \mathcal{G}^t}\mathcal{I}(o_k^t = o_i^t)}{| \mathcal{G}^t |}. \end{equation} With Eq.\,(\ref{prob}), the sampling times to find the target subnet reduces from $10^6$ to $10^1$ approximately according to our observation, which greatly improves the sampling efficiency. \textit{Case 2: Sampling from the subnet pool $\pi^t$ (Line 5 -- Line 7, Alg.\,\ref{alg:sampling}).} For $\pi^t = \{ \big( (\phi^t)_j, (m^t)_j ) \big) \}_{j=1}^M$, to obtain the best subnet conditioned on $\theta^t$ in Eq.\,(\ref{eq:sim_definition}), we resort to preserving the best subnet structure in $\pi^t$ for deployment, \emph{i.e.}, \begin{equation} (\phi^t)_{best} = \underset{(\phi^t)_j}{\arg\max}\, Acc(\mathcal{N}_{(\phi^t)_j,\mathbf{W}}), \end{equation} after our PSS-Net training. Thus, it is natural to prioritize the subnet structure with the best performance $m^t$ in $\pi^t$ to train our PSS-Net. To this end, we perform weighted sampling upon $\pi^t$ so that better subnets are assigned with higher probabilities. Thus, we can obtain a distribution set $\{ (q^t)_j \}_{j=1}^M$ with $\sum_{j=1}^M(q^t)_j = 1$ where $(q^t)_j$ denotes the probability of sampling $(\phi^t)_j$ to train PSS-Net, which is defined as: \begin{equation}\label{pool_p} (q^t)_j = \frac{\exp{\big((m^t)_j / \eta}\big)}{\sum_{i=1}^M\exp{\big((m^t)_i / \eta\big)}}, \end{equation} where $\eta$ is a temperature to control the smoothness of the distribution. In the early training stage, the subnets are not well trained, and thus $m^t$ is not a reliable measure to reflect the actual performance of each subnet. At this time, we expect each subnet to be sampled equally. As training goes, $m^t$ will become stable and we expect the distribution to be a one-hot form. Similar to Eq.\,(\ref{p}), we achieve this by setting $\eta = {\eta_{end}}^{\mathcal{I}(|\pi^t|< M)\cdot(e - 1)/E}$, where $\eta_{end} = 0.01$. \begin{table*}[!t] \centering \setlength{\tabcolsep}{2mm} { \begin{tabular}{c|cccc|cccc} \hline Backbone & \multicolumn{4}{c|}{MobileNetV1 569M / 70.6\%} & \multicolumn{4}{c}{MobileNetV2 301M / 72.0\%} \\ \hline Method & USNet & MutualNet & PSS-Net$_\text{F}$ & PSS-Net$_\text{M}$ & USNet & MutualNet & PSS-Net$_\text{F}$ & PSS-Net$_\text{M}$ \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}FLOPs(M)\\/ Acc(\%)\end{tabular}} & 569 / 71.8 & 569 / 72.4 & 555 / 74.2 & \textbf{562 / 74.5 } & 301 / 71.5 & 301 / 72.9 & 301 / 73.4 & \textbf{295 / 73.4 } \\ & 306 / 69.1 & 309 / 69.7 & 306 / 72.3 & \textbf{309 / 72.5 } & 151 / 67.6 & 154 / 70.1 & 154 / 70.7 & \textbf{154 / 70.7 } \\ & 114 / 61.9 & 111 / 63.5 & 107 / 67.9 & \textbf{107 / 68.0 } & 88 / 64.2 & 84 / 65.8 & \textbf{84 / 66.8 } & 83 / 66.7 \\ \hline Model & USNet & MutualNet & PSS-Net$_\text{G}$ & PSS-Net$_\text{M}$ & USNet & MutualNet & PSS-Net$_\text{G}$ & PSS-Net$_\text{M}$ \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}GPU\_lat($\mu$s)\\ / Acc(\%)\end{tabular}} & 238 / 71.8 & 238 / 72.4 & 238 / 74.4 & \textbf{236 / 74.5 } & 269 / 71.5 & 275 / 72.9 & 260 / 73.4 & \textbf{260 / 73.4 } \\ & 138 / 66.3 & 132 / 68.4 & \textbf{128 / 71.9 } & 131 / 71.8 & 229 / 62.3 & 207 / 71.0 & \textbf{197 / 72.5 } & 197 / 72.4 \\ & 76 / 57.3 & 80 / 63.5 & 76 / 68.1 & \textbf{71 / 68.1 } & / & 105 / 64.2 & 101 / 66.5 & \textbf{102 / 66.7 } \\ \hline Model & USNet & MutualNet & PSS-Net$_\text{C}$ & PSS-Net$_\text{M}$ & USNet & MutualNet & PSS-Net$_\text{C}$ & PSS-Net$_\text{M}$ \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}CPU\_lat(ms)\\ / Acc(\%)\end{tabular}} & 36 / 71.8 & 37 / 72.4 & 32 / 74.2 & \textbf{30 / 74.5 } & 41 / 71.5 & 41 / 72.9 & 30 / 73.2 & \textbf{33 / 73.4 } \\ & 22 / 67.8 & 21 / 68.4 & \textbf{21 / 72.8 } & 21 / 72.5 & / & 25 / 71.0 & \textbf{23 / 72.4 } & 26 / 72.4 \\ & 13 / 61.0 & 13 / 63.5 & 13 / 68.3 & \textbf{13 / 68.6 } & / & 17 / 64.2 & \textbf{17 / 69.0 } & 18 / 68.2 \\ \hline \end{tabular} } \vspace{-0.5em} \caption{ Performance comparison with the resource-adaptive methods~\cite{yu2019universally,yang2020mutualnet}. } \vspace{-0.5em} \label{tab:main} \end{table*} \begin{figure*}[!t] \centering \includegraphics[width=0.86\textwidth]{figs/main.pdf} \vspace{-0.5em} \caption{MobileNetV1/V2 experiments under single and multiple types of resource constraints.} \label{fig:main} \vspace{-1em} \end{figure*} \subsubsection{Subnet Pool Manipulation (Line 8 -- Line 16, Alg.~\ref{alg:sampling}).} We continuously collect the information tuple $(\phi^t, m^t)$ until the pool $\pi^t$ is full. When receiving a $(\phi^t, m^t)$, we insert it into $\pi^t$ such that the information tuples in $\pi^t$ are arranged in a decreasing order according to the performance $m^t$. In the case of full pool, we can obtain $\pi^t = \{ \big( (\phi^t)_j, (m^t)_j ) \big) \}_{j=1}^M$ with $(m^t)_{j+1} \le (m^t)_j$ and $(\phi^t)_j = \{(o^t_i)_j\}_{i=1}^L$. If one more tuple received, we will remove the worst performing tuple, \emph{i.e.}, $\big((\phi^t)_M, (m^t)_M\big)$, before inserting this tuple. To model $m^t$ of $\phi^t$, the best way is to define it as the accuracy of the subnet $\mathcal{N}_{\phi^t, \mathbf{W}}$. However, due to the large subnet structure space, it is almost impossible to execute a complete training for every subnet. Inspired by~\cite{wang2021attentivenas,berman2020aows}, we define $(m^t)_j = -batch\_loss$ if $\phi^t$ is inserted into $\pi^t$ for the first time. If $\phi^t$ is sampled from $\pi^t$ for updating PSS-Net, we update $m^t$ using moving average as $m^t = \lambda \cdot m^t + (1-\lambda)\cdot(-batch\_loss)$ after the current training batch. Here, we define $batch\_loss$ as the training loss in the current batch. \section{Experiments} \subsection{Experimental Settings} We use the light-weight MobileNetV1~\cite{howard2017mobilenets} and MobileNetV2~\cite{sandler2018mobilenetv2} as the backbones of PSS-Net and compared methods, and then conduct experiments on ImageNet~\cite{deng2009imagenet}. We set $o_i^{max}$ to be the same as the channel number of the $i$-th layer in the backbone network, and $r^{max}$ is 224. Then we define $o_i^{min}=0.75 \cdot o_i^{max}$, $r^{min}=128$. After that we can obtain the supernet $\mathcal{N}_{\phi^{max}, \mathbf{W}}$, and the subnet space $\mathcal{S}$. We perform three resource constraints in this paper, including FLOPs, CPU latency and GPU latency. The resource constraint set $\Theta$ ranges from $\mathcal{C}(\mathcal{N}_{\phi^{min}, \mathbf{W}})$ to $\mathcal{C}(\mathcal{N}_{\phi^{max}, \mathbf{W}})$ with steps of 10M, 10$\mu$s and 1ms for FLOPs, GPU latency and CPU latency, respectively. The subnet pool size $M$ is set to $50$. We construct lookup tables of CPU and GPU latencies for a quick calculation of resource consumption $\mathcal{C}(\cdot)$ during PSS-Net training. The details of the lookup tables and more ablation studies are provided in the appendix. \subsection{Experimental Results} \subsubsection{Comparison with Resource-Adaptive Methods.} We first compare our proposed PSS-Net with the resource-adaptive studies~\cite{yu2019universally,yang2020mutualnet}. We train four types of PSS-Net constrained by different resources including: (1) PSS-Net$_\text{F}$ is trained under only FLOPs constraint; (2) PSS-Net$_\text{C}$ is trained under only CPU latency constraint; (3) PSS-Net$_\text{G}$ is trained under only GPU latency constraint; (4) PSS-Net$_\text{M}$ is trained under multiple constraints of FLOPs, CPU latency and GPU latency. In Tab.\,\ref{tab:main}, we respectively compare the accuracies of the subnets resulting from different methods under similar FLOPs, GPU latency and CPU latency. Some observations can be found from Tab.\,\ref{tab:main}. First, our PSS-Net provides subnets with better performance when compared to MutualNet~\cite{yang2020mutualnet} and USNet~\cite{yu2019universally} under similar or less resource consumption on FLOPs, GPU latency and CPU latency. Second, USNet using MobileNetV2 as its supernet backbone fails to produce subnets with low GPU/CPU latency. Third, though PSS-Net$_\text{M}$ needs to accommodate more resource constraints, its performance is still comparable or even better than PSS-Net$_\text{F}$, PSS-Net$_\text{G}$ and PSS-Net$_\text{C}$ dedicated to a single type of resource constraint. Fourth, PSS-Net can significantly improve the performance of the backbone networks, for example, PSS-Net$_\text{M}$ increases the accuracy of MobileNetV1/V2 from 70.6\%/72.0\% to 74.5\%/73.4\% with reduction on FLOPs. To better demonstrate the advantage of our PSS-Net over existing studies, we further plot the resource-accuracy curves of different methods in Fig.\,\ref{fig:main}. We can observe that our PSS-Net consistently outperforms USNet and MutualNet by a large margin in all subfigures. Under similar resource consumption, our PSS-Net brings subnets with higher accuracy. In addition, similar to Tab.\,\ref{tab:main}, USNet using MobileNetV2 as the supernet backbone only produces subnets with high GPU/CPU latency. Specifically, the GPU latency is over 225$\mu$s and the CPU latency is over 30ms. Such a limitation greatly barricades the deployment of USNet, particularly when the available resources are in short supply. The reasons are attributed to two points. First, the input image resolution of USNet is fixed to 224, which is a large size and thus results in heavy GPU/CPU latency. Second, USNet adopts uniform subnet sampling, which ignores the diversity of layer-wise width. The resulting subnets are usually hardware-unfriendly. Our PSS-Net searches for the optimal image resolution for each subnet and the sampling strategy is non-uniform, which brings about subnets with low latency. Besides, the prioritized subnet sampling ensures that high-performing subnets are fully trained, which in turn entitles high performance of these low-latency subnets. \subsubsection{Comparison with Compact Models.} \begin{table}[!t] \centering \setlength{\tabcolsep}{1.3mm} { \begin{tabular}{cc|cc} \hline Method & \begin{tabular}[c]{@{}c@{}}FLOPs(M)\\/ Acc(\%)\end{tabular} & Method & \begin{tabular}[c]{@{}c@{}}FLOPs(M)\\/ Acc(\%)\end{tabular} \\ \hline MobileNetV1 & 569 / 70.6 & MobileNetV2 & 301 / 72.0 \\ \hline PNAS${\color{red}^\bigstar}$ & 588 / 74.2 & NASNet${\color{red}^\bigstar}$ & 488 / 72.8 \\ DARTS${\color{red}^\bigstar}$ & 574 / 73.3 & MetaPruning${\color{teal}^\blacktriangledown}$ & 291 / 72.7 \\ NASNet${\color{red}^\bigstar}$ & 564 / 74.0 & \textbf{PSS-Net$_\text{M}$} & \textbf{295 / 73.4} \\ PFS${\color{teal}^\blacktriangledown}$ & 567 / 71.6 & \textbf{PSS-Net$_\text{F}$} & \textbf{294 / 73.3} \\ \textbf{PSS-Net$_\text{F}$} & \textbf{569 / 74.1} & DPFPS${\color{teal}^\blacktriangledown}$ & 226 / 71.1 \\ \textbf{PSS-Net$_\text{M}$} & \textbf{562 / 74.5} & MetaPruning${\color{teal}^\blacktriangledown}$ & 217 / 71.2 \\ MetaPruning${\color{teal}^\blacktriangledown}$ & 324 / 70.9 & ChamNet${\color{red}^\bigstar}$ & 212 / 71.6 \\ MDP${\color{teal}^\blacktriangledown}$ & 309 / 71.2 & CC${\color{teal}^\blacktriangledown}$ & 215 / 70.9 \\ \textbf{PSS-Net$_\text{F}$} & \textbf{310 / 72.4} & AMC${\color{teal}^\blacktriangledown}$ & 211 / 70.8 \\ \textbf{PSS-Net$_\text{M}$} & \textbf{309 / 72.5} & DMCP${\color{teal}^\blacktriangledown}$ & 211 / 72.2 \\ PFS${\color{teal}^\blacktriangledown}$ & 286 / 70.7 & PFS${\color{teal}^\blacktriangledown}$ & 210 / 70.9 \\ AMC${\color{teal}^\blacktriangledown}$ & 285 / 70.5 & MDP${\color{teal}^\blacktriangledown}$ & 206 / 71.4 \\ NetAdapt${\color{teal}^\blacktriangledown}$ & 284 / 69.1 & \textbf{PSS-Net$_\text{M}$} & \textbf{204 / 72.1} \\ EagleEye${\color{teal}^\blacktriangledown}$ & 284 / 70.9 & \textbf{PSS-Net$_\text{F}$} & \textbf{203 / 72.1} \\ MetaPruning${\color{teal}^\blacktriangledown}$ & 281 / 70.6 & CPLI${\color{teal}^\blacktriangledown}$ & 166 / 67.4 \\ \textbf{PSS-Net$_\text{M}$} & \textbf{278 / 71.8} & DMC${\color{teal}^\blacktriangledown}$ & 163 / 68.4 \\ \textbf{PSS-Net$_\text{F}$} & \textbf{273 / 72.1} & \textbf{PSS-Net$_\text{F}$} & \textbf{163 / 70.9} \\ PFS${\color{teal}^\blacktriangledown}$ & 150 / 65.5 & \textbf{PSS-Net$_\text{M}$} & \textbf{163 / 70.9} \\ AutoSlim${\color{teal}^\blacktriangledown}$ & 150 / 67.9 & MetaPruning${\color{teal}^\blacktriangledown}$ & 140 / 68.2 \\ MetaPruning${\color{teal}^\blacktriangledown}$ & 149 / 66.1 & MDP${\color{teal}^\blacktriangledown}$ & 139 / 68.8 \\ \textbf{PSS-Net$_\text{F}$} & \textbf{126 / 68.1} & \textbf{PSS-Net$_\text{F}$} & \textbf{134 / 70.0} \\ \textbf{PSS-Net$_\text{M}$} & \textbf{118 / 68.1} & \textbf{PSS-Net$_\text{M}$} & \textbf{133 / 70.0} \\ \hline \end{tabular} } \vspace{-0.5em} \caption{ Performance comparison with compact models including channel pruning (${\color{teal}\blacktriangledown}$) and NAS (${\color{red}\bigstar}$). } \label{tab:pruning} \vspace{-1.5em} \end{table} We compare PSS-Net with some compact models including channel pruning and Network Architecture Search (NAS) methods. Channel pruning methods include PFS~\cite{wang2020pruning}, MetaPruning~\cite{liu2019metapruning}, MDP~\cite{liu2020joint}, AMC~\cite{he2018amc}, NetAdapt~\cite{yang2018netadapt}, EagleEye~\cite{li2020eagleeye}, AutoSlim~\cite{yu2019autoslim}, DPFPS~\cite{ruan2021dpfps}, CC~\cite{li2021towards}, DMCP~\cite{guo2020dmcp}, CPLI~\cite{guo2020channel} and DMC~\cite{gao2020discrete}. NAS methods include DARTS~\cite{liu2019darts}, PNAS~\cite{liu2018progressive}, NASNet~\cite{zoph2018learning} and ChamNet~\cite{dai2019chamnet}. We compare the accuracy under similar FLOPs consumption since the FLOPs metric is more often adopted in the compact model research. To that effect, we train our supernet PSS-Net$_\text{M}$ and PSS-Net$_\text{F}$ using MobileNetV1 and MobilenetV2 as backbones respectively, and then extract the best subnets from PSS-Net$_\text{M}$ and PSS-Net$_\text{F}$, whose FLOPs consumption is similar to the compact models for a fair comparison. Tab.~\ref{tab:pruning} displays the performance comparison. As can be seen, our PSS-Net$_\text{M}$ results in high-capacity subnets which not only surpass the compact model methods significantly, but also are better than the original MobileNetV1/V2. Taking MobileNetV1 as an example, our PSS-Net$\text{M}$ provides a subnet that reduces the FLOPs of MobileNetV1 from 569M to 278M, and meanwhile increases the accuracy from 70.6\% to 71.8\%. Moreover, these compact methods produce static models for deployment while our PSS-Net$_\text{M}$ offers switchable subnets to adapt the change of available resources, which greatly eases the model deployment in practical applications. \begin{table}[!t] \centering \setlength{\tabcolsep}{1.9mm} { \begin{tabular}{cccc} \hline Method & Subnet Num. &Training &Storage \\ \hline USNet & $N$ & $<4O_T$ & $(1+0.02N)O_S$ \\ MutualNet & $N$ & $<4O_T$ & $(1+0.02N)O_S$ \\ Pruning & $N$ & $NO_T$ & $NO_S$ \\ PSS-Net & $N$ & $<3O_T$ & $(1+0.02N)O_S$ \\ \hline \end{tabular} } \vspace{-0.5em} \caption{Complexity comparison of training and storage costs among existing resource-adaptive methods~\cite{yu2019universally,yang2020mutualnet}, channel pruning, and the proposed PSS-Net.} \label{tab:cost} \vspace{-1.5em} \end{table} \subsubsection{Complexity Comparison.} We further compare the storage and training costs of our PSS-Net, resource-adaptive methods~\cite{yu2019universally,yang2020mutualnet}, and a compact method of channel pruning. Denote the training cost of the supernet as $O_T$ and the storage cost as $O_S$. Given $N$ subnets, we summarize the cost complexity in Tab.~\ref{tab:cost}. For resource-adaptive networks, $k$ subnets of different sizes ($k=4$ for USNet and MutualNet, $k=3$ for PSS-Net) are trained in each batch, and thus the total training cost is not more than $kO_T$. The resource-adaptive network methods require to store BN parameters for each of the $N$ subnets (the number of BN parameters for each MobileNetV1/V2 subnet is about 2\% of the supernet's parameters $O_S$), and thus the total storage overhead is about $(1+0.02N)O_S$. Most of the channel pruning methods require a complete training for each compact subnet in isolation, so the total training cost is about $NO_T$ and the total storage cost is $NO_S$. Taking $N = 30$ as an example, PSS-Net achieves better performance than the channel pruning methods (Tab.~\ref{tab:pruning}) with about $\frac{1}{10}$ of the training cost and about $\frac{1}{20}$ of the storage cost compared to the channel pruning methods (Tab.~\ref{tab:cost}). \section{Conclusion} In this paper, we have proposed Prioritized Subnet Sampling to train a resource-adaptive supernet, referred to as PSS-Net. Compared to existing resource-adaptive networks, our PSS-Net offers subnets with a better accuracy-resource trade-off by maintaining a set of subnet pools, each of which is conditioned on a particular resource constraint, and assigning priority to high-quality subnets for training. Consequently, our PSS-Net produces a set of high-quality subnets with different resource consumptions, thus allowing a fast switch of high-quality subnets for inference when the available resources vary. Besides, compared to the compact network methods such as pruning and NAS, our PSS-Net significantly reduces the training and storage cost. Extensive experiments on ImageNet using MobileNetV1/V2 as supernets have demonstrated the effectiveness of our approach.
{'timestamp': '2021-09-14T02:19:08', 'yymm': '2109', 'arxiv_id': '2109.05432', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05432'}
arxiv
\section{Appendices} \section{Acknowledgments} This work was supported by the ReEnTrust project from the Engineering and Physical Sciences Research Council (grant number EP/R033633/1) and Oxford Univeristy COVID-19 Rebuilding Research Momentum Fund (0010067). \input{8.Appendix} \section{Introduction} Children are spending an unprecedented amount of time online each day via their smartphones and tablets. In the UK, for instance, 96\% of children aged 5-15 are online, and more than half of ten-year-olds have their own smartphones or tablets \cite{ofcom2020}. While the Internet has become an essential enabler for children to learn, have fun, and grow–--especially during a pandemic---there are, of course, significant risks associated with children going online, especially as they engage in new digital activities \cite{eukids2020, policy20218}. Increasing concerns are discussed regarding excessive screen time \cite{st2020, st2019, wang2019concerns}, as well as more direct risks including cyber bulling, inappropriate or harmful content, among others~\cite{zhao2019make, harm2017, pinter2017adolescent}. In response to children's increasing exposure to both classes of risks, a new genre of apps, known as \emph{parental control apps} have emerged. These tools are designed to act as technical mediation support for parents to facilitate access to, and control over, their children's online activities as a means of protecting them from such harms~\cite{zaman2016parental}. These apps have rapidly grown in popularity over the past few years. The global parental control software market is anticipated to grow from \$1.52Bn USD in 2017 to \$2.53Bn USD by the end of 2023~\cite{mrfr}. This rapid adoption and increasing reliance on parental control apps has raised corresponding questions about their efficacy --- how such apps fit into existing parenting strategies, and the effects such apps are having on parents and their children. Only a few empirical studies of these apps have thus far been conducted, and have started to reveal some shortcomings of these apps. Wisniewski et al. (2017) ~\cite{wisniewski2017parental} derived a Teen Online Safety Strategies Framework (TOSS) and applied it for an analysis of features of 75 popular parental control apps for teenagers. A following-up analysis of reviews on these apps by children found many reasons they disliked parental control apps, including the ways they overly restricted them and disenfranchised them of autonomy and privacy, but also identified positive aspects, such as for managing screen time and keeping them from harmful content~\cite{ghosh2018safety}. These studies reveal there may be significant room to improve parental control apps not just towards supporting more effective parental mediation, but ensuring that such measures do not inadvertently introduce new harms or take away valuable opportunities and benefits of digital environments for children. To understand where and how such improvements might be achieved, we used Wisniewski et al. (2017) ~\cite{wisniewski2017parental} as the baseline for our research. In this paper we first analysed 58 popular Android parenting control apps to examine how features on the current app market maps to the TOSS framework, and then we further analysed the ways these features were specifically realised. We found three primary axes of feature variation relating to \emph{granularity}, which refers to the level of control an app enables parents to do or the level of information given to the parents, \textit{feedback/transparency}, which refers to the different designs that support varied level of information given to the children, and finally \textit{parent-child communications support}, which reflect how apps supported or stimulated discussions between parents and children about their online activities. These axes of variation offer an orthogonal way of organising the current parental app design space in comparison to TOSS, allowing us to focus on the different designs used to support each function. To then understand how each of these axes relate to how apps effectively support or create problems for children, we conducted a thematic analysis of both children's and parents' reviews regarding how their perceptions varied across the ways features were implemented. The contributions of this paper are threefold, as follow: 1) first, it extends Wisniewski and Ghosh's ~\cite{wisniewski2017parental} TOSS framework by introducing three orthogonal axes of variation, which contributes an understanding of how parental control apps realise their functionalities differently along these three axes of variation, 2) second, by relating such axes to positive and negative reviews of apps, we identify how the design of features may influence children's and parents' perceptions of them, and finally 3) we identify gaps in the current parental control app design space, contextualising our findings to digital parenting theories. From this, we derive at least two approaches that more autonomy-supportive parental control apps might be achieved. The first, by simply designing app features to fall along each of the three axes within our identified ``zone of best practice''--designs perceived most positively by both parents and children. Second, to complement and pair restriction and monitoring features in an age and skill-appropriate manner, e.g. to gradually allow children to move from strictest monitoring and restriction features to gain more autonomy as they develop necessary skills associated with recognising and mitigating online risks, and to prioritise the use of verbal agreements, thus reframing the use of restriction and monitoring features as a means of scaffolding children's online skills. \section{Related Work} \subsection{Children's Online Safety} Children's online safety has been a broad topic that is closely related to our research. Livingstone et al. ~\cite{livingstone2015framework} categorised the different types of online risks under \textit{content (child as receiver), contact (child as participant) and conduct (child as actor)}, in which children may experience online risks of four types - aggressive (violent content, harassment, and hostile peer activity), sexual (pornographic content, sexual abuse online, `sexting'), values (hateful content, ideological persuasion, potentially harmful user-generated content) and commercial (embedded marketing, personal data misuse, copyright infringement). Similarly, the UK Online Harms White Paper ~\cite{hm2019online} identified the scope of online harms as explicit harms (e.g. harassment and cyberstalking), harms with a less clear definition (e.g. cyberbullying and trolling), and underage exposure (e.g. inappropriate material). A survey done by Ofcom in 2019 showed that data-related harms (e.g. data collection in obscure ways), security harms (e.g. scams/fraud) and content/contact harms (e.g. offensive language) were the most commonly reported online harms experienced by children~\cite{ofcom2019}. Children's online safety has become an even more critical issue when it comes to their mobile online safety, due to the ubiquitous nature of mobile devices. Existing online safety problems including stranger danger, online inappropriate content, bullying problems have been amplified. Children now have instant access to the internet~\cite{smahel2020eu,mollborn2020making}, and parents reported that it has been even harder for them to keep track of their children's online activities when their children were using devices of their own~\cite{PEW2020}. Children have been subjected to mobile use starting from a very young age. In their initial years (3-5), children's mobile use are still mainly adult-guided. Several studies indicate that it is not uncommon for parents to rely on technology to keep their children busy or entertained, regularly using a smartphone to replace babysitting \cite{livingstone2011risks}. Meanwhile, children at this stage do not always understand the difference between fantasy and reality~\cite{pine2002dear, ali2009young}. For slightly older children (6-11), they are gaining increasing independent use of devices \cite{ofcom2017, ofcom2016}. Children at this stage are learning about the complexities of relationships and becoming socially more sophisticated. Contacting their friends through mobile devices become an essential part of their lives, due to the need to fit in and be accepted by the peer group~\cite{kidron2017digital}. Meanwhile, they are particularly vulnerable to `tech tantrums' - reward loops and auto-plays make it difficult for them to manage their online usage because their evolutionary biology (need to react) is exploited by random rewards and interventions \cite{disruptedchildhood}. For children between 12-15, phone becomes a key social information and education tool. They start to become more heavily involved in social media platforms through their devices. A recent report showed that by the age of 13 already (the minimum age to open an account on many social media platforms) , more than half of them have a social media profile~\cite{ofcom2019}. Meanwhile, children at this stage are undergoing significant neuro-psychological changes, leading to differences in how they perceive emotions and make decisions~\cite{kidron2017digital, paulsen2012risk}. They often become easily influenced by the content they see as they tend to be characterised by idealism, with a tendency towards polarised thinking \cite{temple1997cognitive, briones2013kony}. Today's children are exposed to the same range of online risks on mobile platforms, only with risks becoming even more exacerbated and pervasive. \subsection{Theoretical Frameworks For Children's Online Safety} Safeguarding children during their use of technologies has been a long concern for parents. With more of these theories being embedded in technical designs and empirically evaluated, we are seeing a transition of focus from the parent-centred approach that emphasises on restrictions and family rules, to the more child-centred approach that encourages self-autonomy and empathy. \subsubsection{Parental Mediation Theory: From Pre-Internet Era to Digital Parenting} The basis of work focusing on ways that parents can regulate their children's media habits is grounded in parental mediation theory. Pre-dating the Internet era, the focus of parental mediation was on children's TV consumption \cite{nathanson1999identifying, valkenburg1999developing} and how parents can prevent or mitigate harmful effects of children's exposure to increasing amounts of TV content, in particular, that containing violent and inappropriate themes. It set up three mediation strategies: \emph{restrictive mediation}, setting rules and regulations about children's television viewing, \emph{co-view}, simply watching television with children, and \emph{active mediation}, or talking with children about the content they saw on television. With increasing concern over risks beyond media exposure, parental mediation theory has been adapted to incorporate these broader concerns regarding children's online safety. It was refocused to the goal of minimising online risks in general while maximising opportunities for children \cite{livingstone2008parental, mesch2009parental}. This change of context required considerable refinements to the constructs of existing theories. Restrictive mediation, for instance, was recast to refer to parents setting the family's rules and boundaries around online activities. While the restriction of television media consumption was relatively easy as parents can take guidance from television program classification \cite{clark2011parental}, online restriction requires much more effort from parents as it involves a great more of diversity. This modern version of restrictive mediation now also includes some technical means, such as using software restrictions to limit access to content or screen time \cite{nikken2014developing}. Active mediation is still centered around parent-child communication and refers more specifically to parents' active efforts to guide, interpret, and discuss online harms and risk copings with children \cite{clark2011parental}. Co-view has been replaced by a more ``internet-specific'' strategy - monitoring children's activities online. \subsubsection{Teen Online Safety Strategies Framework (TOSS)} The TOSS (Teen Online Safety Strategies Framework) proposed by Wisniewski et al. \cite{wisniewski2017parental} made a novel attempt of highlighting the gap between a parent-centred and a child-centred mediation approach, see Figure~\ref{fig:pmt}. TOSS is a theoretically derived conceptual framework of teen online safety strategies, comprised of two main strategies - parental control, which was originally derived from parental mediation theory; and teen self-regulation - the framework extends the mediation theory by introducing a complementary set of strategies centred around the child/teenager orientated around teen self-regulation. As shown in Figure~\ref{fig:pmt}, the parental control strategies contain three sub-strategies, including \textit{monitoring}, \textit{restriction}, and \textit{active mediation}. The teen self-regulation strategies comprised \textit{self-monitoring}, in which children self-regulate their behaviors through self-observation; \textit{impulse control}, which refers to children exhibiting their short-term desires in favor of the long-term consequences; and \textit{risk-coping}, defined to be a self-regulatory process that occurs after one found themselves in risks, which typically involves processes such as problem-solving, advice-seeking and acquiring social support. Although originally developed for analysing \textit{teen} online safety strategies, the TOSS framework is equally valuable for analysing \textit{children} online safety strategies, especially the \textit{parental control} side of the framework. Furthermore, the framework provides a useful way for analysing parental control apps practices. In the original paper the framework was proposed, the authors used the TOSS framework to analyse features that support parental control strategies and teen self-regulation strategies \cite{wisniewski2017parental}, and they found that the apps strongly favored features that promote parental control through monitoring and restricting teens online. The framework provides the conceptual basis of our work here, which relies on both Parental Mediation Theory and TOSS. In particular, we used the TOSS framework as the baseline for our app analysis. \begin{figure}[h] \centering \includegraphics[width=1\textwidth]{PMT.jpg} \caption{How parental mediation theory changes through the digital age and how it connects to the TOSS framework} \label{fig:pmt} \end{figure} \subsubsection{Mediation Strategies: A Dynamic Process} \label{subsubsection:beyondTOSS} Both the parental mediation theory and TOSS categorised the online safety strategies into distinct types. Previous research argued that the parental mediation theory tends to address restriction, monitoring, and active mediation strategies independently of each other \cite{beyens2017parent, meeus2018managing}. However, several studies have challenged the view that one mediation type should be significantly better or worse than the others. They instead found that parent-child conflicts depend more on the styles in which parents provide mediation, regardless it's restriction, monitoring, or active \cite{beyens2017parent, valkenburg2013developing}. For example, Valkenburg et al~\cite{valkenburg2013developing} suggested that active, monitoring or restrictive mediation strategies are not in themselves good or bad; their effectiveness may depend on the style in which parents apply these strategies to their children. Examples of such styles were adapted from a self-determination theory viewpoint \cite{ryan2000self}, namely \textit{controlling}, parents pressuring children to think and behave in certain ways through, for example, guilt induction or criticism \cite{fikkers2017matter}; or \textit{autonomy-supportive}, which refers to ``structure and guidance but takes the child’s feelings and perspective seriously providing a convincing rationale for behavioural requests and rule-making'' \cite{valkenburg2013developing}; or \textit{inconsistent}, in which parents were sometimes strict and at other times acquiesce to their children \cite{fikkers2017matter}. Similarly, studies on families showed that parents do not use active and restrictive mediation strategies independently of each other. Instead, parents who were motivated to play an active part in their children’s online activities also tend to implement monitoring and restriction through various active ways \cite{chen2016active}. These findings echo similar work that suggested that parental mediation may be better conceived as a dynamic process that should integrate into the daily interactions between parents and children, rather than as a set of distinct strategies implemented separately \cite{symons2017parental}. \subsubsection{Online Safety as Skill Development} Parental mediation theory can be dated back to developmental psychology research in the early 20th century on how children's developmental could be guided by interpersonal communication ~\cite{reynolds1971mutually}. While parental mediation theory drew upon Bandura's social learning theory ~\cite{bandura1977social} that posit parents as `role models' and explore how parental involvement may mitigate the negative behaviour of children. There has been another line of work that also originated from interpersonal communication studies, but place at the center of the investigation the children and their interactive experiences with adults. Vygotsky ~\cite{chaiklin2003zone} theorised children's potential for cognitive development using the term `zone of proximate development'. This `zone' describe the things that's beyond the children's current capabilities, but is `just about' to be grasped by them as long as they are given sufficient `scaffolding' - guidance and support from more knowledgeable others. A survey of 215 parents and their teens showed that increased parental control was associated with more (not fewer) online risks~\cite{10.1145/3173574.3173768}. On the other hand, a study of 18 U.S. families with children ages 5-11 found that children largely relied on their parents for online risks support, and parental scaffolding via conversations and interactions was an essential part of their rick coping skills development~\cite{kumar2017no}. Similarly, a study with children aged 6-10 in the UK showed children were well capable of grasping the key ideas of online risks and develop coping skills, when sufficient scaffolding is given~\cite{zhao2019make}. \subsection{Parental Control Apps For Children's Online Safety} With the increase of digital technologies in families' life, parental controls mobile apps are commonly used by parents to mediate their children's online usage. Research has been trying to assess how effective these apps are for safeguarding children online. A review of 75 parental control apps \cite{wisniewski2017parental} showed that restriction and monitoring approaches were most common across the commercial market of these parental control apps. A further study on users' perspectives found that children mainly felt these apps were overly restrictive and invasive of their privacy and negatively impacting their relationship with their parents \cite{ghosh2018safety}. Recent research also explicitly analysed the linguistic patterns of parent's reviews versus children's reviews on parental control apps and found that tensions were more likely to occur when apps failed to solve problems regarding children's safety \cite{alelyani2019examining}. Apart from users' perceptions, existing literature also suggested there are significant privacy concerns around these apps. In a study done on 46 parental control apps, researchers found that 72\% of them share data with third parties without mentioning their presence in privacy policies \cite{feal2020angel}. Following these understandings, researchers are beginning to explore new ways to enable this safeguarding. For instance, Ghosh et al.~\cite{ghosh2020circle} proposed \textit{Circle of Trust}, a parental mediation tool that integrates positive family values and aims to strike a balance between teen's privacy and their online safety. Hashish et al.~\cite{hashish2014involving} designed We-Choose, a tool for controlling content on the smart tablets for children between six to eight years. It supports collaborative rule-setting by facilitating discussion on the appropriateness of apps and helping children to review their choices . Ko et al.~\cite{ko2015familync} developed \textit{FamiLync}, a tool that facilitates participatory parental mediation by encouraging both parents and children to participate in co-learning of digital media use. However, we still lack a systematic understanding of how various parental mediation theories are currently realised or designed in the commercial market. \section{Methods} We used two pipelines to explore our research questions (see Figure~\ref{fig:pipeline}), to analyse app feature designs and their app reviews. Through this, we wanted to review how parental control is currently realised to identify gaps in the market and further see how these features are perceived by users. We particularly aligned our app feature coding with the qualitative feature analysis conducted by Wisniewski et al. in 2017~\cite{wisniewski2017parental}. Their analysis included 75 Android mobile parental control apps and led to an identification of 42 app features (e.g. website monitoring, or app activity blocking) that are mapped to the TOSS conceptual framework (see Figure~\ref{fig:pmt}). Our methodology was based on and extended the work by Wisniewski et al~\cite{wisniewski2017parental}. We started by replicating their method for app data acquisition and then introduced particular analysis about how each of the feature was realised in the current apps. Our intention to replicate here was not just to establish a baseline for our further analysis but also because replication is especially valuable in HCI to analyse quickly evolving phenomena, especially the design of mobile apps. \begin{figure}[h] \centering \includegraphics[width=1\textwidth]{method.jpg} \caption{Our methodology: we started by replicating the method by Wisniewski et al~\cite{wisniewski2017parental} and used their results as baseline for our analysis. We then extended our data analysis beyond their methodologies by 1) analysing how the app features are realised; and 2) conducting a thematic analysis on parents' and children's reviews of these features in order to identify their positive v.s. negative perceptions. } \label{fig:pipeline} \end{figure} \subsection{Collecting Apps} In July through August of 2020, we sought to identify popular Android parental control applications (“apps”) that promote children's online safety on Google Play. In order to effectively compare our analysis with Wisniewski et al.'s~\cite{wisniewski2017parental} analysis of app features in 2017, we adopted their search keywords (since our research focused on children instead of teens, we replaced the words ``teen'' and ``adolescent'' with ``child''). We performed keyword searches using the terms ``online safety,” ``family safety,'' ``child safety,'' ``child online safety,” ``parental controls,'' ``parental monitoring,'' ``child monitoring,'' ``cyberbullying,'' and ``sexting.'' Similar to the original method used by Wisniewski et al~\cite{wisniewski2017parental}, we also included all ‘similar apps’ that were suggested by the search results, and read each app description \& app screenshots to ensure returned results met the inclusion criteria, which was that the app had to be designed to support the parental mediation of children's online activities. We generated an initial list of 241 apps. During our process of finding and filtering through these apps, we found that the popularity (in number of downloads) of these apps assumed a long tail distribution: nearly 80\% of these 241 apps had fewer than 20 downloads, while the more popular apps had multi-thousands of downloads. Since our intentions were to examine features and design elements in the most popular apps, we kept the top 66 apps with at least 10K+ downloads. Among these 66 apps, we further removed the following: three that required subscriptions to use, two that required SIM cards (which was not installed on the test device), and three focused on parental control of IoT devices. Our final app list included 58 apps. Out of these 58 apps, only 27 of the apps were identical to Wisniewski's original app list in 2017. The full list of apps can be found in Appendix. \subsection{Analysing App Features} In analysing apps, our goals were twofold: to identify key features that these apps have, and, second, to identify whether such apps varied in terms of the ways that such features were realised. We first generated descriptions of app features by applying a walkthrough method~\cite{light2018walkthrough}, first role-playing as a parent and then as a child using the app. This method is similar to the more commonly used cognitive walkthroughs (CWs) in usability evaluation~\cite{lewis1997cognitive}, in that it is an exploratory screen-by-screen navigation through each app, role-playing as a particular kind of user. However, there are two important differences: unlike cognitive walkthroughs, our objective was not to identify usability problems, but to identify and descriptively characterise the features of each app. Second, instead of starting with extremely concrete tasks, we started with the goal of approaching each app as a methodical new user might, trying all features provided and systematically exploring their options. To do this, we installed each app on our devices, in turn. For parenting apps that came in pairs (corresponding to a parent child version), we installed the parent app on an Android tablet, and the corresponding child app on an Android mobile phone. For those apps that were singular apps, we set up the app in parent mode on the tablet, and installed set up the app in child mode on the mobile phone. The tablet used for analysis was a Huawei MediaPad M5 with 32GB of storage running Android 9 and the phone we used was a Samsung Galaxy S20 with 16 GB of storage running Android 9. Then, two researchers role-played a parent and then a child, on each respective app, walking through the app a screen at a time to identify features each app provided. Each feature was examined to identify all options and functionality. Then, a short textual description was generated for each. \subsubsection{Identifying Distinct Features Using TOSS Categories} \label{subsubsection:methodTOSSfeature}- We first analysed these descriptions using a ``top-down'' approach, applying the codebook from Wisniewski et al~\cite{wisniewski2017parental}. Although TOSS focused on teen self-regulation, we felt it still appropriate as a starting point for two reasons; first, most such apps did not explicitly designate use by teens only (vs younger children); second, the emerging literature on online safety of younger children suggested that establishing safety-related skills and self-regulation was increasingly pressing in children's younger years due to their increased activity online~\cite{kumar2017no}. Therefore, we chose to interpret the \textit{teen self-regulation} strategies of the TOSS framework as self-regulation strategies for all children \cite{wisniewski2017parental}. Two researchers coded each feature description against the TOSS feature codebook. If a particular feature did not correspond to an existing code, we made a note with a description of its functionality and added it as a new separate feature into our code book. Cohen's kappa was calculated to be high ($\kappa=0.83$) on a hold out sample of 20\% of the apps. \subsubsection{Feature Design Analysis} \label{subsubsection:methodFeatureDesign} - To explore feature variation, we revisited the feature descriptions and performed a second round of coding, focusing on \emph{how features was realised}. This analysis phase was, again, performed by two researchers who sub-divided the apps. Codes were reconciled, refined, and combined, and then affinity-clustered based on across all TOSS strategies. This process yielded 22 clusters corresponding to three axes: 6 along \emph{granularity}, 8 along \emph{feedback/transparency}, and 8 along \emph{parent-child communications support}, as we describe in detail in Section \ref{subsection:threeaxes}. \subsection{Collecting App Reviews} The second analysis pipeline focused on app user reviews; to complement our app analysis, we sought to collect user reviews of each of the 58 apps to understand users' opinions. We scraped all reviews for 58 apps (including the \textit{child app} versions) using open source scraping tools \cite{gps}. This resulted in an initial data set of 93,404 reviews from all 58 apps. Duplicate reviews were then removed, yielding 81,488 reviews. \subsubsection{Selecting app reviews pertaining to specific features} Due to the immense number of reviews being spams, irrelevant, or simple statements without justification like ``It's good'', we sought to keep only user reviews that expressed a view about specific TOSS features \footnote{By TOSS feature here, we are not referring to the original features as in Wisniewski 2017, but the features we identified using the TOSS framework (with newly identified features). See Figure \ref{fig:feature_compare} for a full list of our TOSS features.} with some sort of justification. Thus, we developed the NLP pipeline to achieve this. Our pipeline was based on that by Guzman et al. \cite{guzman2014users}. An initial data processing procedure was done to only keep the nouns, adjectives and verbs in the reviews. We then used the bigram finding algorithm provided by the NLTK toolkit \cite{bird2009natural} for extracting user reviews around specific features (A bigram is a two-word phrase that co-occurs unusually often). We filtered the bigrams by only considering those that appeared more than five times and had less than three words distance between them. We then clustered bigrams whose pairs of words were synonyms using Wordnet \cite{miller1995wordnet}. After that, we manually reviewed each bigrams cluster to map it to each TOSS feature (identified in Section~\ref{subsubsection:methodTOSSfeature}). For example, both bigrams clusters <limit time> and <limit screen> would belong to the SCREENTIME-BLOCK feature, which is about limiting screen time. This gave us an indication whether an app feature was indeed discussed in a review, and hence made it a potentially `meaningful' review. We then traced back to the original reviews where these bigrams that can be mapped to a TOSS app feature were extracted from. The author then went through all of these reviews to manually verify that the corresponding TOSS feature was indeed mentioned in the review, remove any inconsistent ones and the ones not about a specific feature. We ended up with a review data set consisting of 3,264 reviews in total. To identify perception difference between children and parents, we used a similar method to Ghosh et al~\cite{ghosh2018safety}. This means that we also used certain keywords and phrases to identify posts by parents and children respectively. Examples indicating a child's perspective included: ``my parent'', ``my mom'', ``my dad'', ``I’m a kid'', ``I’m xx years old''. The two authors manually reviewed the automatically generated results. Out of the 3,264 reviews, we identified 746 child reviews and 2,518 parent reviews. We now have a data set consisting of review around each TOSS features, from children, and parents, respectively. \subsection{Analysing App Reviews} We conducted a thematic content analysis on the final filtered set of reviews to identify what perspectives parents and children hold in terms of the apps and their features. So far, the review dataset has been labelled with the TOSS app feature (e.g. monitoring website) discussed by each review (for filtering meaningful reviews), and the type of user contributing the review (parent vs. child). Here, we would like to first identify the feature designs discussed in each review, and then analyse the perceptions from parents and children about each feature design --- positive or negative. First, the researchers used a top-down approach to read through each review to categorise reviews around feature designs (i.e. how a feature is implemented) we previously compiled in Section \ref{subsubsection:methodFeatureDesign}. Then, for reviews around each type of feature designs (e.g. ALL-OR-NOTHING), we used a grounded, thematic approach~\cite{wildemuth2016applications} to identify themes about why a parent or a child liked or disliked that feature design. (The final codebook for reviews data can be found in Appendix) The thematic coding process was performed by two researchers who sub-divided the reviews. The hold out sample was 50 reviews (roughly around 35\%) for each feature design (e.g. coarse granularity, low feedback/transparency), with a Cohen's kappa of 0.77. \section{Results} \subsection{App Feature Analysis} \label{subsection:TOSSfeature} \begin{figure}[h] \centering \includegraphics[width=1\textwidth]{feature_compare.jpg} \caption{Comparing our TOSS feature analysis results with Wisniewski 2017. We found that in practice, active mediation features were often grounded in monitoring and restriction features; Also, restriction and monitoring features came in a great variety of details that was not captured by TOSS (*Previously \textit{TEEN SELF-REGULATION} in Wisniewski 2017 original code book)} \label{fig:feature_compare} \end{figure} Applying the TOSS framework~\cite{wisniewski2017parental} to categorise app features, we identified many features that supported both \emph{Monitoring} and \emph{Restriction} strategies. Figure \ref{fig:feature_compare} juxtaposes the number of occurrences of such features we found in our 58 apps against those reported in the original TOSS paper~\cite{wisniewski2017parental}. As visible in the figure, the prevalence of restriction and monitoring features in apps generally increased compared to the original analysis, suggesting that parental control apps have become more featureful since 2017. Moreover, we identified several new features for supporting \emph{Active Mediation} than in the original study. This includes providing information about apps to help parents decide whether an app is suitable for their child (\textbf{APP-INFO}), and features that encourage parents and children to set technology usage rules together (\textbf{CO-CONFIG}). These features are described in the box in Figure \ref{fig:feature_compare}. In terms of teen/child self regulation, we found several features supporting \emph{Self-Monitoring}, including sending reports to children regarding their mobile usage (\textbf{REPORTING-C}), sending app activity logs to children (\textbf{APP-LOG-C}), and sending browser histories to children (\textbf{BROWSER-LOG-C}).In line with prior work, we did not find any features belonging to \emph{Impulse Control}, or any meaningful \emph{Risk-Coping} strategies (apart from sending SOS requests). During the analysis process, we found considerable variation among the designs of how the features that belonged to a single code were realised. For instance, among apps that offered functionality logging children's app usage (\textbf{APP-LOG}), some apps recorded highly granular detail of the child's activities within, and across, particular apps, whilst others only logged events of a specific type, such as `suspicious activities'. This variation was what inspired us to examine the design axes of variation which we describe in section \ref{subsection:threeaxes}. Third, we found some features supporting child-empowerment that did not correspond to any of the three existing TOSS strategies for self-regulation. Examples included features designed to provide a means for children to inspect their restriction/monitoring policies (\textbf{POLICIES INFO}), as well as features that offer children with detailed information about an app, enabling them to decide what app to use for themselves (\textbf{APP INFO-C}). Finally, with respect to app features supporting \emph{Active Mediation}, we found that rather than being standalone, such features were often contextualised within other restriction and monitoring features. Examples included messaging features that let children request more screen time, or access to a restricted app. Like these, most forms of mediative support concerned restrictions or monitoring activities. Another type of support included interfaces that encouraged parents to collaboratively discuss and negotiate restriction and monitoring policies with their child (\textbf{CO-CONFIG}), instead of encouraging parents to set such policies without their child's involvement (e.g., \textbf{SCREENTIME-BLOCK}). Even (\textbf{PARENTING-TIPS}), the closest to being a standalone active mediation feature, was most often associated with tips around restriction or monitoring strategies. \subsection{Feature Design Variations} \label{subsection:threeaxes} When looking at how features are specifically realised we identified that they fell into three axes of variation, including \textit{granularity}, which refers to the level of control an app enables parents to do or the level of information given to the parents, \textit{feedback/transparency}, which refers to the different designs that support varied level of information given to the children, and finally \textit{parent-child communication support}, which reflect how apps supported or stimulated discussions between parents and children about their online activities. These axes of variation offer an \textit{orthogonal} way of organising the current parental app design space in comparison to TOSS, allowing us to focus on the different \textit{designs} used to support each function. We identified 6 feature \textit{designs} along granularity, 8 feature \textit{designs} along feedback/transparency, and 8 feature \textit{designs} along communications support that reported that variation of designs of TOSS features, as summarised in Figure~\ref{fig:designs_stats}. \begin{figure}[h] \centering \includegraphics[width=1\textwidth]{designs_stats.jpg} \caption{Three axes of variation along which app feature designs varied.} \label{fig:designs_stats} \end{figure} \subsubsection{Axes 1: Granularity} We observed that the level of control/information provided by apps for the parents spanned from very coarse level of granularity, e.g. control/monitor based on an \textbf{ALL-OR-NOTHING} filtering --- parents having to either block all contents or nothing at all; to highly granular feature designs including allowing parents to configure control/monitor on a per app basis (\textbf{CONTROL/MONITOR-PER-APP}). \begin{enumerate} \item (\textit{Coarse}) ALL-OR-NOTHING : This is a most widely supported design (appearing in 40\% of all apps) that spans across all TOSS features. Parents had to either block all contents and request access to every detail (e.g., every video watched, website visited, the apps opened, even logging google search \&keyword queries.) about children's online activities, or gaining no access about children's activities at all, leaving no middle ground in between. \item (\textit{Medium}) CONTROL-CATEGORY/AGE: In comparison to the all-or-nothing approach, this category allows parents to control children's access based on app/website categories. Such categories were usually derived directly from app store listings or website ratings, and seen to afford parents the convenience of setting broad policies without concerns over specific apps or websites. \item (\textit{Medium}) MONITOR-CATEGORY: Provide only high-level summaries of activities children performed on the phone, such as a list of top contacts, apps used, and time spent on the device per day. These high-level summaries were sometimes grouped by app category. \item (\textit{Medium}) CONTROL/MONITOR-CONTACT-LIST: At this level, parents are given a chance to provide customised control by providing a list of a pre-approved contact (or ``suspicious'' contact list); and when children contact people on that list, parents will be acknowledged (or showed with texts etc.) \item (\textit{Medium}) MONITOR-SUSPICIOUS: Similarly, this control of suspicious content can be automatically achieved by apps, which report and alert parents only based on ``suspicious'' or ``dangerous'' activities, messages, or content. \item (\textit{High}) CONTROL/MONITOR-PER-APP: At the highest granularity of control, parents are required to configure settings on a per-app (or website) basis. \end{enumerate} \subsubsection{Axis 2: Feedback/Transparency} By feedback/transparency, we refer to the designs (specifically of monitoring features) that support variation of the level of information given to children. While being closely related to the self-monitoring strategies in TOSS framework, this axis extended and enriched it by adding design variation details and discussed designs that supports children's autonomy online. The variation of these designs ranges from very low feedback/transparency - providing no information on the screen rules and things being monitored, to high feedback/transparency - supporting children with resources (e.g. expert reviews, ratings) to let them decide for themselves what to use. \begin{enumerate} \item (\textit{Low}) RULES-NO-SHOW: A considerate amount of apps (14\%) provided no indication about the restrictions enforced on children's phones, leaving them with no idea of the things they could still do on their phones. \item (\textit{Low}) MONITOR-NO-SHOW: Nearly a third of the apps in our data set did not acknowledge children about how their information were being monitored by their parents. \item (\textit{Low}) ONLY-RULES-AT-MOMENT: This design shows prompts \textit{at the moment} e.g. when children were attempting to access a website on blocking list. However, children weren't informed with the screen rules in advance. \item (\textit{Medium}) RULES-PAGE, provides a means for children to view/inspect the restrictions policies, giving them more transparency than the designs above. \item (\textit{Medium}) MONITOR-PAGE, provides some rudimentary information to children about which activities were being monitored, such as browsing history, app use history, device use time, or messaging. \item (\textit{High}) RULES-EXPLAINED, identified in a small number of apps reviews (6\%), offers a clear explanation for children when an activity or action exceeded or violated a restriction and why that might be bad for children (rather than simply terminating the activity or giving a generic system error or a blank screen). \item (\textit{High}) MONITOR-SELF-TRACK, provides children feedback about their activities as they used the device, such as how much time they had left (total screen time or on an app). \item (\textit{High}) SHOW-KIDS-INFO, again identified in only 6\% of all apps, offers children with detailed information of each app, including expert reviews and ratings, enabling children to decide what apps to use for themselves. \end{enumerate} \subsubsection{Axis 3: Communications Support} As this dimension is pertained to the ways apps supported or stimulated discussions between parents and children about their online activities, it is closely related to previously defined active mediation in TOSS framework. However, in practice, active mediation features are more about \textit{active ways} in which restriction/monitoring can be implemented. This dimension portrayed the variation of such design details. This was done in two ways: first, through features that encouraged communication around the restriction and monitoring policies, and through coaching using discussion aides. \begin{enumerate} \item (\textit{Low}) NO-MEANS: More than half of the apps (54\%) offered no means for children to negotiate screen rules with their parents, and their only choice was to accept and obey. \item (\textit{Medium}) SEND-MESSAGE: In comparison to the complete lack of communication support, these designs make it simple for children to send a message to their parents asking for permission to perform a particular restricted activity, or to grant an exception or extension to a particularly restrictive policy. These features have been identified in 18\% of our apps. \item (\textit{Medium}) REWARD: Provide extrinsic reward incentives for children to earn additional screen time, app categories and content, or access to ordinarily restricted activities. \item (\textit{Medium}) BOTH DEVICE: We found one app that coach or prompt parents and children to spend time with each other, e.g., using a family time lock screen feature for both parents and children's phones to lock both devices out for a duration of time per day to encourage both to spend offline time without the distraction of a screen. \item (\textit{Medium}) APP-INFO: Provide specific information to help parents ascertain whether an app was suitable for their children's use, to understand potential risks, and other issues about the apps they might want to discuss. \item (\textit{Medium}) AGE-GROUP-INFO: Help parents to compare their children's online activities (usually screen time) in comparison with other kids of the same age group. \item (\textit{High}) CO-CONFIG: Provide explicit support that encourages parents and children to set screen rules together, which included interfaces designed to serve as boundary negotiating artifacts ~\cite{lee2007boundary} for a joint resolution of activity restrictions and monitoring policies. \item (\textit{High}) PARENTING-TIPS: Offer advice to parents, include strategies ranging from how to apply restriction/monitoring policies to their children, to how to talk about sensitive issues such as bullying, stranger danger, online pornography, and sexting. \end{enumerate} \subsection{Thematic Analysis of Reviews} This section presents an overview of the primary themes pertaining to the reasons children and parents, respectively, liked or disliked feature designs provided by parental control apps, and how their perspectives varied across the axes of different ways in which features were realised. \subsubsection{\colorbox{shadecolor!20}{\textit{Coarse Granularity}}} We first start with perceptions around granularity - how different feature designs varied in granularity influenced users' perceptions of features. For \textit{coarse} granularity, we specifically refer to the features that are based on \textbf{ALL-OR-NOTHING} filtering. Parents had to either block all contents/shown with every detail (e.g., every video watched, website visited, the apps opened,even logging google search \& keyword queries.) about children’s online activities, or having no access at all, leaving no middle ground in between. Both parents and children, children in particular, expressed grievances on these features: \noindent\textbf{Disliked being overly surveilled and restricted [C]} - The most common grievance of children regarding \textbf{ALL-OR-NOTHING} was the view that these designs not only enabled but nudged parents to set up overly restrictive controls and excessive surveillance. Kids expressed resentment at the extent of both the restrictions and their surveillance, and reflected on the effects lives, welfare, and activities: \begin{small} \begin{quote} This literally blocks everything, I can't even read e-books on my phone. \end{quote} \end{small} \begin{small} \begin{quote} This is insane. Now they can see EVERYTHING! From my browsing history to what apps I downloaded, even my texts! Worst app ever! \end{quote} \end{small} \noindent Kids reflected on a variety of secondary effects of excessive restrictions and surveillance. One child discussed that they felt that, beyond violating their privacy, it was particularly wrong that their parents' access to their messages would compromise their friends' privacy as well: \begin{small} \begin{quote} they can eves drop on your convos and stuff that you dont want them to hear [...] not only is it a violation of my privacy that i didnt permit, but it is of friends too that parents dont know about \end{quote} \end{small} \noindent The pervasiveness and constancy of surveillance made it feel to one as if these apps enabled their parents to ``stalk'' them: \begin{small} \begin{quote} I hate this app my mom is like stalking my life!! \end{quote} \end{small} \noindent Even when not restricted, the perception that their social communications were being surveilled by their parents had a chilling effect that indirectly forced them to cease communicating and be cut off from their friends. \begin{small} \begin{quote} I can't talk with my friends anymore, everything will be recorded! \end{quote} \end{small} \noindent Several comments discussed longer-term effects such restrictions were having on their well-being. One view was that restrictions were directly and immediately harmful because they broke essential lines of social support. \begin{small} \begin{quote} This is stupid. absolutely awful. this will ruin people's lives. I had severe depression and the only thing keeping me from killing my self was my friend who I could only talk to online. Now I'm fine but if I lose contact with that friend I will most likely get my depression back. Horrible and stupid app. \end{quote} \end{small} \noindent Beyond cutting off lines of social support, restrictions were seen to prevent kids from apps and activities that they normally used to cope with boredom and isolation, further undermining well-being: \begin{small} \begin{quote} I can't play a lot of games, and I can't watch YouTube. I've sat in my room for weeks doing nothing and practically getting depressed because there is literally NOTHING I can do! \end{quote} \end{small} \noindent Beyond the social and emotional aspects of children's lives, a few comments connected these restrictions to developmental and educational harms-namely, how such restrictions impeded learning by depriving them of experiences and learning opportunities: \begin{small} \begin{quote} The internet is where kids discover and learn new things. And by restricting it, you're denying them that ability. \end{quote} \end{small} \noindent\textbf{We don't want to know everything [P]} - Interestingly, the most common comments regarding \textbf{ALL-OR-NOTHING} from parents were the complaints that the app is showing them \textit{too many} things while leaving them with \textit{too few} choices. Parents expressed resentment in terms of wanting to be able to do more tailored controls based on children's individual needs: \begin{small} \begin{quote} You either completely stop your kids from using their phone, or absolutely no rules. It's just so silly, don't they know kids these days need to do homework ONLINE? \end{quote} \end{small} With regard to monitoring features, parents showed confusion and some reported lost in the vast amount of information given by the apps: \begin{small} \begin{quote} I don't want to know everything! What's the point of showing all these location info to me? I'm not a control freak! I just want to protect him from the crazy stuffs online, that's all! \end{quote} \end{small} \noindent \textbf{We do want to know everything [P]} - On the other hand, some parents cherished being able to know every single detail of their children’s lives, and that led on to them expressing multiple opposing views around children's rights to privacy - whether children deserved any rights to privacy at all. One stated that since parents were paying for the phone, they should be able to set the rules: \begin{small} \begin{quote} Don’t listen to these spoiled children. I pay the bills. I control the phone. You want to control you pay the bills! Very very simple equation! It’s a shame how kids here actually can fathom the thought of ``rights'' while living in their parents' home. Who made that joke up? \end{quote} \end{small} \noindent In some cases, parents also talked about how their duty as parents to keep kids safe outweighed any claim to rights: \begin{small} \begin{quote} When it comes to social media, kids don't need privacy. It’s not even about the child as much as it is about others preying on them. I would hope none of the negative reviews are from parents. You should monitor everything your children do. That is our job as parents. \end{quote} \end{small} \noindent A more lenient version of this was the view that rights to autonomy/privacy should be an earned privilege, not a fundamental right: \begin{small} \begin{quote} If you want more trust privacy, prove you can handle it with good choices to show your parents you are trustworthy! \end{quote} \end{small} \noindent Others viewed their children as being too young to make decisions for themselves until they become adults, regardless of their age: \begin{small} \begin{quote} It’s not that we don’t trust them, but studies show they can’t make decisions or assess risk like adults can until age 25 or so. \end{quote} \end{small} \subsubsection{\colorbox{shadecolor!20}{\textit{High Granularity}}} The other extreme along the granularity axis is the feature designs that are highly granular - for this, we specifically refer to the designs that allow parents the freedom to configure apps, websites, videos on a ``per item" basis (\textbf{CONTROL/MONITOR-PER-APP}). Parents were now able (sometimes even required) to refine the specific controls/monitoring they want. \noindent \textbf{Lost in choices due to lack of support [P]} - As we observed earlier, many parents brought up how they'd like to be able to do more refined configurations when they mediate their children's online activities. However, when actually offered with these choices, several of the parents' comments expressed confusion and disappointment regarding these designs. One common complaint was that they simply don't have the time to go through each settings one by one, and they don't have the time to review each app to see if it needs to be banned: \begin{small} \begin{quote} I'm a working mum with a full time job with three kids. Although I appreciate the app designers' efforts in letting us make the decision. It's just not practical for us working parents to go through all the apps one by one. \end{quote} \end{small} \noindent In some cases, parents talked about how frustrated they were as they felt they were indirectly accused as irresponsible parents, and they were ``nudged'' to go back to banning everything: \begin{small} \begin{quote} I don't see the point in letting us choose which videos for children to watch. One, I can't sit through everything they watch, I have a job. Two, 5-year-olds quickly get bored of the old ones and they want more. This so-called ``refinement'' just gave me two choices: either let them watch whatever they want (God knows what's on there), or bans the whole platform. \end{quote} \end{small} \noindent In most cases, parents expressed their needs for supporting resources that help them make restriction/monitoring rules: \begin{small} \begin{quote} I really wish there's something like an app version of the tv age guide. \end{quote} \end{small} \subsubsection{\colorbox{shadecolor!20}{\textit{Medium Granularity}}} Feature designs of \textit{medium} granularity offer a middle ground for parents to mediate their children's online activities, without being too coarse or requires too much effort. Designs like this includes control/monitor based on app/website categories or age ratings; or control/monitor of contacts based on a parent-pre-approved contact; or apps reported and alerted parents only based on ``suspicious'' or ``dangerous'' activities, messages, or content. \noindent\textbf{Protection, not punishment: achieving a successful middle ground [P]} - Parents were generally positive about the apps that offer feature designs of medium granularity, and they saw achieving a successful middle ground being essential for striking a balance between protection and respect for their children. This was seen not only as convenient for parents, but also supporting setting of boundaries in a more flexible manner. Similarly, both parents and children appreciated how some apps enabled different children, especially older ones, with different level of freedom: \begin{small} \begin{quote} I love how this app allows us to reach balance. The app only alerts us when it detects something unusual, we can adjust the things he could access as he gets older. \end{quote} \end{small} \noindent And when such balance was achieved, parents generally saw the parental control apps as effective at helping them support their primary goal, which was to keep their children safe. These parents felt such apps gave them ``peace of mind'': \begin{small} \begin{quote} I love this app. I have a 10 year old son that I just recently found out was doing inappropriate things on the Internet with his phone, like viewing porn [...] but with this app I Have some peace of mind. I have full control of what he downloads and views [...] all form [sic] my device. \end{quote} \end{small} \noindent\textbf{Reasonable safe zone [C]} - Similarly, when app designs managed to help strike a balance between protection and punishment, children regarded them as effective and reasonable at protecting them from dangers online: \begin{small} \begin{quote} Not too bad, I guess a bit boundary is necessary, at least I still have access to things I love. \end{quote} \end{small} \begin{small} \begin{quote} This is just great. It allows age-appropriate control, so giving us more freedom as we get older. \end{quote} \end{small} \subsubsection{\colorbox{shadecolor!20}{\textit{Low Feedback/Transparency}}} A second axis of feature design variation we looked at is feedback/transparency, and how users', especially children's perceptions varied across different designs along this axis. The designs came in various details along their ability of supporting children to have sufficient feedback and transparency, thus to allow them to learn and understand the screen rules, as well as learn more about their own activities online. For \textit{low} feedback/transparency, we refer to the designs that support very little or no means for children to become acknowledged of these things. Typical designs include apps provided no indication about the restrictions enforced on children's phones, leaving them with no idea of the things they could or could not do on their phones; apps did not acknowledge children about what information of them can be seen by parents; and apps only showed prompts at the moment when children were attempting to access content, however, they did not inform children with the screen rules in advance. \noindent\textbf{Insecure, and not respected[C]} - Both children and parents, children in particular, expressed their dislike of feature designs that supported no feedback/transparency, which were sadly the most common feature designs. Rules without prior acknowledgment were sometimes presumed to be annoying by children. For example, both parents and children brought up that prior warnings on time remaining are important. Otherwise, children will feel upset due to the sudden cut-off. Children complained about how some app did not let them know what their screen rules were when such system was missing, and children found themselves in the position of having to work things out based on trial-and-error: \begin{small} \begin{quote} I constantly get these error messages with blank pages, is that part of the screen rules or just an error? \end{quote} \end{small} In terms of monitoring, children felt insecure when not knowing what their parents can see about them: \begin{small} \begin{quote} Can they see all my texts too? That would be creepy. \end{quote} \end{small} \subsubsection{\colorbox{shadecolor!20}{\textit{High Feedback/Transparency}}} Feature designs that were of \textit{high} feedback/transparency includes designs not only provided children with means of viewing/inspecting the restriction policies but also offered a clear explanation on why the screen rules were made and why accessing restricted content might be bad for them. In terms of monitoring, features designs that support high feedback/transparency include the ones that provided children with feedback about their activities (allowing children to do self-monitoring), and offered children with detailed information about each app, including expert reviews and ratings and enabling children to decide what apps are good to use for themselves. \noindent\textbf{Keeping them safe and productive [C]} - Both parents and children liked feature designs that supported children’s understanding of their online boundaries. In terms of restriction, both parents and children brought up how they liked apps offering children with clear screen rule pages so their children would be better informed instead of suffering from being turned down at the moment when they were trying to do some online activities. In particular, many kids pointed out how they liked being offered with explanations on why a website/app was blocked, which made them feel less confused and more respected as a consequence: \begin{small} \begin{quote} Not the best but definitely better than the previous one. Now I know why the websites are blocked. They give you reasons and things like that. I mean, I disagree with them all the time, but at least they tried to show some respect! \end{quote} \end{small} When children understood why the apps were for, they reported more positively about the apps. Several of the comments by children pointed out that the apps helped to keep them safe online from inappropriate things: \begin{small} \begin{quote} I know this may sound crazy from the kids view, but I love this now! It fits me and my phone perfectly, and my mom knows that I am safe on my phone without having to go to any other horrible apps. \end{quote} \end{small} \noindent Other children who suffered from addiction online appreciated how the apps dragged them out of that cycle: \begin{small} \begin{quote} This is AWESOME! I'm a kid so I got this app in order to keep myself in check on my screen time because I am an internet addict. I'm so much happier now! It makes it absolutely impossible to get around! \end{quote} \end{small} \noindent Beyond the positive impacts online, children also appreciated how the apps helped with their time offline. Some children commented that they were now able to become more productive and spend more time with their families: \begin{small} \begin{quote} When my mom and dad put this on my phone and tablet at first I hated it. but then I realised with a limited amount of time I spent more time with my family and do actual work. I hope this inspires you to limit yourself with the amount of time you spend staring at useless junk. \end{quote} \end{small} \noindent\textbf{Supporting them to make own decisions [C]} - In particular, children reported positively about designs that offer them with detailed information (including expert reviews and ratings) of each app. They talked about how they cherish being respected to make their own decisions on what is best for themselves: \begin{small} \begin{quote} They tell you what others said about this app, but let you decide to use it or not – it’s my call. \end{quote} \end{small} \subsubsection{\colorbox{shadecolor!20}{\textit{No/Little Communications Support}}} A third axis of feature design variation was \emph{parent-child communications support}. Specifically, we looked at how features were perceived differently due to the variation of communications support designs they came in with. For \textit{little} communications support, we refer to the designs that first, did not offer any explanation helping children to understand their screen rules, and also, offered none or very little means for children to negotiate screen rules with their parents, leaving them with the only choice - to accept and obey. \noindent\textbf{Role of Parenting Apps: Unnecessary, Punishment, or Lazy Parenting [C]} - When the purpose of these apps were not communicated with children, several of the children's comments expressed confusion or questioned the role these apps in keeping them safe. One child viewed that these apps were fundamentally redundant because they were already old enough or competent enough to keep themselves safe: \begin{small} \begin{quote} I'm a 4.0 student. Who is able to manage her school work and screen time by herself thank you very much. I'm old enough to know what's good and bad, I can't change the settings and there no way to let my mom know that. \end{quote} \end{small} \noindent Other kids lamented that these apps were unnecessary because kids could be told what to do and trusted to keep what they were told. In a sense, the use of apps to force represented a failure of trust. \begin{small} \begin{quote} How bout you try and talk to them about your phone usage first, see if they'll make a change for you first, then go from there. Think twice before you destroy you kid's trust like this. I understand there's kids who need to get their head straight. But for those like me who are focused in school and a well-rounded kid, I feel all you need to do is talk to them. \end{quote} \end{small} \noindent The perception that parents were not trusting them made children question the point of these apps. In some cases, children regarded the use of these apps as purely for punishment. \begin{small} \begin{quote} If you are a parent that wants this app I would reconsider getting this and punish your child a different way. Instead of us being punished, parents should be blamed for dictating their children to use this app. \end{quote} \end{small} \noindent Some children continued to criticise the bad parenting styles that these apps nudged their parents into. Apart from parents being overly-protective (as we previously reported), children also accused parents of being lazy and using the apps as substitutes for parenting. \begin{small} \begin{quote} Yes, it's good to be one step ahead, but having an app to do it for you? You might as well call child protective services if you're that lazy. \end{quote} \end{small} \subsubsection{\colorbox{shadecolor!20}{\textit{High Communications Support}}} Designs that were of \textit{high} communications support mainly came in two ways: first, through features that encouraged communications around the restriction and monitoring policies and through coaching using discussion aides. These includes designs such as apps enabling children to negotiate their rules with their parents, apps providing explicit support that encouraged parents and children to set screen rules together, and apps offering advice to parents - strategies ranging from how to apply restriction/monitoring policies to their children to how to talk about sensitive issues. \noindent\textbf{Feeling of being respected [C]} - When children were given the chance to communicate and negotiate with their parents, they felt they were part of the decision and they generally respected the rules more. In particular, they loved the co-configuration designs that allowed them to sit down with their parents to reach mutual agreement on their boundaries: \begin{small} \begin{quote} My parents sat down with me to go through this ``setting rules together'' thing, and I can send a request to them whenever I felt the restrictions are unfair. Love it! \end{quote} \end{small} \noindent\textbf{Supports, rather than enacts parenting[P]} - Meanwhile, parents also reported their favour towards feature designs that supported or coached them on conversations with their children. And they found designs like parenting tips particularly useful. Some parents felt that they were supported by the app without being hijacked by it. \begin{small} \begin{quote} This is a great tool. Easy to communicate. Easy to adjust. I use this tool to help, but in noway does it replace being a good parent watching over their child. It should not be the only arrow in your quiver, and you should not expect it to do your parenting for you. \end{quote} \end{small} \subsection{Thematic Analysis of Reviews} This section presents an overview of the primary themes pertaining to the reasons children and parents, respectively, liked or disliked features provided by parental control apps. \subsubsection{Children's viewpoints:} We first start with children's perspectives; the children expressed a variety of views on what they hated about parenting apps, which we believe offers a rich starting point for understanding the potential harms and limitations of these apps. \vspace{1em} \noindent\textbf{Disliked being overly surveilled and restricted} - The most common grievance was the view that these apps not only enabled but encouraged parents to set up overly restrictive controls and excessive surveillance. Kids expressed resentment at the extent of both the restrictions and their surveillance, and reflected on the effects lives, welfare, and activities: \begin{small} \begin{quote} This literally blocks everything, I can't even read e-books on my phone. \end{quote} \end{small} \begin{small} \begin{quote} This is insane. Now they can see EVERYTHING! From my browsing history to what apps I downloaded, even my texts! Worst app ever! \end{quote} \end{small} \noindent Kids reflected on a variety of secondary effects of excessive restrictions and surveillance. One child discussed that they felt that, beyond violating their privacy, it was particularly wrong that their parents' access to their messages would compromise their friends' privacy as well: \begin{small} \begin{quote} they can eves drop on your convos and stuff that you dont want them to hear [...] not only is it a violation of my privacy that i didnt permit, but it is of friends too that parents dont know about \end{quote} \end{small} \noindent The pervasiveness and constancy of surveillance made it feel to one as if these apps enabled their parents to ``stalk'' them: \begin{small} \begin{quote} I hate this app my mom is like stalking my life!! \end{quote} \end{small} \noindent Even when not restricted, the perception that their social communications were being surveilled by their parents had a chilling effect that indirectly forced them to cease communicating and be cut off from their friends. \begin{small} \begin{quote} I can't talk with my friends anymore, everything will be recorded! \end{quote} \end{small} \noindent Several comments discussed longer-term effects such restrictions were having on their well-being. One view was that restrictions were directly and immediately harmful because they broke essential lines of social support. \begin{small} \begin{quote} This is stupid. absolutely awful. this will ruin people's lives. I had severe depression and the only thing keeping me from killing my self was my friend who I could only talk to online. Now I'm fine but if I lose contact with that friend I will most likely get my depression back. Horrible and stupid app. \end{quote} \end{small} \noindent Beyond cutting off lines of social support, restrictions were seen to prevent kids from apps and activities that they normally used to cope with boredom and isolation, further undermining well-being: \begin{small} \begin{quote} I can't play a lot of games, and I can't watch YouTube. I've sat in my room for weeks doing nothing and practically getting depressed because there is literally NOTHING I can do! \end{quote} \end{small} \noindent Beyond the social and emotional aspects of children's' lives, a few comments connected these restrictions to developmental and educational harms-namely, how such restrictions impeded learning by depriving them of experiences and learning opportunities: \begin{small} \begin{quote} The internet is where kids discover and learn new things. And by restricting it, you're denying them that ability. \end{quote} \end{small} \noindent\textbf{Role of Parenting Apps: Unnecessary, Punishment, or Lazy Parenting} - A second theme related to the roles parenting apps were meant to play. Several of the children's comments expressed confusion or questioned the role these apps were supposed to play in keeping them safe. One view that these apps were fundamentally redundant because they were already old enough or competent enough and to be able to keep themselves safe: \begin{small} \begin{quote} I'm a 4.0 student. Who is able to manage her school work and screen time by herself thank you very much. I'm old enough to know what's good and bad, but my mom just doesn't understand that. \end{quote} \end{small} \noindent Other kids lamented that these apps were unnecessary because kids could be told what to do, and trusted to keep what they were told. In a sense, the use of apps to force represented a failure of trust. \begin{small} \begin{quote} How bout you try and talk to them about your phone usage first, see if they'll make a change for you first, then go from there. Think twice before you destroy you kid's trust like this. I understand there's kids who need to get their head straight. But for those like me who are focused in school and a well-rounded kid, I feel all you need to do is talk to them. \end{quote} \end{small} \noindent The perception that parents are not trusting them made children question the point of these apps. In some cases, children regarded the use of these apps as purely for punishment. \begin{small} \begin{quote} If you are a parent that wants this app I would reconsider getting this and punish your child a different way. Instead of us being punished, parents should be blamed for dictating their children to use this app. \end{quote} \end{small} \noindent Some children continued the criticise the bad parenting styles that these apps nudged their parents into. Apart from parents being overly-protective (as we previously reported), children also accused parents of being lazy and using the apps as substitutes for parenting. \begin{small} \begin{quote} Yes, it's good to be one step ahead, but having an app to do it for you? You might as well call child protective services if you're that lazy. \end{quote} \end{small} \noindent\textbf{Perceived benefits: Keeping them safe and productive} - When children understand why the apps are for, they reported more positively about the apps. Several of the comments by children pointed out that the apps helped to keep them safe online from inappropriate things: \begin{small} \begin{quote} I know this may sound crazy from the kids view, but I love this now! It fits me and my phone perfectly, and my mom knows that I am safe on my phone without having to go to any other horrible apps. \end{quote} \end{small} \noindent Other children who suffered from addiction online appreciated how the apps dragged them out of that cycle: \begin{small} \begin{quote} This is AWESOME! I'm a kid so I got this app in order to keep myself in check on my screen time because I am an internet addict. I'm so much happier now! It makes it absolutely impossible to get around! \end{quote} \end{small} \noindent Beyond the positive impacts online, children also appreciated how the apps help with their time offline. Some children commented that they are now able to become more productive and spend more time with their families: \begin{small} \begin{quote} When my mom and dad put this on my phone and tablet at first I hated it. but then I realised with a limited amount of time I spent more time with my family and do actual work. I hope this inspires you to limit yourself with the amount of time you spend staring at useless junk. \end{quote} \end{small} \subsubsection{Parents' views and counterpoints} In this section, we report a subset of themes of parents' reviews that correspond to major themes, and those that represent counterpoints to the children's themes above. \noindent\textbf{Peace of mind, protection not punishment} - Parents were generally positive about the apps, generally seeing parental control apps as effective at helping them support their primary goal, which was to keep their children safe. These parents felt such apps gave them ``peace of mind'': \begin{small} \begin{quote} I love this app. I have a 10 year old son that I just recently found out was doing inappropriate things on the Internet with his phone, like viewing porn [...] but with this app I Have some peace of mind. I have full control of what he downloads and views [...] all form [sic] my device. \end{quote} \end{small} \noindent With regard to children feeling punished, some parents showed awareness of this perception and provided advice to others about how to avoid it. One advocated for discussing the purpose of the tool with the child to frame it within an educational and protective context: \begin{small} \begin{quote} Talk with them about the reason you’re doing this. Allow your kids to help you set limits and rules. Show them you trust them. Emphasize it as a tool for them to stay safe and to learn important skills, rather than simply a way to punish them. \end{quote} \end{small} \noindent Other parents struggled to communicate this, expressing that their children indeed felt punished: \begin{small} \begin{quote} I want to make sure no more creeps are following her. I took away all of her access to her electronics and she felt like she was being punished! She didn’t do anything wrong, so she shouldn’t have to feel that way! Hopefully, one day she will see the bigger picture... \end{quote} \end{small} \noindent\textbf{Supports, rather than enacts parenting}- One parent felt it was necessary to remind other parents to see such apps merely as one of an arsenal of tools to retain an active involvement in parenting: \begin{small} \begin{quote} This is a great tool. Easy to use. Straightforward. Just enough options. I use this tool to help, but in noway does it replace being a good parent watching over their child. It should not be the only arrow in your quiver, and you should not expect it to do your parenting for you. \end{quote} \end{small} \noindent \textbf{Diverse attitudes: Privilege not a right} - Parents expressed multiple opposing views around children's rights to privacy. Several expressed sympathy, saying they exercised caution and tried to be respectful in the use of restrictions and monitoring features, negotiating rules in advance: \begin{small} \begin{quote} This app is perfect. We do homeschooling, and we know it’s important to let our kids stay connected with their friends. We adjusted the setting so that our kids can still chat online during scheduled study times...” \end{quote} \end{small} \begin{small} \begin{quote} For best results, track your kids' usage for a while before limiting anything, and when restricting usage, have the discussion about what’s reasonable so you can come to an agreement. Resist the temptation to go \emph{full fascist} right away even though you are probably extremely frustrated when you finally download this app. \end{quote} \end{small} \noindent An opposing view was expressed by some parents who questioned whether children deserved any rights to privacy at all. One stated that since parents were paying for the phone, they should be able to set the rules: \begin{small} \begin{quote} Don’t listen to these spoiled children. I pay the bills. I control the phone. You want to control you pay the bills! Very very simple equation! It’s a shame how kids here actually can fathom the thought of ``rights'' while living in their parents' home. Who made that joke up? \end{quote} \end{small} \noindent In some cases, parents also talked about how their duty as parents to keep kids safe outweighed any claim to rights: \begin{small} \begin{quote} When it comes to social media, kids don't need privacy. It’s not even about the child as much as it is about others preying on them. I would hope none of the negative reviews are from parents. You should monitor everything your children do. That is our job as parents. \end{quote} \end{small} \noindent A more lenient version of this was the view that rights to autonomy/privacy should be an earned privilege, not a fundamental right: \begin{small} \begin{quote} If you want more trust privacy, prove you can handle it with good choices to show your parents you are trustworthy! \end{quote} \end{small} \noindent Others viewed their children as being too young to make decisions for themselves until they become adults, regardless of their age: \begin{small} \begin{quote} It’s not that we don’t trust them, but studies show they can’t make decisions or assess risk like adults can until age 25 or so. \end{quote} \end{small} \noindent\textbf{Other concerns: privacy and disclosure to third parties}- Similarly, a few children reflected on how much access to private data apps had, and that their use represented a fundamental violation of what they were taught about being cautious with apps accessing personal info at school: \begin{small} \begin{quote} My school kept telling us to protect our personal information online, but what parents did here directly contradicts what I was told. (K) \end{quote} \end{small} \noindent Parents similarly expressed privacy concerns relating to the potential for developers of parenting apps to collect and abuse information about their children's' behaviour sensed and collected through the app: \begin{small} \begin{quote} Forget the children's privacy for a moment. How much DATA MINING is this company doing?? They are not only getting all your information from FB, but they also learn everything about your child\'s behavior. This app isn't meant for the parents. It's meant for the company to harvest data. \end{quote} \end{small} \noindent Parents also criticised how heavy surveillance on children would train them into the mindset of getting used to, thus not caring about personal information as they grow up: \begin{small} \begin{quote} Considering how little privacy we have left, I fell this app is training kids to feel ok with the fact their data is being spread all over the internet by advertisers and making it normal to feel like there is no privacy. (P) \end{quote} \end{small} \subsection{How do features relate to perceptions?} \begin{figure}[h!] \caption{\emph{Mapping feature analysis to perceptions-} Here we connect all the variations of app features along each of the 3 axes against reviews about them, and indicate whether children and parents primarily viewed such features \emph{positively}, \emph{negatively} or \emph{conflicted}, or expressed no view (x). \label{fig:mapping}} \label{fig:compare} \centering \includegraphics[width=1\textwidth]{mapping.png} \end{figure} Thus far, we have analysed apps and how features varied along three axes in Section 4.1, and, separately, thematically coded perceptions of parenting apps by both parents and children in Section 4.2. In this section, we aim to understand how particular aspects of how features are realised (along the axes of variation), and how that maps to parents and children's perceptions. We use a grounded approach to code our reviews. However, interesting matching between our previous feature analysis and users' perceptions (reviews) can be identified (see \textbf{Figure \ref{fig:mapping}}). \subsubsection{Granularity} \begin{itemize} \item Both parents and children disliked the coarsest level of granularity, \emph{all-or-nothing}, corresponding to over 30\% of apps (\scalebox{0.5}{ALL-OR-NOTHING}32\%) \item Both parents and children liked apps providing an \emph{intermediate level of granularity}, which usually consisted policies based on meaningful/convenient sets, which were approximately as common as the previous category \\(\scalebox{0.5}{CONTROL-CATEGORY-AGE}32\%, \scalebox{0.5}{MONITOR-CATEGORY}18\%, \scalebox{0.5}{MONITOR-SUSPICIOUS}16\%) \item Children disliked apps providing highly granular controls, while some parents strongly liked these. Such designs are prominent in apps( \scalebox{0.5}{CONTROL-PER-APP}34\%, \scalebox{0.5}{MONITOR-EXPLICIT-INFO}40\%): \end{itemize} Both parents and children disliked when apps only offered control in an all-or-nothing fashion. They criticised such apps as unreasonable, inconvenient and annoying. On the other hand, most children didn't like apps providing the most granular affordances, especially in terms of monitoring, which enabled their parents to see very detailed information. Interestingly, parents held conflicted opinions; while some expressed sympathy and reported that they didn't want to know ``everything'', others cherished being able to know every single detail of their children's lives. In terms of restriction, whilst some parents loved being able to adjust the setting on a per-app/website basis, others complained about the effort and knowledge required from them to do that. Most parents and children liked intermediate levels of granularity, which consisted of apps supporting controls grouped into meaningful categories, such as app genres and categories, age-appropriateness, and support for filtering monitored data for only `suspicious content'. This was seen not only as convenient for parents, but also seen to support setting of boundaries in a more flexible manner. Similarly, both parents and children appreciated how some apps enabled different children, especially older ones, with different level of freedom: \begin{small} \begin{quote} This is just great. It allows age-appropriate control, so giving us more freedom as we get older. (K) \end{quote} \end{small} \subsubsection{Feedback/Transparency} \begin{itemize} \item Both parents and children dislike features that support little feedback/transparency. However, such features are prominent (\scalebox{0.5}{RULES-NO-SHOW}14\%, \scalebox{0.5}{MONITOR-NO-SHOW}32\%, \scalebox{0.5}{ONLY-RULES-AT-MOMENT}20\%) \item Both parents and children agreed features should support feedback/transparency. However, only 20\% apps offer these (\scalebox{0.5}{RULES-PAGE}12\%, \scalebox{0.5}{MONITOR-PAGE}8\%) \item Both parents and children like features that have high feedback/transparency. However, such features are largely scarce (\scalebox{0.5}{RULES-EXPLAIN}6\%, \scalebox{0.5}{MONITOR-SELF-TRACK}14\%, \scalebox{0.5}{SHOW-KIDS-INFO}4\%) \end{itemize} Both children and parents expressed their dislike of feature designs that supported no feedback/transparency, which were sadly the most common feature designs. In terms of screen rules, they complained about how some app doesn't let children know what their screen rules are when such system is missing, children found themselves in the position of had to work things out based on trial-and-error. In terms of monitoring, children felt insecure when not knowing what their parents can see about them. Rules without prior acknowledgment were sometimes presumed to be annoying by children. For example, both parents and children brought up that prior warnings on time remaining are important. Otherwise, children will feel upset due to the sudden cut-off. Both parents and children liked feature designs that supported children's understanding of their online boundaries. In terms of restriction, both parents and children brought up how they like apps offering children with clear screen rule pages so their children will be better informed instead of suffering from being turned down at the moment when they are trying to do some online activities. In particular, Many kids pointed out how they like being offered with explanations on why a website/app is blocked, which made them feel less confused and more respected as a consequence: \begin{small} \begin{quote} Not the best but definitely better than the previous one. Now I know why the websites are blocked. They give you explanations and things like that. I mean, I disagree with them all the time, but at least they tried to show some respect! (K) \end{quote} \end{small} Some apps also showed children with their detailed online activities (rather than just a page on the list of things that will be monitored). Through this process, children were also acknowledged of their digital use online. Both parents and children reported this as helping to raise children's awareness of their time online, thus helped them make more informed decisions on their time: \begin{small} \begin{quote} It is just a simple way to track your phone usage. It has helped me be more aware of how much I spend on my phone, and I do spend too much time on games sometimes. It has helped me lessen that amount. I love this app! (K) \end{quote} \end{small} \subsubsection{Communications Support} \begin{itemize} \item Both parents and children disliked apps that failed to support any communication. While nearly 70\% of apps fall into this category (\scalebox{0.5}{DONT-KNOW-EXIST}14\%, \scalebox{0.5}{NO-MEANS}54\%) \item Both parents and children liked features that support some communication. While only around 30\% of apps support that (\scalebox{0.5}{SEND-MESSAGE}18\%, \scalebox{0.5}{REWARD}12\%, \scalebox{0.5}{BOTH-DEVICE}2\%) \item Parents in particular, loved features that support active parenting. However, limited apps offer these features (\scalebox{0.5}{CO-CONFIG}4\%, \scalebox{0.5}{PARENTING-TIPS}10\%) \end{itemize} Most apps offered no means for negotiating screen rules (54\%), which is disfavoured by both parents and children. They complained about how inconvenient it was, especially when parents could not physically adjust settings in person. In general, parents and children liked designs that supported any form of communication. Whether it's a negotiation on screen time through a reward system, or simply having a send message function to alter the settings. Children, in particular, loved the co-configuration designs that allowed them to sit down with their parents and reach mutual agreement on their boundaries. Meanwhile, parents also reported their favour towards feature designs that supported or coached them on conversations with their children. And they found designs like parenting tips particularly useful. For feature designs in this group, parents and children hole quite similar opinions. They either both loved it, or both hated it. Interestingly though, the reason they liked the reward systems was quite different. While children talked about how they love the fun or getting used to the reward systems, parents tend to think that their children learned important internal values throughout the process, such as self-discipline or being responsible: \begin{small} \begin{quote} I am a kid, and I think it's awesome because your parents can block you at certain times, and you can do things to earn more time.;-) It's super fun! P.S. Kids, if u don’t like it, u must be messed in the head! It's such a great app!!!;- (K) \end{quote} \end{small} \begin{small} \begin{quote} They WANT to do their chores to earn more screen time :) It is teaching them time management, and they are more responsible with their tablet use now. (P) \end{quote} \end{small} \begin{wrapfigure}{r}{0.5\textwidth} \begin{center} \includegraphics[width=0.5\textwidth]{practices.png} \end{center} \caption{\textit{Most and Least Favoured Design Practices} - Here we plot the apps under three axes of variations, the level of granularity is represented by different shades of colour\label{fig:practices}} \end{wrapfigure} \subsubsection{Most and Least favoured combinations by Parents and Children} \hfill \break Mapping our feature analysis with review analysis, we concluded the most and least favoured combinations of feature designs (see \textbf{Figure \ref{fig:practices}}): \begin{itemize} \item Least Favoured, were the apps with feature designs low on all three dimensions: low granularity, low feedback/transparency, and low communications support. \item Most Favoured were the apps with feature designs high on both feedback/transparency and communications support, while offering a medium level of granularity. \end{itemize} \section{Discussion} \subsection{Connecting Feature Designs to Parental Mediation Theory} Given the potential for both detrimental and beneficial effects of restriction and monitoring, and the likelihood that these strategies will remain important aspects of many parents' mediation strategies for the foreseeable future, can we strike a balance? Specifically, how might apps play a role in fostering a more responsible, considered, and appropriate use of these strategies? To answer these questions, we first reflect on whether some of our findings related to the feature design space described in Section \ref{subsection:threeaxes} might help. The three axes deal with very different aspects of parenting support and thus take each in turn. Starting with the first axis, \emph{granularity} was associated with the degree and detail with which parents could control and monitor children's activities. This axis was directly related to the ``restrictive mediation” from parental mediation theory ~\cite{livingstone2008parental}. Beyenes et al.~\cite{beyens2017parent} found that restrictive mediation leads to increased conflicts between parents and children . Nathanson~\cite{nathanson2013media} argued that children might exhibit more disobedience and rebelliousness against parents under restrictive mediation . Ghosh et al.~\cite{10.1145/3173574.3173768} also found that teens who were victimized online and had peer problems were more likely to be controlled and monitored by their parents. These previous findings reinforce our analysis, such that a balance between restriction and children’s autonomy is much needed. The use and application of highly granular restrictions provides more flexibility for the parents but they can also be seen as overly demanding - parents need to be familiar with all the apps and websites their children could possibly access. On the other hand, the coarsest (all-or-nothing) controls were generally seen as less desirable because such apps denied children access to basic, risk-free, and unproblematic aspects of their devices that they deemed essential. The former takes a parent-centric view whilst permits limited inputs from children; and the latter is a close representation of an authoritarian parental approach ~\cite{darling1999parenting}, which has been deemed to decrease children and parents’ mutual trust and the development of children’s self-autonomy~\cite{10.1145/3173574.3173768, mensah2013influence} Various kinds of “medium granularity” identified in this research (e.g controlling by categories) were deemed most favoured by many parents because of the simplicity such granularities afford. Such abstractions encourage slightly less parental involvement because of the way they homogenise the treatment of different apps in the same category; without requiring parents to be deeply involved with the particular risks, details or benefits of specific apps. With respect to \emph{transparency/feedback}, this axis dealt with the extent to which children remain informed of their own online activities and screen policies. By clearly establishing what was being restricted, monitored, and why, children could understand the boundaries of their parents' control so that they could negotiate their activities within and around such barriers. As such, this axis was most directly aligned with aspects of active \emph{self-regulation} ~\cite{fingerman2011handbook, kopp1982antecedents, moilanen2015bidirectional} but it's more than that - through empowering children with information and choices about their own behaviors online, as well as supporting resources such as information or expert ratings on particular apps, children were given the opportunity to make more responsible decisions for themselves - one of the key outcomes from an active mediation approach ~\cite{shin2017does}. Less feedback and transparency could be seen as \emph{more privacy-invasive and autonomy restrictive}, making it less clear or visible when and what parents would be watching. Much like Bentham's panopticon ~\cite{strub1989theory}, less transparency can be seen as undermining children's rights by creating a perpetual spectre of possible observation. Regarding \emph{communications support}, this axis was most closely related to the ``active mediation” from parental mediation theory, in which communication is the core ~\cite{livingstone2008parental, lee2007children, nikken2014developing}. Previous studies found that active mediation was associated with lower levels of aggression children ~\cite{collier2016does}, and that active mediation may reduce online risks without hindering children's online opportunities ~\cite{duerager2012can, wisniewski2015preventative}. Kuppens et al.~\cite{kuppens2019parenting} found that children who experienced frequent discussions about online activities with parents were more likely to regard control/monitoring as legitimately in their best interests . While being closely related to active mediation, this axis was more than that. It dealt with providing supports for parent-child interactions in several forms; one was parental informational support, which comprised both \emph{general parenting advice} pertaining to ways to talk to children about their online activities and risks, and \emph{specific information} about particular apps and activities. Other support includes encouraging the co-setting of restrictions and monitoring practices, allowing children to be involved in the configuration of such activities, and can have significant benefits in terms of how they view such activities as a result ~\cite{kuppens2019parenting}. We contend that granular restrictions and monitoring support active/authoritative parenting \mbox{\cite{darling1999parenting}} by increasing the flexibility and means by which parents can remain in-the-loop of, and control over, children's activities. However, we argue that our finding shows that this is only true for apps which also had a high degree of \emph{transparency/feedback} (axis 2), as well as high \mbox{\emph{communications support}} (axis 3). Such capabilities are essential for enabling children to understand restrictions, monitored activities, and goals (transparency/feedback), providing a means of understanding of the context and purpose of these restrictions, and a means of digitally facilitating discussion, negotiation, or relaxation of such policies (communications support). Without such feedback, monitoring and restrictions are most directly aligned to \mbox{\emph{authoritarian parenting}} \mbox{\cite{ford1985factors, darling1999parenting}} by enabling precise control and detailed monitoring without associated feedback, transparency, or support for negotiation or communications. Parental mediation theory categorised parental mediation strategies into distinct types, namely restrictive, monitoring and active ~\cite{livingstone2008parental}. However, a new view of parental mediation as a continuous, dynamic process is supported by recent empirical and theoretical literature, including work by Symonds et al.~\cite{symons2017parental}, who proposed that parental mediation be viewed as a dynamic integrative process that brings strategies into the daily interactions between parents and children. Other studies that support this view similarly found that parents tended not to use restrictive, monitoring, or active mediation strategies independently, but in ways that supported each other~\cite{beyens2017parent, meeus2018managing}, while Chen et al.~\cite{chen2016active} suggested that mediation such as restriction and monitoring were most effective when they were implemented in an active way. Our findings reinforced this new look of the parental mediation approaches: restrictive and active mediations are not in and of themselves good or bad; rather, their effectiveness may be highly dependent on the style in which parents apply these strategies with their children ~\cite{valkenburg2013developing, chen2016active}. The feature designs along three axes (granularity, transparency/feedback, communications support) align perfectly with these arguments - instead of considering features as separate categories, the axes of variation reflect the designs on how strategic elements can be combined, and implemented in a lesser or greater extent - overlapping and reinforcing each other, in an overall dynamic process. \subsection{Revisiting the TOSS Framework} \begin{figure}[h] \centering \includegraphics[width=1\textwidth]{revisit.png} \caption{Revisiting the TOSS Framework. a). The TOSS framework looks at \textit{what} features are supported b). Our Axes of Variation complement the TOSS framework by adding orthogonal dimensions of \textit{how} features were implemented. c). As a result, our three axes of variation allow us to identify a \textit{Zone of Best Practice}, this also shows that most of the apps on the current market fall outside of this zone.} \label{fig:rev} \end{figure} Our analysis offered empirical evidence that suggests that the ways in which features are designed influence users' perceptions of features in parental control apps. In particular, we found that parents and children's perceptions of features varied significantly across the three axes designs variation. For example, for a single restriction feature such as APP-BLOCK, when implemented differently, such with features for supporting parents-child negotiation, were viewed more positively than when apps offered no such means at all. Instead of viewing app features as belonging to separate independent mediation strategies as TOSS does, we prefer to view such features as playing variable roles in mediation strategies articulated by many factors including their design. We feel that our axes of variation can be seen as an extension to the TOSS framework, orthogonal to its categorisation of features by strategy, that provides a view to the ways such features should be designed. In particular, by looking at the areas along each of the axes that correspond to the most positive comments, we can identify a \textit{Zone of Best Practice}, corresponding to the regions of the feature design space viewed most positively by parents and children. For \textit{granularity}, the designs that were of medium level of granularity were perceived as helping to strike a balance between protecting children online, while leaving them with enough space to learn and explore online - such designs include configurations on categorical level or age ratings, managing contacts based on a parent-pre-approved list, or only alerting parents when ``suspicious'' or ``dangerous'' activities were identified. For \textit{feedback/transparency}, the most welcomed designs were those that provided support for children to remain informed of their screen rules, their own activities online, and support them to make decisions for themselves online - good design practices include panels that show children explicit information on their own online activities, pop ups that explain why certain screen rules were made for them, and info panels that offer children with detailed information of each app, thus enabling themselves to decide what apps to use. For \textit{communications support}, the most welcomed designs were those that encourage negotiation between parents and children, and support parents with information and resources to start those conversations - e.g. co-configuration panels that encourage parents and children to set screen rules together, pop up parenting tips that offer advice to parents. Unfortunately, our analysis also found that most existing apps fell outside this zone for many of their features. \subsection{Opportunities for more autonomy-supportive parental mediation} One of the major problems with restriction and monitoring is the extent to which these strategies reduce children's autonomy and violate their privacy. How might apps be made to be more autonomy-supportive, especially in the long term? Our view is that the inherent problem with the parental control apps we reviewed is that they were focused exclusively on effective restriction and monitoring, instead of digital parenting. Instead of framing restrictions and monitoring as protective measures to be used in perpetuity, for instance, a digital parenting app might not only include support for other TOSS strategies (such as impulse control), but also re-frame restriction and monitoring as a means of skills scaffolding \cite{hammond2012effects, bibok2009parental}. Starting with the most supportive scaffolding (maximum restrictions and monitoring) for the very young and most vulnerable, such apps could then align the gradual removal of restrictions and monitoring measures with milestones as children get older, or demonstrate the ability to recognise and cope with online risks. Then, as their needs for autonomy and privacy needs change, typically peaking by mid-teenage years~\cite{arnett2000emerging}, such restrictions should probably reach a minimum at such an age. However, if children require special support such scaffolds could be seen as flexible as needed. Such a re-framing would address several of the children's comments we found, especially relating to children seeing restrictions as pointless and infantilising, and supporting them as they grow older, so as to not be seen to hold them back. Another re-framing that might provide protection against overuse of restriction and monitoring is to frame such measures as options of last resort, after other more autonomy-confirming strategies fail. Primary autonomy-confirming strategies for older children might instead include, for example, simple verbal agreements about limits on online activity which require children to take responsibility for their actions. Such a shift would be in line with the literature on autonomy-supportive parental mediation, which requires a ``convincing rationale for rule-making''~\cite{haddon2015children}. We propose that similarly, requiring a convincing rationale to justify the use of restriction and monitoring features might ensure that they are used only as necessary. \section{Limitations and Future Work} There are several important limitations of this work; the first pertains to the app analysis; our sample of parental control apps were taken only from the Android UK Google Play store, and thus may vary significantly by region. Due to a feasibility constraints we were only able to analyse 58 of these apps, out of the massive growing pool available. The second most significant limitation is that we based our analysis on reviews available in the wild. There are obvious limitations of trying to use reviews as ``vessels of truth''; namely, they could be fabricated by bots, or, even if genuine, could represent a skewed non-representative sample of particularly angry or passionate people. We attempted to mitigate some of these possibilities several ways, one was by using a process of filtering reviews to carefully select only those discussing specific aspects of apps. Moreover, we avoided deriving any conclusions through quantitative measures which would be distorted; instead, we used reviews only to collate reasoned perspectives about features. Nonetheless caution should still be exercised using any app reviews for deriving any sort of definitive conclusions about causal relationships, for instance, relating app use to children's welfare or safety. Our contributions thus should be interpreted as a high-level understanding of the design space of features of parental control apps, with evidence that might suggest regions most promising for further exploration. Our future work would involve actually working with parents and children to get more direct inputs. We hope our contributions could guide others navigate the space of parental control apps, for running field studies of the effectiveness of specific feature designs. Apart from that, this work adopted a ground-up approach as well as being guided by the TOSS framework, instead of a value-driven approach. Therefore, we did not take a full consideration of the different cultural and parenting styles intrinsically embedded in different cultures and societal values, which would benefit from future work. \section{Conclusion} Parental control apps are being increasingly seen as the answer to online safety concerns parents have for their children~\cite{ofcom2019}. However, increasing evidence suggests that such apps may be bringing with them new kinds of harms associated with excessive restrictions and privacy invasion~\cite{wisniewski2017parental, ghosh2018safety}. This paper is the first to contribute an understanding of the design space of the mediation features of current parental control apps. Then, to identify how such variation might articulate the use of these apps in practice, we analysed reviews corresponding to features at various points along each of the axes. Our findings suggest that apps providing the most transparency and feedback, the greatest support for parent-child communications, and flexible categories are most likely to be perceived by both parents and children in positive ways instead as punitive and detrimental. Contextualising our findings in parental control theory, we derive at least two approaches that more autonomy-supportive parental control apps might be achieved. The first, by simply designing app features to fall along each of the three axes within our identified ``zone of best practice''--designs perceived most positively by both parents and children. Second, to complement and pair restriction and monitoring features in an age and skill-appropriate manner. This includes gradually allowing children to move from strictest monitoring and restriction features to gain more autonomy, as they develop necessary skills associated with recognising and mitigating online risks. \section{Appendix} \begin{figure}[H] \centering \includegraphics[width=1\textwidth]{applist.png} \caption{App List with Icons} \end{figure} \begin{figure}[H] \centering \includegraphics[width=1\textwidth]{codebook.png} \caption{Final Codebook for Reviews. Reviews were first organised using Feature Designs Codebook we previously compiled in Section \ref{subsubsection:methodFeatureDesign}. Then, we used a grounded, thematic approach~\cite{wildemuth2016applications} to identify themes about why a parent or a child liked or disliked that feature design.} \end{figure}
{'timestamp': '2021-09-14T02:15:57', 'yymm': '2109', 'arxiv_id': '2109.05347', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05347'}
arxiv
\section{Introduction} \label{sec:intro} Advancements in deep learning have brought performance improvements in acoustic and language modeling, yielding robust automatic speech recognition (ASR) systems in many languages. However, such systems require a large amount of speech data and the associated transcriptions. It is tough to collect large volumes of paired speech and transcriptions for most low-resource languages. It is estimated that only about 1\% of the world languages have the minimum amount of data that is needed to train an ASR \cite{low-resource}. However, in many cases, especially for languages in south Asia, we can find a ``close enough'' language with the same set (or a superset) of phonemes as the low-resource language and enough resources for building an ASR. In this work, we show that a better performing ASR can be built for the low-resource language using unsupervised domain adaptation (UDA) of acoustic models from the corresponding high-resource language. This method has the benefit of modeling on real data in comparison to the data augmentation techniques like vocal tract length perturbation \cite{vltp, vltp2}, speech and tempo perturbation \cite{audio_aug}, noise addition \cite{deepspeech}, data synthesis \cite{low_res_data_aug}, and spectral augmentation \cite{specaug}, where the modeling makes use of the synthetic data as well. Unsupervised domain adaptation (UDA) has been successfully applied to various tasks to alleviate the shift between the train and test distributions. \cite{ganin} shows good adaptation performance in the classification task on digit image datasets having considerable domain shifts. They learn features that are discriminative for the image classification task and invariant to the domain. They introduce a gradient reversal layer (GRL) for achieving this objective. \cite{gender_accent_shift} reports performance improvements in speech recognition for data shifted in the domain by gender and accent. \cite{emo1} employs GRL layers to reduce the mismatch between train and test domains in the task of emotion recognition from speech data. \cite{speech} uses the GRL approach to improve the word error rate (WER) in speech recognition with the source domain data as clean speech and the target domain data as contaminated speech. They also show the robustness of the approach to the domain shifts caused by the differences in datasets. The basic UDA scheme with a GRL tries to learn domain invariant features but ignores the individual characteristics of each domain. \cite{dsn} introduces domain separation networks (DSN) and shows improvements in a range of UDA scenarios in the image classification task. They learn two representations: one specific to each domain and the other common to both domains. \cite{dsn_clean2noisy} uses DSN for adaptation from clean speech to noisy speech. In this work, we explore the feasibility of the UDA schemes in the ASR task on low-resource languages that share the same acoustic space with a high-resource language. Specifically, we place the following assumptions in the selection of high and low resource language pairs. \begin{enumerate} \item The acoustic space spanned by the low-resource language is a subspace of that of the high-resource language. This requires the phoneme set of the low-resource language to be a subset of the high-resource language. \item There exists a high-resource language with reasonable amount of paired audio data and transcriptions to build an ASR. \item The low-resource language has enough text data available to train the language models. \item The speech data available in the low-resource language is quite limited, and the transcriptions are not available. \end{enumerate} Though the above assumptions seem quite constrictive, we can easily find a few low-resource languages in the Indian subcontinent which share a common acoustic space with a reasonably high-resource language. In this work, we use Hindi as the high-resource language and Sanskrit as the low-resource language, both belonging to the Indo-Aryan language family. Hindi is written in the Devanagari script, and many of its words are derived from Sanskrit. However, there exist substantial differences in the vocabulary and pronunciation between the two languages. One of the important differences is that the schwa, implicit in each consonant of the script, is not pronounced at the end of words and in some other contexts in Hindi. The script does not tell us when the schwa should be deleted, a phenomenon known as schwa deletion. For example, the word for "salty" is pronounced as \textit{nam'kīn} in Hindi and not \textit{namakīna}. Another difference is the pitch accents that are common in Sanskrit. Despite the above differences, these languages share a common phoneme set. So we can intuitively argue that there exists a domain shift between the distributions of acoustic features in Hindi and Sanskrit. This makes us believe that the speech recognition problem in Sanskrit, an extremely low-resource language, may be posed as an UDA problem from Hindi, a language with a reasonably good collection of annotated audio. \section{Unsupervised domain adaptation for acoustic modeling} \label{sec:uda} We pose the problem of acoustic modeling in Sanskrit as an unsupervised domain adaptation task from Hindi. We build a deep neural network (DNN) - hidden Markov model (HMM) ASR system \cite{dnn-hmm} for Sanskrit with the domain-independent acoustic models learned from Hindi through UDA approaches. We make use of the UDA schemes introduced in \cite{ganin} and \cite{dsn}. \begin{figure}[t] \centering \includegraphics[width=1\linewidth, height =0.6\columnwidth]{dda.pdf} \caption{Block diagram of the basic scheme for unsupervised domain adaptation with a gradient reversal layer (GRL). $\theta_f$, $\theta_y$ and $\theta_d$ represent the parameters of the feature extractor, senone classifier, and domain classifier, respectively.} \label{fig:blockdiagram} \end{figure} \begin{figure*}[htb] \centering \includegraphics[scale=0.8]{dsn.pdf} \caption{Block diagram of the domain separation network to model private and shared components. } \label{fig:dsn} \end{figure*} \subsection{Adversarial training using GRL} \label{sec:grl} In GRL-based adversarial training, we try to learn a feature representation invariant to the domain, but good enough in discriminating the senone labels. The neural network architecture for learning the acoustic model consists of three parts: feature extractor, senone classifier, and domain classifier. A block diagram of the UDA architecture employing GRL is shown in Fig. \ref{fig:blockdiagram}. Feature extractor $G_f$ maps the input acoustic features $\mathbf{x}$ to an internal representation $\mathbf{f} \in \mathcal{R}^D$. Senone classifier $G_y$ maps the output of the feature extractor to the senone labels $\mathbf{y}$ whereas the domain classifier $G_d$ maps them to domain labels $\mathbf{d}$. We train the network to minimize the senone classification loss during the training phase by optimizing the parameters in the feature extractor $G_f$ and senone classifier $G_y$. This makes the network look for features that are capable of discriminating the senone labels. To make the features domain-invariant, we optimize the parameters of the feature extractor to maximize the domain classification loss. But at the same time, the parameters of the domain classifier $G_d$ are optimized to minimize the domain classification loss. This is achieved by introducing a GRL between the feature extractor $G_f$ and domain classifier $G_d$. During the forward pass, GRL acts as an identity transform. GRL takes the gradient from the subsequent layer during the backward pass, multiplies it with $-\alpha$, a hyperparameter to control the trade-off between senone discrimination and domain-invariance, and passes it to the preceding layer. During the inference time, the domain classifier and GRL are ignored. The acoustic feature vectors are passed through the feature extractor and the senone classifier, and senone labels are predicted. \subsection{Domain separation networks} \label{sec:dsn} A block diagram of the DSN architecture is shown in Fig. \ref{fig:dsn}. They model both the private and shared components of the domain representation. Private encoders $E_p^t(.)$ and $E_p^s(.)$ extract components $f_p^t$ and $f_p^s$ which are specific to the target and source domains. Shared encoder $E_c(.)$ is common to both domains and extract the shared components $f_c^t$ and $f_c^s$ . Shared decoder $D$ tries to reconstruct the input using the private and shared components. $G(.)$, the senone classifier maps $f_c^s$ to the senone label $\mathbf{\hat{y}}$. The domain classifier $Z(.)$ maps the shared components $f_c^s$ and $f_c^t$ to their respective domain labels $\mathbf{\hat{d}}$. The network is trained to minimize the following loss function with respect to the parameters of $E_p$, $E_c$, $G$ and $Z$: \begin{equation} L = L_{class} + {\beta} L_{sim} + {\gamma} L_{diff} + {\delta} L_{recon} \end{equation} where $\beta, \gamma$, and $\delta$ are hyperparameters. $L_{class}$ represents the senone classification loss and is applied only to the source domain. It is computed as the negative log-likelihood of the ground-truth senone labels. $L_{sim}$ represents the domain adversarial similarity loss and is computed as the negative log-likelihood of the domain labels. $L_{sim}$ ensures that the shared components $f_c^t$ and $f_c^s$ are as similar as possible irrespective of their domain so that the domain classifier cannot reliably predict the domain of the sample from its shared representation. Parameters of the domain classifier $Z(.)$ are trained to minimize the domain classification loss while the parameters of the shared encoder $E_c$ are trained to maximise the domain classification loss. This is also accomplished with a GRL. $L_{diff}$ encourages the shared component $f_c$ and the private component $f_p$ to encode different aspects of the input. This is achieved by imposing a soft subspace orthogonality constraint between the private and shared components. \begin{equation} L_{diff} = \| \mathbf{F}_c^{sT} \mathbf{F}_p^s \|^2_F + \| \mathbf{F}_c^{tT} \mathbf{F}_p^t \|^2_F \end{equation} where $\mathbf{F}_c^{s}$, $\mathbf{F}_c^{t}$, $\mathbf{F}_p^s$ and $\mathbf{F}_p^t$ are matrices with $f_c^s$, $f_c^t$, $f_p^s$ and $f_p^t$ as rows. $\|.\|_F$ denotes the Frobenius norm. $L_{recon}$ is the reconstruction loss, computed as the mean squared error (MSE) between $\mathbf{x}$ and $\hat{\mathbf{x}} = D (E_c(\mathbf{x})+E_p(\mathbf{x}))$. \begin{equation} L_{recon} = \sum_{i=1}^{N_s} \| \mathbf{x}_i^s - \hat{\mathbf{x}}_i^s\|^2 + \sum_{i=1}^{N_t} \| \mathbf{x}_i^t - \hat{\mathbf{x}}_i^t\|^2 \end{equation} where $N_s$ and $N_t$ represent the number of speech frames from the source and target domains. We also validate the performance of the system with scale-invariant mean squared error (SIMSE) which is computed as: \begin{equation} L_{SIMSE} = \frac{1}{k} \| \mathbf{x} - \hat{\mathbf{x}} \|_2^2 - \frac{1}{k^2} (\left[\mathbf{x} - \hat{\mathbf{x}}\right] . \mathbf{1}_k)^2 \end{equation} where $k$ in the dimension of the input vector $\mathbf{x}$, $\mathbf{1}_k$ is a $k$-dimensional vector of ones and $\|.\|_2$ is the $L_2$ norm. \section{Experimental setup} \label{sec:setup} \subsection{Datasets used for the study} We primarily use a Hindi dataset \cite{data_hindi} in the source domain. We also use a Telugu dataset \cite{data_telugu} in the ablation studies. Both these datasets are the same as the ones used in multilingual and code-switching ASR challenge, Interspeech-2021. The details of both these datasets are available in \cite{multilingual}. Both the speech data and the corresponding transcriptions are available. Hindi and Telugu audio files have sampling frequencies of 8 and 16 kHz, respectively. Both have 16-bit encoding. Telugu audio is downsampled to 8 kHz in our experiments. We randomly select 15,000 utterances ($\approx$ 15 hours) from their train sets for training the domain-independent acoustic models. The senone labels required for training the acoustic model are obtained from the alignments generated by a HMM-GMM system \cite{hmm} trained using Kaldi \cite{kaldi}. We also use a random selection of 1000 utterances from the test set to validate the domain independence of learned features. We refer to this set as \textit{dev}. The Sanskrit dataset used in the target domain has 3395 utterances with 16 kHz sampling frequency and 16-bit encoding. The data is randomly divided into two sets - train and test, with approximately 5.5 hours (2837 utterances) in the train set and 1 hour (558 utterances) in the test set. The train set is used for domain training, and the test set is used for inference. The data is downsampled to 8 kHz before its use in all our experiments. The text corpus for building the Sanskrit language models makes use of the \textit{wiki} Sanskrit data dump \cite{Sanskrit} and data from several Sanskrit websites. The extracted text is cleaned to remove unwanted characters and pre-processed to restrict the graphemes to the Devanagari Unicode symbols. \subsection{Details of feature extraction} We use 40-dimensional filterbank features together with their delta and acceleration coefficients. Cepstral mean variance normalisation is performed at the utterance level. The features are spliced with a left and right context of 5 frames each. Thus the acoustic feature vector at the input of the DNN has dimensions of 1320 (40 x 3 x 11). Feature extraction is performed using Kaldi \cite{kaldi}. \subsection{Training of the GRL model} The feature extractor ($G_f$) has six hidden layers with 1024 nodes in each layer. The input to the $G_f$ is a 1320-dimensional acoustic feature vector, and the output is a 1024-dimensional feature $\mathbf{f}$. The feature vector $\mathbf{f}$ is forwarded to both the senone classifier $G_y$ and the domain classifier $G_d$. The senone classifier has two hidden layers, each with 1024 nodes and an output layer with 3080 nodes (equal to the number of senones in the Hindi training data). Domain classifier has a hidden layer with 256 nodes and an output layer with two nodes corresponding to the source and target domains. All the hidden layers are followed by batch normalization and ReLU activation. The logarithm of the softmax is computed at the output of both domain and senone classifiers. All the parameters ($\theta_f$, $\theta_y$ and $\theta_d$) are updated during the training with Hindi utterances. Only $\theta_f$ and $\theta_d$ are updated during the training with unlabelled Sanskrit utterances. Negative log-likelihood loss is used for training. The models are trained using stochastic gradient descent with momentum \cite{sgd}. We use a batch size of 32 and an initial learning rate of 0.01. The learning rate is scaled by a factor of 0.95 after every 20000 steps. Training is performed for 20 epochs. The same number of frames from the source and target domains are used for training at every epoch. The domain adaptation factor $\alpha$ is gradually changed from 0 to 1 using the approach in \cite{ganin}. \subsection{Training of the DSN model} Acoustic frames from the source and target domains, both of dimension 1320, are Input to the DSN. Private encoders for the source and target have four hidden layers with 512 nodes in each layer. The shared encoder has six hidden layers with 1024 nodes each. The senone and domain classifiers have the same architecture as the GRL model. All the hidden layers are followed by batch normalization and ReLU activation. The shared decoder has three hidden layers and an output layer with 1320 nodes. The hyperparameters $\beta$, $\gamma$, and $\delta$ are chosen as 0.25, 0.075, and 0.1, respectively. In order to promote the learning of the senone classifier in the initial phase of training, domain adversarial similarity losses are activated only after 10000 steps. The rest of the training process is the same as in the GRL model. \subsection{Decoding} During the inference stage, only the output of the senone classifier is considered. The pre-softmax output of the senone classifier is normalized using the log probability of priors. To find the most probable word sequence, we use weighted finite-state transducers (WFST) \cite{wfst} based decoding. The vocabulary of Sanskrit is distinct from that of Hindi. So the FSTs for grammar (G) and lexicon (L) are built using the text corpus collected in Sanskrit (target domain). Pronunciation dictionary for building the L-FST uses the grapheme to phoneme (G2P) mapping scheme in Sanskrit. This is different from the Hindi G2P scheme in aspects like schwa deletion and pronunciation of visargas \cite{asr_sanskrit}. HMM (H) and context-dependency (C) FSTs are created using the HMMs learned from the source domain data. These four FSTs are composed to form a single HCLG graph, which maps the senones directly to the words in the target domain. \section{Results} \label{sec:results} We decode the Sanskrit test set of 558 utterances with the adversarially trained GRL and DSN architectures. These models use both the labeled Hindi data and the unlabelled Sanskrit data for training. In order to benchmark the performance of these UDA models, we decode the utterances using a simple DNN model trained only with the Hindi speech data. In this model, the domain classifier is not part of the network architecture. We also compare our results with a DNN model trained in multi-task (MT) learning setup, training the whole network to minimize both the senone and domain classification objectives. This network has the same architecture as the network in Fig. \ref{fig:blockdiagram}, except that it does not have the GRL. This model also makes use of both the Hindi and Sanskrit data. \begin{table}[htb] \caption{WER on the Sanskrit-test set. Column-I gives the WER when the text corpus for creating L and G FSTs includes the \textit{wiki} data dump and web-crawled data ($\approx$ 436840 words). Column-II gives the WER when the text corpus is restricted to the transcriptions of the Sanskrit speech corpus ($\approx$ 12250 words). } \begin{center} \begin{tabular}{ | c | c | c | c | c |} \hline \textbf{Model} & \textbf{Source} & \textbf{Target} & \textbf{I} & \textbf{II}\\ \hline DNN & Hindi & - & 24.58\% & 16.14\% \\ \hline MT & Hindi & Sanskrit & 21.43\% & 13.10\% \\ \hline GRL & Hindi & Sanskrit & 17.87\% & 10.22\% \\ \hline DSN & Hindi & Sanskrit & 17.26\% & 9.89\% \\ \hline \hline \end{tabular} \end{center} \vspace{-0.2cm} \label{tab:wer} \end{table} The performance measure used to evaluate these models is word error rate (WER). The results are shown in Table \ref{tab:wer} for two cases: i) when the language models are trained on the whole text corpus made out of \textit{wiki} data dump and web-crawling (column I) and ii) when the language models are trained only on the transcriptions of the Sanskrit speech corpus (column II). GRL approach gives an absolute improvement of 6.71\% in WER over the baseline DNN model when the language model is trained on a large text corpus in Sanskrit (column I of Table \ref{tab:wer}). DSN provides an absolute improvement of 7.32\%. Both the UDA models have nearly similar performance, and they beat the multi-task learning model by more than 3.5\%. When the language model training is restricted to the transcriptions of the Sanskrit speech corpus, the performance of all the models improves as expected. However, the UDA approaches still retain the edge over the MT models by about 3\%. We have also tried to fine-tune the UDA models using the senone labels of the Sanskrit train set computed from the DNN models trained on Hindi, but they did not improve the performance of the models. \subsection{Ablation studies} In all the experiments below, we compute WER using the bi-gram language models trained on the larger text corpus associated with column I of Table \ref{tab:wer}. \subsubsection{Effect of the amount of unlabelled training data from the target domain} Next, we address the question of the amount of unlabelled data required for proper adaptation. We split the training set in the target domain into six sets with 0.5, 1.5, 2.5, 3.5, 4.5, and 5.5 hours of data and train the UDA models using them. The entire source domain data is used for training. The performance of these models in terms of WER is shown in Fig. \ref{fig:hours}. The performance of both the models improves as the amount of unlabelled training data increases but nearly saturates after about 2.5 hours of data in the target domain (Sanskrit). \begin{figure}[htb] \centering \includegraphics[width=1\linewidth]{wer_hrs.png} \caption{Effect of the amount of unlabelled training data from the target domain on the WER. } \label{fig:hours} \end{figure} \vspace{-0.7cm} \subsubsection{Domain independence of features} We also visualize the features at the output of the feature extractor (shared encoder for DSN) for our models. We collect an equal number of frames with the same senone label (based on the HMM-GMM alignment) from the Hindi-dev and Sanskrit-test sets and plot the vectors at the output of the feature extractor (or shared encoder) using t-SNE \cite{tsne}. The results are shown in Fig. \ref{fig:tsne}. Compared to Figs.\ref{fig:tsne}(a) and \ref{fig:tsne}(b), the features in Figs. \ref{fig:tsne}(c) and \ref{fig:tsne}(d) are more intermingled indicating the domain independence of features. The domain-discriminative power is higher for the features from MT models as seen from Fig. \ref{fig:tsne}(b). \begin{figure}[htb] \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{tsne_hindi.png} \vspace{-0.6cm} \label{fig:tsne_dnn} \subcaption[]{} \end{minipage} \hspace{0.1cm} \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{tsne_multitask.png} \vspace{-0.6cm} \label{fig:tsne_mt} \subcaption[]{} \end{minipage} \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{tsne_grl.png} \vspace{-0.6cm} \label{fig:tsne_grl} \subcaption[]{} \end{minipage} \hspace{0.1cm} \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{tsne_dsn.png} \vspace{-0.6cm} \label{fig:tsne_dsn} \subcaption[]{} \end{minipage} \caption{2-D t-SNE plots of features at the output of feature extractor/shared encoder in (a) baseline DNN (trained only with Hindi data), (b) MT, (c) GRL, and (d) DSN models for frames with senone label 3009. \textit{H} and \textit{S} denote the frames obtained from the Hindi-dev set (source domain) and Sanskrit-test set (target domain), respectively.} \label{fig:tsne} \end{figure} To verify the extent of domain independence achieved by the model, we compute the frame-level domain accuracy on the Hindi-dev and the Sanskrit-test sets. The results are listed in Table \ref{tab:domain_acc}. It can be seen that the features from UDA models are much more domain-independent compared to the MT models. \begin{table}[htb] \caption{Frame-level domain accuracy of the UDA models computed on the Sanskrit-test and Hindi-dev sets.} \label{tab:domain_acc} \centering \begin{tabular}{|c|c|c|} \hline & \multicolumn{2}{c|}{\textbf{Domain Accuracy}} \\ \hline \textbf{Model} & \textbf{Sanskrit-test} & \textbf{Hindi-dev} \\ \hline MT & 91.86\% & 76.31\% \\ \hline GRL & 63.77\% & 44.94\% \\ \hline DSN & 63.21\% & 52.18\% \\ \hline \hline \end{tabular} \end{table} \vspace{-0.6 cm} \subsubsection{Effect of the loss functions in DSN} Next, we experiment with the constituents of the loss function in DSN. We train four models: (i) with all the loss functions in DSN, (ii) without the difference loss ($\gamma$ = 0), (iii) without the similarity loss ($\beta$ = 0), and (iv) with the reconstruction loss computed as SIMSE. The results are listed in Table \ref{tab:dsnloss}. The performance degrades slightly in the absence of difference loss which tries to enhance the orthogonality between the private and shared components. There is considerable degradation in the performance in the absence of similarity loss. The results are still better than the baseline DNN and MT models (refer column I in Table \ref{tab:wer}) indicating the usefulness of private and shared component decomposition in DSN. The model using SIMSE as the reconstruction loss performs inferior to that of the one using MSE. \begin{table}[htb] \caption{Effect of the different constituents of the loss function on the performance of the DSN.} \begin{center} \begin{tabular}{ | l | c | } \hline \textbf{Loss functions} & \textbf{WER} \\ \hline All terms included & 17.26\% \\ \hline $L_{diff}$ = 0 ($\gamma$ = 0) & 18.10\% \\ \hline $L_{sim}$ = 0 ($\beta$ = 0) & 20.37\% \\ \hline $L_{recon}$ = SIMSE & 18.00\% \\ \hline \hline \end{tabular} \end{center} \vspace{-0.5cm} \label{tab:dsnloss} \end{table} \vspace{-0.6cm} \subsubsection{Source domain language selection} Though both Hindi and Sanskrit are written in Devanagari, they have a difference in pronunciation, as pointed out in section \ref{sec:intro}. However, \cite{telugu} suggests that Telugu and Malayalam are the closest languages to Sanskrit in terms of pronunciation, vocabulary, and grammar. Moreover, the schwa is retained in Dravidian languages like Telugu and Malayalam, just like Sanskrit. Since suitable datasets are available in Telugu, we repeat the experiment with Telugu in the source domain, hoping for better acoustic and pronunciation models in Sanskrit. The results are shown in Table \ref{tab:telugu}. All the models improve, as the phone HMM models learned from Telugu better match Sanskrit. Here also, the performance of UDA models is better than the DNN and MT models. The UDA approaches improve by around 3.5-4.5\% compared to adaptation from Hindi. \begin{table}[htb] \caption{WER on the Sanskrit-test set when trained with Telugu as the source domain language. } \centering \begin{tabular}{|c|c|c|c|} \hline \textbf{Model} & \textbf{Source} & \textbf{Target} & \textbf{WER} \\ \hline DNN & Telugu & - & 17.65\% \\ \hline MT & Telugu & Sanskrit & 14.71\% \\ \hline GRL & Telugu & Sanskrit & 13.09\% \\ \hline DSN & Telugu & Sanskrit & 13.72\% \\ \hline \hline \end{tabular} \label{tab:telugu} \end{table} \vspace{-0.6cm} \section{Conclusions} \label{sec:conclusions} In this work, we propose UDA as an option to tackle the scarcity of data in low-resource languages which share a common acoustic space with a high-resource language. We experiment with Hindi as the source domain language and Sanskrit as the target domain language. GRL and DSN models improve the WER by 6.71\% and 7.32\%, respectively, compared to a baseline DNN model trained only on Hindi. The models perform better than the multi-task learning framework. Proper selection of source domain language (Telugu in our case) further improves the results. The results indicate that UDA can provide a faster way of building ASR systems in low-resource languages, reducing the hassle of collecting large amounts of annotated training data if a suitable high-resource language is available. \bibliographystyle{IEEEbib} \section{Introduction} \label{sec:intro} Advancements in deep learning have brought performance improvements in acoustic and language modeling, yielding robust automatic speech recognition (ASR) systems in many languages. However, such systems require a large amount of speech data and the associated transcriptions. It is tough to collect large volumes of paired speech and transcriptions for most low-resource languages. It is estimated that only about 1\% of the world languages have the minimum amount of data that is needed to train an ASR \cite{low-resource}. However, in many cases, especially for languages in south Asia, we can find a ``close enough'' language with the same set (or a superset) of phonemes as the low-resource language and enough resources for building an ASR. In this work, we show that a better performing ASR can be built for the low-resource language using unsupervised domain adaptation (UDA) of acoustic models from the corresponding high-resource language. This method has the benefit of modeling on real data in comparison to the data augmentation techniques like vocal tract length perturbation \cite{vltp, vltp2}, speech and tempo perturbation \cite{audio_aug}, noise addition \cite{deepspeech}, data synthesis \cite{low_res_data_aug}, and spectral augmentation \cite{specaug}, where the modeling makes use of the synthetic data as well. Unsupervised domain adaptation (UDA) has been successfully applied to various tasks to alleviate the shift between the train and test distributions. \cite{ganin} shows good adaptation performance in the classification task on digit image datasets having considerable domain shifts. They learn features that are discriminative for the image classification task and invariant to the domain. They introduce a gradient reversal layer (GRL) for achieving this objective. \cite{gender_accent_shift} reports performance improvements in speech recognition for data shifted in the domain by gender and accent. \cite{emo1} employs GRL layers to reduce the mismatch between train and test domains in the task of emotion recognition from speech data. \cite{speech} uses the GRL approach to improve the word error rate (WER) in speech recognition with the source domain data as clean speech and the target domain data as contaminated speech. They also show the robustness of the approach to the domain shifts caused by the differences in datasets. The basic UDA scheme with a GRL tries to learn domain invariant features but ignores the individual characteristics of each domain. \cite{dsn} introduces domain separation networks (DSN) and shows improvements in a range of UDA scenarios in the image classification task. They learn two representations: one specific to each domain and the other common to both domains. \cite{dsn_clean2noisy} uses DSN for adaptation from clean speech to noisy speech. In this work, we explore the feasibility of the UDA schemes in the ASR task on low-resource languages that share the same acoustic space with a high-resource language. Specifically, we place the following assumptions in the selection of high and low resource language pairs. \begin{enumerate} \item The acoustic space spanned by the low-resource language is a subspace of that of the high-resource language. This requires the phoneme set of the low-resource language to be a subset of the high-resource language. \item There exists a high-resource language with reasonable amount of paired audio data and transcriptions to build an ASR. \item The low-resource language has enough text data available to train the language models. \item The speech data available in the low-resource language is quite limited, and the transcriptions are not available. \end{enumerate} Though the above assumptions seem quite constrictive, we can easily find a few low-resource languages in the Indian subcontinent which share a common acoustic space with a reasonably high-resource language. In this work, we use Hindi as the high-resource language and Sanskrit as the low-resource language, both belonging to the Indo-Aryan language family. Hindi is written in the Devanagari script, and many of its words are derived from Sanskrit. However, there exist substantial differences in the vocabulary and pronunciation between the two languages. One of the important differences is that the schwa, implicit in each consonant of the script, is not pronounced at the end of words and in some other contexts in Hindi. The script does not tell us when the schwa should be deleted, a phenomenon known as schwa deletion. For example, the word for "salty" is pronounced as \textit{nam'kīn} in Hindi and not \textit{namakīna}. Another difference is the pitch accents that are common in Sanskrit. Despite the above differences, these languages share a common phoneme set. So we can intuitively argue that there exists a domain shift between the distributions of acoustic features in Hindi and Sanskrit. This makes us believe that the speech recognition problem in Sanskrit, an extremely low-resource language, may be posed as an UDA problem from Hindi, a language with a reasonably good collection of annotated audio. \section{Unsupervised domain adaptation for acoustic modeling} \label{sec:uda} We pose the problem of acoustic modeling in Sanskrit as an unsupervised domain adaptation task from Hindi. We build a deep neural network (DNN) - hidden Markov model (HMM) ASR system \cite{dnn-hmm} for Sanskrit with the domain-independent acoustic models learned from Hindi through UDA approaches. We make use of the UDA schemes introduced in \cite{ganin} and \cite{dsn}. \begin{figure}[t] \centering \includegraphics[width=1\linewidth, height =0.6\columnwidth]{dda.pdf} \caption{Block diagram of the basic scheme for unsupervised domain adaptation with a gradient reversal layer (GRL). $\theta_f$, $\theta_y$ and $\theta_d$ represent the parameters of the feature extractor, senone classifier, and domain classifier, respectively.} \label{fig:blockdiagram} \end{figure} \begin{figure*}[htb] \centering \includegraphics[scale=0.8]{dsn.pdf} \caption{Block diagram of the domain separation network to model private and shared components. } \label{fig:dsn} \end{figure*} \subsection{Adversarial training using GRL} \label{sec:grl} In GRL-based adversarial training, we try to learn a feature representation invariant to the domain, but good enough in discriminating the senone labels. The neural network architecture for learning the acoustic model consists of three parts: feature extractor, senone classifier, and domain classifier. A block diagram of the UDA architecture employing GRL is shown in Fig. \ref{fig:blockdiagram}. Feature extractor $G_f$ maps the input acoustic features $\mathbf{x}$ to an internal representation $\mathbf{f} \in \mathcal{R}^D$. Senone classifier $G_y$ maps the output of the feature extractor to the senone labels $\mathbf{y}$ whereas the domain classifier $G_d$ maps them to domain labels $\mathbf{d}$. We train the network to minimize the senone classification loss during the training phase by optimizing the parameters in the feature extractor $G_f$ and senone classifier $G_y$. This makes the network look for features that are capable of discriminating the senone labels. To make the features domain-invariant, we optimize the parameters of the feature extractor to maximize the domain classification loss. But at the same time, the parameters of the domain classifier $G_d$ are optimized to minimize the domain classification loss. This is achieved by introducing a GRL between the feature extractor $G_f$ and domain classifier $G_d$. During the forward pass, GRL acts as an identity transform. GRL takes the gradient from the subsequent layer during the backward pass, multiplies it with $-\alpha$, a hyperparameter to control the trade-off between senone discrimination and domain-invariance, and passes it to the preceding layer. During the inference time, the domain classifier and GRL are ignored. The acoustic feature vectors are passed through the feature extractor and the senone classifier, and senone labels are predicted. \subsection{Domain separation networks} \label{sec:dsn} A block diagram of the DSN architecture is shown in Fig. \ref{fig:dsn}. They model both the private and shared components of the domain representation. Private encoders $E_p^t(.)$ and $E_p^s(.)$ extract components $f_p^t$ and $f_p^s$ which are specific to the target and source domains. Shared encoder $E_c(.)$ is common to both domains and extract the shared components $f_c^t$ and $f_c^s$ . Shared decoder $D$ tries to reconstruct the input using the private and shared components. $G(.)$, the senone classifier maps $f_c^s$ to the senone label $\mathbf{\hat{y}}$. The domain classifier $Z(.)$ maps the shared components $f_c^s$ and $f_c^t$ to their respective domain labels $\mathbf{\hat{d}}$. The network is trained to minimize the following loss function with respect to the parameters of $E_p$, $E_c$, $G$ and $Z$: \begin{equation} L = L_{class} + {\beta} L_{sim} + {\gamma} L_{diff} + {\delta} L_{recon} \end{equation} where $\beta, \gamma$, and $\delta$ are hyperparameters. $L_{class}$ represents the senone classification loss and is applied only to the source domain. It is computed as the negative log-likelihood of the ground-truth senone labels. $L_{sim}$ represents the domain adversarial similarity loss and is computed as the negative log-likelihood of the domain labels. $L_{sim}$ ensures that the shared components $f_c^t$ and $f_c^s$ are as similar as possible irrespective of their domain so that the domain classifier cannot reliably predict the domain of the sample from its shared representation. Parameters of the domain classifier $Z(.)$ are trained to minimize the domain classification loss while the parameters of the shared encoder $E_c$ are trained to maximise the domain classification loss. This is also accomplished with a GRL. $L_{diff}$ encourages the shared component $f_c$ and the private component $f_p$ to encode different aspects of the input. This is achieved by imposing a soft subspace orthogonality constraint between the private and shared components. \begin{equation} L_{diff} = \| \mathbf{F}_c^{sT} \mathbf{F}_p^s \|^2_F + \| \mathbf{F}_c^{tT} \mathbf{F}_p^t \|^2_F \end{equation} where $\mathbf{F}_c^{s}$, $\mathbf{F}_c^{t}$, $\mathbf{F}_p^s$ and $\mathbf{F}_p^t$ are matrices with $f_c^s$, $f_c^t$, $f_p^s$ and $f_p^t$ as rows. $\|.\|_F$ denotes the Frobenius norm. $L_{recon}$ is the reconstruction loss, computed as the mean squared error (MSE) between $\mathbf{x}$ and $\hat{\mathbf{x}} = D (E_c(\mathbf{x})+E_p(\mathbf{x}))$. \begin{equation} L_{recon} = \sum_{i=1}^{N_s} \| \mathbf{x}_i^s - \hat{\mathbf{x}}_i^s\|^2 + \sum_{i=1}^{N_t} \| \mathbf{x}_i^t - \hat{\mathbf{x}}_i^t\|^2 \end{equation} where $N_s$ and $N_t$ represent the number of speech frames from the source and target domains. We also validate the performance of the system with scale-invariant mean squared error (SIMSE) which is computed as: \begin{equation} L_{SIMSE} = \frac{1}{k} \| \mathbf{x} - \hat{\mathbf{x}} \|_2^2 - \frac{1}{k^2} (\left[\mathbf{x} - \hat{\mathbf{x}}\right] . \mathbf{1}_k)^2 \end{equation} where $k$ in the dimension of the input vector $\mathbf{x}$, $\mathbf{1}_k$ is a $k$-dimensional vector of ones and $\|.\|_2$ is the $L_2$ norm. \section{Experimental setup} \label{sec:setup} \subsection{Datasets used for the study} We primarily use a Hindi dataset \cite{data_hindi} in the source domain. We also use a Telugu dataset \cite{data_telugu} in the ablation studies. Both these datasets are the same as the ones used in multilingual and code-switching ASR challenge, Interspeech-2021. The details of both these datasets are available in \cite{multilingual}. Both the speech data and the corresponding transcriptions are available. Hindi and Telugu audio files have sampling frequencies of 8 and 16 kHz, respectively. Both have 16-bit encoding. Telugu audio is downsampled to 8 kHz in our experiments. We randomly select 15,000 utterances ($\approx$ 15 hours) from their train sets for training the domain-independent acoustic models. The senone labels required for training the acoustic model are obtained from the alignments generated by a HMM-GMM system \cite{hmm} trained using Kaldi \cite{kaldi}. We also use a random selection of 1000 utterances from the test set to validate the domain independence of learned features. We refer to this set as \textit{dev}. The Sanskrit dataset used in the target domain has 3395 utterances with 16 kHz sampling frequency and 16-bit encoding. The data is randomly divided into two sets - train and test, with approximately 5.5 hours (2837 utterances) in the train set and 1 hour (558 utterances) in the test set. The train set is used for domain training, and the test set is used for inference. The data is downsampled to 8 kHz before its use in all our experiments. The text corpus for building the Sanskrit language models makes use of the \textit{wiki} Sanskrit data dump \cite{Sanskrit} and data from several Sanskrit websites. The extracted text is cleaned to remove unwanted characters and pre-processed to restrict the graphemes to the Devanagari Unicode symbols. \subsection{Details of feature extraction} We use 40-dimensional filterbank features together with their delta and acceleration coefficients. Cepstral mean variance normalisation is performed at the utterance level. The features are spliced with a left and right context of 5 frames each. Thus the acoustic feature vector at the input of the DNN has dimensions of 1320 (40 x 3 x 11). Feature extraction is performed using Kaldi \cite{kaldi}. \subsection{Training of the GRL model} The feature extractor ($G_f$) has six hidden layers with 1024 nodes in each layer. The input to the $G_f$ is a 1320-dimensional acoustic feature vector, and the output is a 1024-dimensional feature $\mathbf{f}$. The feature vector $\mathbf{f}$ is forwarded to both the senone classifier $G_y$ and the domain classifier $G_d$. The senone classifier has two hidden layers, each with 1024 nodes and an output layer with 3080 nodes (equal to the number of senones in the Hindi training data). Domain classifier has a hidden layer with 256 nodes and an output layer with two nodes corresponding to the source and target domains. All the hidden layers are followed by batch normalization and ReLU activation. The logarithm of the softmax is computed at the output of both domain and senone classifiers. All the parameters ($\theta_f$, $\theta_y$ and $\theta_d$) are updated during the training with Hindi utterances. Only $\theta_f$ and $\theta_d$ are updated during the training with unlabelled Sanskrit utterances. Negative log-likelihood loss is used for training. The models are trained using stochastic gradient descent with momentum \cite{sgd}. We use a batch size of 32 and an initial learning rate of 0.01. The learning rate is scaled by a factor of 0.95 after every 20000 steps. Training is performed for 20 epochs. The same number of frames from the source and target domains are used for training at every epoch. The domain adaptation factor $\alpha$ is gradually changed from 0 to 1 using the approach in \cite{ganin}. \subsection{Training of the DSN model} Acoustic frames from the source and target domains, both of dimension 1320, are Input to the DSN. Private encoders for the source and target have four hidden layers with 512 nodes in each layer. The shared encoder has six hidden layers with 1024 nodes each. The senone and domain classifiers have the same architecture as the GRL model. All the hidden layers are followed by batch normalization and ReLU activation. The shared decoder has three hidden layers and an output layer with 1320 nodes. The hyperparameters $\beta$, $\gamma$, and $\delta$ are chosen as 0.25, 0.075, and 0.1, respectively. In order to promote the learning of the senone classifier in the initial phase of training, domain adversarial similarity losses are activated only after 10000 steps. The rest of the training process is the same as in the GRL model. \subsection{Decoding} During the inference stage, only the output of the senone classifier is considered. The pre-softmax output of the senone classifier is normalized using the log probability of priors. To find the most probable word sequence, we use weighted finite-state transducers (WFST) \cite{wfst} based decoding. The vocabulary of Sanskrit is distinct from that of Hindi. So the FSTs for grammar (G) and lexicon (L) are built using the text corpus collected in Sanskrit (target domain). Pronunciation dictionary for building the L-FST uses the grapheme to phoneme (G2P) mapping scheme in Sanskrit. This is different from the Hindi G2P scheme in aspects like schwa deletion and pronunciation of visargas \cite{asr_sanskrit}. HMM (H) and context-dependency (C) FSTs are created using the HMMs learned from the source domain data. These four FSTs are composed to form a single HCLG graph, which maps the senones directly to the words in the target domain. \section{Results} \label{sec:results} We decode the Sanskrit test set of 558 utterances with the adversarially trained GRL and DSN architectures. These models use both the labeled Hindi data and the unlabelled Sanskrit data for training. In order to benchmark the performance of these UDA models, we decode the utterances using a simple DNN model trained only with the Hindi speech data. In this model, the domain classifier is not part of the network architecture. We also compare our results with a DNN model trained in multi-task (MT) learning setup, training the whole network to minimize both the senone and domain classification objectives. This network has the same architecture as the network in Fig. \ref{fig:blockdiagram}, except that it does not have the GRL. This model also makes use of both the Hindi and Sanskrit data. \begin{table}[htb] \caption{WER on the Sanskrit-test set. Column-I gives the WER when the text corpus for creating L and G FSTs includes the \textit{wiki} data dump and web-crawled data ($\approx$ 436840 words). Column-II gives the WER when the text corpus is restricted to the transcriptions of the Sanskrit speech corpus ($\approx$ 12250 words). } \begin{center} \begin{tabular}{ | c | c | c | c | c |} \hline \textbf{Model} & \textbf{Source} & \textbf{Target} & \textbf{I} & \textbf{II}\\ \hline DNN & Hindi & - & 24.58\% & 16.14\% \\ \hline MT & Hindi & Sanskrit & 21.43\% & 13.10\% \\ \hline GRL & Hindi & Sanskrit & 17.87\% & 10.22\% \\ \hline DSN & Hindi & Sanskrit & 17.26\% & 9.89\% \\ \hline \hline \end{tabular} \end{center} \vspace{-0.2cm} \label{tab:wer} \end{table} The performance measure used to evaluate these models is word error rate (WER). The results are shown in Table \ref{tab:wer} for two cases: i) when the language models are trained on the whole text corpus made out of \textit{wiki} data dump and web-crawling (column I) and ii) when the language models are trained only on the transcriptions of the Sanskrit speech corpus (column II). GRL approach gives an absolute improvement of 6.71\% in WER over the baseline DNN model when the language model is trained on a large text corpus in Sanskrit (column I of Table \ref{tab:wer}). DSN provides an absolute improvement of 7.32\%. Both the UDA models have nearly similar performance, and they beat the multi-task learning model by more than 3.5\%. When the language model training is restricted to the transcriptions of the Sanskrit speech corpus, the performance of all the models improves as expected. However, the UDA approaches still retain the edge over the MT models by about 3\%. We have also tried to fine-tune the UDA models using the senone labels of the Sanskrit train set computed from the DNN models trained on Hindi, but they did not improve the performance of the models. \subsection{Ablation studies} In all the experiments below, we compute WER using the bi-gram language models trained on the larger text corpus associated with column I of Table \ref{tab:wer}. \subsubsection{Effect of the amount of unlabelled training data from the target domain} Next, we address the question of the amount of unlabelled data required for proper adaptation. We split the training set in the target domain into six sets with 0.5, 1.5, 2.5, 3.5, 4.5, and 5.5 hours of data and train the UDA models using them. The entire source domain data is used for training. The performance of these models in terms of WER is shown in Fig. \ref{fig:hours}. The performance of both the models improves as the amount of unlabelled training data increases but nearly saturates after about 2.5 hours of data in the target domain (Sanskrit). \begin{figure}[htb] \centering \includegraphics[width=1\linewidth]{wer_hrs.png} \caption{Effect of the amount of unlabelled training data from the target domain on the WER. } \label{fig:hours} \end{figure} \vspace{-0.7cm} \subsubsection{Domain independence of features} We also visualize the features at the output of the feature extractor (shared encoder for DSN) for our models. We collect an equal number of frames with the same senone label (based on the HMM-GMM alignment) from the Hindi-dev and Sanskrit-test sets and plot the vectors at the output of the feature extractor (or shared encoder) using t-SNE \cite{tsne}. The results are shown in Fig. \ref{fig:tsne}. Compared to Figs.\ref{fig:tsne}(a) and \ref{fig:tsne}(b), the features in Figs. \ref{fig:tsne}(c) and \ref{fig:tsne}(d) are more intermingled indicating the domain independence of features. The domain-discriminative power is higher for the features from MT models as seen from Fig. \ref{fig:tsne}(b). \begin{figure}[htb] \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{tsne_hindi.png} \vspace{-0.6cm} \label{fig:tsne_dnn} \subcaption[]{} \end{minipage} \hspace{0.1cm} \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{tsne_multitask.png} \vspace{-0.6cm} \label{fig:tsne_mt} \subcaption[]{} \end{minipage} \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{tsne_grl.png} \vspace{-0.6cm} \label{fig:tsne_grl} \subcaption[]{} \end{minipage} \hspace{0.1cm} \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{tsne_dsn.png} \vspace{-0.6cm} \label{fig:tsne_dsn} \subcaption[]{} \end{minipage} \caption{2-D t-SNE plots of features at the output of feature extractor/shared encoder in (a) baseline DNN (trained only with Hindi data), (b) MT, (c) GRL, and (d) DSN models for frames with senone label 3009. \textit{H} and \textit{S} denote the frames obtained from the Hindi-dev set (source domain) and Sanskrit-test set (target domain), respectively.} \label{fig:tsne} \end{figure} To verify the extent of domain independence achieved by the model, we compute the frame-level domain accuracy on the Hindi-dev and the Sanskrit-test sets. The results are listed in Table \ref{tab:domain_acc}. It can be seen that the features from UDA models are much more domain-independent compared to the MT models. \begin{table}[htb] \caption{Frame-level domain accuracy of the UDA models computed on the Sanskrit-test and Hindi-dev sets.} \label{tab:domain_acc} \centering \begin{tabular}{|c|c|c|} \hline & \multicolumn{2}{c|}{\textbf{Domain Accuracy}} \\ \hline \textbf{Model} & \textbf{Sanskrit-test} & \textbf{Hindi-dev} \\ \hline MT & 91.86\% & 76.31\% \\ \hline GRL & 63.77\% & 44.94\% \\ \hline DSN & 63.21\% & 52.18\% \\ \hline \hline \end{tabular} \end{table} \vspace{-0.6 cm} \subsubsection{Effect of the loss functions in DSN} Next, we experiment with the constituents of the loss function in DSN. We train four models: (i) with all the loss functions in DSN, (ii) without the difference loss ($\gamma$ = 0), (iii) without the similarity loss ($\beta$ = 0), and (iv) with the reconstruction loss computed as SIMSE. The results are listed in Table \ref{tab:dsnloss}. The performance degrades slightly in the absence of difference loss which tries to enhance the orthogonality between the private and shared components. There is considerable degradation in the performance in the absence of similarity loss. The results are still better than the baseline DNN and MT models (refer column I in Table \ref{tab:wer}) indicating the usefulness of private and shared component decomposition in DSN. The model using SIMSE as the reconstruction loss performs inferior to that of the one using MSE. \begin{table}[htb] \caption{Effect of the different constituents of the loss function on the performance of the DSN.} \begin{center} \begin{tabular}{ | l | c | } \hline \textbf{Loss functions} & \textbf{WER} \\ \hline All terms included & 17.26\% \\ \hline $L_{diff}$ = 0 ($\gamma$ = 0) & 18.10\% \\ \hline $L_{sim}$ = 0 ($\beta$ = 0) & 20.37\% \\ \hline $L_{recon}$ = SIMSE & 18.00\% \\ \hline \hline \end{tabular} \end{center} \vspace{-0.5cm} \label{tab:dsnloss} \end{table} \vspace{-0.6cm} \subsubsection{Source domain language selection} Though both Hindi and Sanskrit are written in Devanagari, they have a difference in pronunciation, as pointed out in section \ref{sec:intro}. However, \cite{telugu} suggests that Telugu and Malayalam are the closest languages to Sanskrit in terms of pronunciation, vocabulary, and grammar. Moreover, the schwa is retained in Dravidian languages like Telugu and Malayalam, just like Sanskrit. Since suitable datasets are available in Telugu, we repeat the experiment with Telugu in the source domain, hoping for better acoustic and pronunciation models in Sanskrit. The results are shown in Table \ref{tab:telugu}. All the models improve, as the phone HMM models learned from Telugu better match Sanskrit. Here also, the performance of UDA models is better than the DNN and MT models. The UDA approaches improve by around 3.5-4.5\% compared to adaptation from Hindi. \begin{table}[htb] \caption{WER on the Sanskrit-test set when trained with Telugu as the source domain language. } \centering \begin{tabular}{|c|c|c|c|} \hline \textbf{Model} & \textbf{Source} & \textbf{Target} & \textbf{WER} \\ \hline DNN & Telugu & - & 17.65\% \\ \hline MT & Telugu & Sanskrit & 14.71\% \\ \hline GRL & Telugu & Sanskrit & 13.09\% \\ \hline DSN & Telugu & Sanskrit & 13.72\% \\ \hline \hline \end{tabular} \label{tab:telugu} \end{table} \vspace{-0.6cm} \section{Conclusions} \label{sec:conclusions} In this work, we propose UDA as an option to tackle the scarcity of data in low-resource languages which share a common acoustic space with a high-resource language. We experiment with Hindi as the source domain language and Sanskrit as the target domain language. GRL and DSN models improve the WER by 6.71\% and 7.32\%, respectively, compared to a baseline DNN model trained only on Hindi. The models perform better than the multi-task learning framework. Proper selection of source domain language (Telugu in our case) further improves the results. The results indicate that UDA can provide a faster way of building ASR systems in low-resource languages, reducing the hassle of collecting large amounts of annotated training data if a suitable high-resource language is available. \bibliographystyle{IEEEbib}
{'timestamp': '2021-09-17T02:12:38', 'yymm': '2109', 'arxiv_id': '2109.05494', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05494'}
arxiv
\section{Introduction} Deep Reinforcement learning (DRL) has recently shown a great success in a variety of decision-making problems that involve controls with either discrete actions, such as Go \citep{Silver2016Go} and Atari \citep{Mnih2015DQN}, or continuous actions, such as robot control \citep{Schulman2015TRPO, Lillicrap2015DDPG}. However, in contrast to these two kinds of homogeneous action space, many real-world scenarios requires more complex controls with discrete-continuous hybrid action space, e.g., Robot Soccer \citep{WarwickMasson} and Games \citep{JiechaoXiong}. For example, in robot soccer, the agent not only needs to choose whether to shoot or pass the ball (i.e., discrete actions) but also the associated angle and force (i.e., continuous parameters). Such a hybrid action is also called parameterized action in some previous works \citep{HausknechtandStone, massaroli2020neural}. Unfortunately, most conventional RL algorithms cannot deal with such a heterogeneous action space directly, thus preventing the application of RL in these kinds of practical problems. \begin{comment} \begin{figure} \centering \includegraphics[width=0.50\textwidth]{overall5.pdf} \caption{An overview of HyAR. Agent learns a latent policy in the latent representation space of discrete-continuous actions. The selected latent action is then decoded into the original space so as to interact with the environment. } \label{figure:conceptual_overview} \end{figure} \end{comment} To deal with hybrid action space, the most straightforward approach is to convert the heterogeneous space into a homogeneous one through discretization or continualization. However, it is apparent that discretizing continuous parameter space suffers from the scalability issue due to the exponentially exploring number of discretized actions; while casting all discrete actions into a continuous dimension produces a piecewise-function action subspace, resulting in additional difficulties in approximation and generalization. To overcome these problems, a few recent works propose specific policy structures to learn DRL policies over the original hybrid action space directly. Parameterized Action DDPG (PADDPG) \citep{HausknechtandStone} makes use of a DDPG \citep{Lillicrap2015DDPG} structure where the actor is modified to output a unified continuous vector as the concatenation of values for all discrete actions and all corresponding continuous parameters. By contrast, Hybrid PPO (HPPO) \citep{ZhouFan2019} uses multiple policy heads consisting of one for discrete actions and the others for corresponding continuous parameter of each discrete action separately. A very similar idea is also adopted in \citep{peng2019improving}. These methods are convenient to implement and are demonstrated to effective in simple environments with low-dimensional hybrid action space. However, PADDPG and HPPO neglect the dependence between discrete and continuous components of hybrid actions, thus can be problematic since the dependence is vital to identifying the optimal hybrid actions in general. Besides, the modeling of all continuous parameter dimensions all the time introduces redundancy in computation and policy learning, and may also have the scalability issue when the hybrid action space becomes high-dimensional. \begin{wraptable}{r}{0cm} \begin{minipage}[t]{.55\linewidth} \centering \vspace{-0.2cm} \scalebox{0.75}{ \begin{tabular}{ccccc} \toprule Algorithm & Scalability & Stationarity & Dependence & Latent \\ \midrule PADDPG & \XSolidBrush & \Checkmark & \XSolidBrush & \XSolidBrush\\ HPPO & \XSolidBrush & \Checkmark & \XSolidBrush & \XSolidBrush\\ PDQN & \XSolidBrush & \Checkmark & \Checkmark & \XSolidBrush\\ HHQN & \Checkmark & \XSolidBrush & \Checkmark & \XSolidBrush \\ \midrule HyAR (Ours) & \textcolor{green}{\Checkmark} & \textcolor{green}{\Checkmark} & \textcolor{green}{\Checkmark} & \textcolor{green}{\Checkmark}\\ \bottomrule \end{tabular} } \caption{A comparison on algorithmic properties of existing methods for discrete-continous hybrid action RL. } \label{table:alg_comparison} \vspace{-0.1cm} \end{minipage} \end{wraptable} To model the dependence, Parameterized DQN (PDQN) \citep{JiechaoXiong} proposes a hybrid structure of DQN \citep{Mnih2015DQN} and DDPG. The discrete policy is represented by a DQN which additionally takes as input all the continuous parameters output by the DDPG actor; while the DQN also serves as the critic of DDPG. Some variants of such a hybrid structure are later proposed in \citep{Olivier,MaYCSJ21,MPDQN}. Due to the DDPG actor's modeling of all parameters, PDQN also have the redundancy and potential scalablity issue. In an upside-down way, Hierarchical Hybrid Q-Network (HHQN) \citep{Haotian2019} models the dependent hybrid-action policy with a two-level hierarchical structure. The high level is for the discrete policy and the selected discrete action serves as the condition (in analogy to subgoal) which the low-level continuous policy conditions on. This can be viewed as a special two-agent cooperative game where the high level and low level learn to coordinate at the optimal hybrid actions. Although the hierarchical structure \citep{WeiWL18} seems to be natural, it suffers from the high-level non-stationarity caused by off-policy learning dynamics \citep{WangY0R20I2HRL}, i.e., a discrete action can no longer induce the same transition in historical experiences due to the change of the low-level policy. In contrast, PADDPG, HPPO and PDQN are stationary in this sense since they all learn an overall value function and policy thanks to their special structures, which is analogous to learning a joint policy in the two-agent game. All the above works focus on policy learning over original hybrid action space. As summarized in Table \ref{table:alg_comparison}, none of them is able to offer three desired properties, i.e., scalability, stationarity and action dependence, at the same time. \begin{wrapfigure}{r}{0cm} \begin{minipage}[t]{.45\linewidth} \centering \vspace{-0.2cm} \hspace{-0.1cm} \includegraphics[width=1.\textwidth]{overall5.pdf} \caption{An overview of HyAR. Agent learns a latent policy in the latent representation space of discrete-continuous actions. The selected latent action is then decoded into the original space so as to interact with the environment. } \label{figure:conceptual_overview} \vspace{-0.2cm} \end{minipage} \end{wrapfigure} In this paper, we propose a novel framework for hybrid action RL, called \textbf{Hy}brid \textbf{A}ction \textbf{R}epresentation (\textbf{HyAR\xspace}), to achieve all three properties in Table \ref{table:alg_comparison}. A conceptual overview of HyAR\xspace is shown in Fig.~\ref{figure:conceptual_overview}. The main idea is to construct a unified and decodable representation space for original discrete-continuous hybrid actions, among which the agent learns a latent policy. Then, the selected latent action is decoded back to the original hybrid action space so as to interact with the environment. HyAR\xspace is inspired by recent advances in Representation Learning in DRL. Action representation learning has shown the potentials in boosting learning performance \citep{WilliamF}, reducing large discrete action space \citep{YashChandak}, improving generalization in offline RL \citep{PLAS} and so on. Different from these works, to the best knowledge, we are the first to propose representation learning for discrete-continuous hybrid actions, which consist of heterogeneous and dependent action components. In HyAR, we maintain a continuous vector for each discrete action in a learnable embedding table; then a conditional Variational Auto-encoder (VAE) \citep{DiederikP} that conditions on the state and the embedding of discrete action is used to construct the latent representation space for the associated continuous parameters. Different from HHQN, the conditional VAE models and embeds the dependence in an implicit fashion. The learned representation space are compact and thus scalable, while also provides convenient decoding by nearest-neighbor lookup of the embedding table and the VAE decoder. Moreover, we utilize the unsupervised environmental dynamics to learn dynamics predictive hybrid action representation. Such a representation space can be semantically smooth, i.e., hybrid action representations that are close in the space have similar influence on environmental dynamics, thus benefits hybrid action RL in the representation space. With the constructed action representation space, we use TD3 algorithm \citep{TD3} for the latent policy learning. To ensure the effectiveness, we further propose two mechanisms: \textit{latent space constraint} and \textit{representation shift correction} to deal with unreliable latent representations and outdated off-policy action representation experiences respectively. In our experiments, we evaluate HyAR in a few representative environments with hybrid action space, as well as several new and more challenging benchmarks. \begin{comment} \begin{table} \centering \scalebox{0.6}{ \begin{tabular}{ccccc} \toprule Algorithm & Scalability & Stationarity & Dependence & Latent \\ \midrule PADDPG & \XSolidBrush & \Checkmark & \XSolidBrush & \XSolidBrush\\ HPPO & \XSolidBrush & \Checkmark & \XSolidBrush & \XSolidBrush\\ PDQN & \XSolidBrush & \Checkmark & \Checkmark & \XSolidBrush\\ HHQN & \Checkmark & \XSolidBrush & \Checkmark & \XSolidBrush \\ \midrule HyAR (Ours) & \textcolor{green}{\Checkmark} & \textcolor{green}{\Checkmark} & \textcolor{green}{\Checkmark} & \textcolor{green}{\Checkmark}\\ \bottomrule \end{tabular} } \caption{A comparison on algorithmic properties of existing methods for discrete-continous hybrid action RL. } \label{table:alg_comparison} \end{table} \end{comment} Our main contributions are summarized below: \begin{itemize} \item We propose a novel and generic framework for discrete-continuous hybrid action RL by leveraging representation learning of hybrid action space for the first time. \item We propose an unsupervised method of learning a compact and decodable representation space for discrete-continuous hybrid actions, along with two mechanisms to improve the effectiveness of latent policy learning. \item Our algorithm consistently outperforms prior algorithms in representative hybrid-action benchmarks, especially demonstrating significant superiority when the hybrid action space becomes larger. For reproducibility, codes are provided in the supplementary material. \end{itemize} \section{Preliminaries} \label{section:Preliminaries} \paragraph{Markov Decision Process} Consider a standard Markov Decision Process (MDP) $\left< \mathcal{S}, \mathcal{A}, \mathcal{P}, \mathcal{R}, \gamma, T \right>$, defined with a state set $\mathcal{S}$, an action set $\mathcal{A}$, transition function $\mathcal{P}: \mathcal{S} \times \mathcal{A} \times \mathcal{S} \rightarrow \mathbb{R}$, reward function $\mathcal{R}: \mathcal{S} \times \mathcal{A} \rightarrow \mathbb{R}$, discounted factor $\gamma \in [0,1)$ and horizon $T$. The agent interacts with the MDP by performing its policy $\pi: \mathcal{S} \rightarrow \mathcal{A}$. The objective of an RL agent is to optimize its policy to maximize the expected discounted cumulative reward $J(\pi) = \mathbb{E}_{\pi} [\sum_{t=0}^{T}\gamma^{t} r_t ]$, where $s_{0} \sim \rho_{0}\left(s_{0}\right)$ the initial state distribution, $a_{t} \sim \pi\left(s_{t}\right)$, $s_{t+1} \sim \mathcal{P}\left(s_{t+1} \mid s_{t}, a_{t}\right)$ and $r_t = \mathcal{R}\left(s_{t},a_{t}\right)$. The state-action value function $Q^{\pi}$ is defined as $Q^{\pi}(s, a)=\mathbb{E}_{\pi} \left[\sum_{t=0}^{T} \gamma^{t} r_{t} \mid s_{0}=s, a_{0}=a \right]$. \begin{comment} \hy{This paragraph is optional.} With function approximation, $Q^{\pi}$ can be approximated by $Q_{\theta}$ with parameter $\theta$ typically through minimizing Temporal Difference loss \citep{Sutton1988ReinforcementLA}, i.e., $L(\theta)=\frac{1}{2}\left[Q_{\theta}(s, a) - \mathbb{E}_{a^{\prime} \sim \pi(s^{\prime})} \left(r + \gamma Q_{\bar{\theta}}(s^{\prime},a^{\prime})\right) \right]^{2}$. A parameterized policy $\pi_{\omega}$, with parameters $\phi$, can be updated by taking the gradient of the objective $\nabla_{\phi} J(\pi_{\omega})$, e.g., with the deterministic policy gradient (DPG) theorem \citep{Silver2014DPG}: $\nabla_{\phi} J(\pi_{\omega}) = \mathbb{E}_{s \sim \rho^{\pi}} \left[ \nabla_{\phi} \pi_{\omega}(s) \nabla_{a} Q^{\pi}(s,a)|_{a=\pi_{\omega}(s)}\right]$, where $\rho^{\pi}$ is the discounted state distribution under policy $\pi$. \end{comment} \vspace{-0.4cm} \paragraph{Parameterized Action MDP} In this paper, we focus on a Parameterized Action Markov Decision Process (PAMDP) $\left< \mathcal{S}, \mathcal{H}, \mathcal{P}, \mathcal{R}, \gamma, T \right>$ \citep{WarwickMasson}. PAMDP is an extension of stardard MDP with a discrete-continuous hybrid action space $\mathcal{H}$ defined as: \begin{equation} \label{equation:1} \mathcal{H}=\left\{\left(k, x_{k}\right) \mid x_{k} \in \mathcal{X}_{k} \text { for all } k \in\mathcal{K}\right\}, \end{equation} where $\mathcal{K}=\{1, \cdots, K\}$ is the discrete action set, $\mathcal{X}_{k}$ is the corresponding continuous parameter set for each $k \in\mathcal{K}$. We call any pair of $k, x_k$ as a hybrid action and also call $\mathcal{H}$ as hybrid action space for short in this paper. In turn, we have state transition function $\mathcal{P}: \mathcal{S} \times \mathcal{H} \times \mathcal{S} \rightarrow \mathbb{R}$, reward function $\mathcal{R}: \mathcal{S} \times \mathcal{H} \rightarrow \mathbb{R}$, agent's policy $\pi: \mathcal{S} \rightarrow \mathcal{H}$ and hybrid-action value function $Q^{\pi}(s,k,x_k)$. Conventional RL algorithms are not compatible with hybrid action space $\mathcal{H}$. Typical policy representations such as Multinomial distribution or Gaussian distribution can not model the heterogeneous components among the hybrid action. Implicit policies derived by action value functions, often adopted in value-based algorithms, also fail due to intractable maximization over infinite hybrid actions. In addition, there exists the dependence between discrete actions and continuous parameters, as a discrete action $k$ determines the valid parameter space $\mathcal{X}_{k}$ associated with it. In other words, the same parameter paired with different discrete actions can be significantly different in semantics. This indicate that in principle an optimal hybrid-action policy can not determine the continuous parameters beforehand the discrete action is selected. \begin{comment} Parameterized Deep Deterministic Policy Gradient (PADDPG) \citep{HausknechtandStone} is one of the most representative RL algorithm for hybrid action space. The critic network is approximated with off-policy TD learning\citep{Sutton1988ReinforcementLA} and the policy is updated through the Chain Rule \citep{Silver2014DPG}. \citeauthor{JiechaoXiong} propose a framework called Parameterized Deep Q-Networks (PDQN)\citep{JiechaoXiong}. The core idea is to update the discrete-continuous action policies separately combining the structure of DQN\citep{Mnih2015DQN} and DDPG\citep{Lillicrap2015DDPG}. It define a deterministic function which maps the state and each discrete action k to its corresponding continuous parameter: $x_{k}=\mu_{k}(s ; \theta)$, then updates the action-value function Q by minimizing: \begin{equation} \label{equation:2} l(\omega)=\frac{1}{2}\left[Q\left(s, k, x_{k} ; \omega\right)-y\right]^{2} \end{equation} where $y=r+\max _{k \in[K]} \gamma Q\left(s^{\prime}, k, \mu_{k}\left(s^{\prime} ; \theta\right) ; \omega\right)$. The policy $\mu_{k}$ for the continuous part is updated by minimizing the following loss: \begin{equation} \label{equation:3} l(\theta)=-\sum_{k=1}^{K} Q\left(s, k, \mu_{k}(s ; \theta) ; \omega\right) \end{equation} \end{comment} \section{Hybrid Action Representation (HyAR\xspace)} \label{section:model} As mentioned in previous sections, it is non-trivial for an RL agent to learn with discrete-continuous hybrid action space efficiently due to the heterogeneity and action dependence. Naive solutions by converting the hybrid action space into either a discrete or a continuous action space can result in degenerated performance due to the scalability issue and additional approximation difficulty. Previous efforts concentrate on proposing specific policy structures \citep{HausknechtandStone, Haotian2019} that are feasible to learn hybrid-action policies directly over original hybrid action space. However, these methods fail in providing the three desired properties: scalability, stationarity and action dependence simultaneously (See Tab.~\ref{table:alg_comparison}). Inspired by recent advances in Representation Learning for RL \citep{WilliamF, YashChandak}, we propose Hybrid Action Representation (HyAR\xspace), a novel framework that converts the original hybrid-action policy learning into a continuous policy learning problem among the latent action representation space. The intuition behind HyAR\xspace is that discrete action and continuous parameter are heterogeneous in their original representations but they jointly influence the environment; thus we can assume that hybrid actions lie on a homogeneous manifold that is closely related to environmental dynamics semantics. In the following, we introduce an unsupervised approach of constructing a compact and decodable latent representation space to approximate such a manifold. \begin{figure*} \centering \includegraphics[width =0.98\textwidth]{hybrid_action_embedding7.pdf} \caption{Illustrations of: (\textit{left}) the framework DRL with HyAR; and (\textit{right}) overall workflow of hybrid action representation model, consisting of an embedding table and a conditional VAE. } \label{figure:2} \end{figure*} \begin{comment} Representation techniques are widely studied in reinforcement learning and verified to be beneficial for RL, e.g., structural state representation promotes generalization~\citep{MPR, CURL}. In practice, hybrid action space is common, critical and challenge for RL (e.g., direction and speed decisions in the robotic control). In general, hybrid action space is heterogeneous and intuitively has more semantic relations. The intuition behind HyAR\xspace is that xxx. We first introduce xxx. \end{comment} \subsection{Dependence-aware Encoding and Decoding} \label{section:Auto-encoding} A desired latent representation space for hybrid actions should take the dependence between the two heterogeneous components into account. Moreover, we need the representation space to be decodable, i.e., the latent actions selected by a latent policy can be mapped back to the original hybrid actions so as to interact with the environment. To this end, we propose dependence-aware encoding and decoding of hybrid action. The overall workflow is depicted in the right of Fig.~\ref{figure:2}. We establish an embedding table $E_{\zeta} \in \mathbb{R}^{K \times d_1}$ with learnable parameter $\zeta$ to represent the $K$ discrete actions, where each row $e_{\zeta,k} = E_{\zeta}(k)$ (with $k$ being the row index) is a $d_1$-dimensional continuous vector for the discrete action $k$. Then, we use a conditional Variational Auto-Encoder (VAE) \citep{DiederikP} to construct the latent representation space for the continuous parameters. In specific, for a hybrid action $k,x_k$ and a state $s$, the encoder $q_{\phi}(z \mid x_{k}, s, e_{\zeta,k})$ parameterized by $\phi$ takes $s$ and the embedding $e_{\zeta,k}$ as condition, and maps $x_k$ into the latent variable $z \in \mathbb{R}^{d_2}$. With the same condition, the decoder $p_{\psi}(\tilde{x}_k \mid z, s, e_{\zeta,k})$ parameterized by $\psi$ then reconstructs the continuous parameter $\tilde{x}_k$ from $z$. In principle, the conditional VAE can be trained by maximizing the variational lower bound \citep{DiederikP}. More concretely, we adopt a Gaussian latent distribution $\mathcal{N}(\mu_x,\sigma_x)$ for $q_{\phi}(z \mid x_{k}, s, e_{\zeta,k})$ where $\mu_x,\sigma_x$ are the mean and standard deviation outputted by the encoder. For any latent variable sample $z \sim \mathcal{N}(\mu_x,\sigma_x)$, the decoder decodes it deterministicly, i.e., $\tilde{x}_k = p_{\psi}(z, s, e_{\zeta,k}) = g_{\psi_1} \circ f_{\psi_0} (z, s, e_{\zeta,k})$, where $f_{\psi_0}$ is a transformation network and $g_{\psi_1}$ is a fully-connected layer for reconstruction. We use $\psi = \cup_{i\in\{0,1,2\}} \psi_i$ to denote the parameters of both the decoder network and prediction network (introduced later in Sec.~\ref{section:dynamics-predictive}) as well as the transformation network they share. With a batch of states and original hybrid actions from buffer $\mathcal{D}$, we train the embedding table $E_{\zeta}$ and the conditional VAE $q_{\phi},p_{\psi}$ together by minimizing the loss function $L_{\text{VAE}}$ below: \begin{equation} \label{equation:6} \begin{aligned} L_{\text{VAE}}(\phi,\psi,\zeta) = \ \mathbb{E}_{s,k,x_k \sim \mathcal{D}, z \sim q_{\phi}} \Big[ \| x_k - \tilde{x}_k \|_{2}^{2} + D_{\text{KL}} \big( q_{\phi}(\cdot \mid x_{k}, s, e_{\zeta,k} ) \| \mathcal{N}(0,I) \big) \Big], \end{aligned} \end{equation} where the first term is the $L_2$-norm square reconstruction error and the second term is the Kullback-Leibler divergence $D_{\text{KL}}$ between the variational posterior of latent representation $z$ and the standard Gaussian prior. Note $\tilde{x}_k$ is differentiable with respect to $\psi$, $\zeta$ and $\phi$ through reparameterization trick \citep{DiederikP}. \begin{comment} We argue that discrete and continuous actions are heterogeneous different and can be represented separately. Fig.~\ref{figure:2} depicts the overall workflow. For discrete actions, we adopts an one-to-one mapping to link the raw action and its latent representation. In specific, given $n$ discrete actions, an embedding table $W \in \mathbb{R}^{n \times d}$ is maintained, where each row is a learnable $d$-dimensional embedding vector, denoted by $e_{\zeta,k}$ (with $k$ being the row index). For continuous parameters, we adopt Variational Auto-Encoder \citep{DiederikP} to construct the mapping between the raw action space and latent space. An encoder is trained to map the raw continuous actions into latent space, and a decoder to achieve the reverse mapping. In specific, the encoder $q_{\phi}(z | x_{k}, s,e_{\zeta,k})$ parameterized by $\phi$ takes as inputs the state $s$, $i$-th discrete action's embedding $e_{\zeta,k}$ and raw continuous action $x_{k}$, and generates the corresponding latent representation $z_{i}$ for action $x_{k}$. Give the latent representation $z$, the decoder $p_{\psi}(x_{k} | z, s,e_{\zeta,k})$ parameterized by $\psi$ outputs action $x_{k}$ in raw continuous action space. Both encoder and decoder are trained by maximizing a variational lower bound as follows: \begin{equation} \label{equation:6} \begin{aligned} L_{\text{VAE}}(\phi,\psi,W)=\mathbb{E}_{z \sim q_{\phi}}\left[\log p_{\psi}(x_{k}\mid z, s,e_{\zeta,k})\right] \\ -\mathcal{D}_{K L}\left[q_{\phi}\left(z\mid x_{k}, s,e_{\zeta,k}\right) \| P(z \mid e_{\zeta,k},s)\right]. \end{aligned} \end{equation} where $q_{\phi}$ and $p_{\psi} $ are the encoder and the decoder with parameters $\phi $ and $\psi$, respectively. $D_{KL}$ is Kullback-Leibler divergence between the encoder output and the prior of z. The prior $ P(z \mid e_{\zeta,k},s)$ is set to a normal distribution $\mathcal{N}(0,1)$. Ideally, given a latent representation $z \sim p_\phi(\cdot | e_{\zeta,k}, x_k, s)$, the decoder is very likely to output the raw action $x_{k}$ under the distribution $p_{\psi}(\cdot | z, s,e_{\zeta,k})$. \end{comment} The embedding table and conditional VAE jointly construct a compact and decodable hybrid action representation space ($\in \mathbb{R}^{d_1 + d_2}$) for hybrid actions. We highlight that this is often much smaller than the joint action space $\mathbb{R}^{K + \sum_{k} |\mathcal{X}_k|}$ considered in previous works (e.g., PADDPG, PDQN and HPPO), especially when $K$ or $\sum_{k} |\mathcal{X}_k|$ is large. In this sense, HyAR\xspace is expected to be more scalable when compared in Tab.~\ref{table:alg_comparison}. Moreover, the conditional VAE embeds the dependence of continuous parameter on corresponding discrete action in the latent space; and allows to avoid the redundancy of outputting all continuous parameters at any time (i.e., $\mathbb{R}^{\sum_{k} |\mathcal{X}_k|}$). This resembles the conditional structure adopted by HHQN \citep{Haotian2019} while HyAR is free of the non-stationary issue thanks to learning a single policy in the hybrid representation space. For any latent variables $e \in \mathbb{R}^{d_1}$ and $z_x \in \mathbb{R}^{d_2}$, they can be decoded into hybrid action $k,x_k$ conveniently by nearest-neighbor lookup of the embedding table along with the VAE decoder. Formally, we summarize the encoding and decoding process below: \begin{equation} \label{equation:encode_and_decode} \begin{aligned} \textbf{Encoding:} & \ \ e_{\zeta,k} = E_{\zeta}(k), \ \ z_x \sim q_{\phi}(\cdot \mid x_{k}, s, e_{\zeta,k} ) \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \ \ \ \text{for} \ s,k,x_k \\ \textbf{Decoding:} & \ \ k = g_{E}(e) = \operatorname{\arg\min}_{k^{\prime} \in \mathcal{K}}\|e_{\zeta,k^{\prime}} - e \|_{2}, \ \ x_k = p_{\psi} ( z_x, s, e_{\zeta,k} ) \quad \ \text{for} \ s, e, z_x \end{aligned} \end{equation} \subsection{Dynamics Predictive Representation} \label{section:dynamics-predictive} In the above, we introduce how to construct a compact and decodable latent representation space for original hybrid actions. However, the representation space learned by pure reconstruction of VAE may be pathological in the sense that it is not discriminative to how hybrid actions have different influence on the environment, similarly studied in \citep{Grosnit2021HDLBO}. Therefore, such a representation space may be ineffective when involved in the learning of a RL policy and value functions, as these functions highly depends on the knowledge of environmental dynamics. To this end, we make full use of environmental dynamics and propose an unsupervised learning loss based on state dynamics prediction to further refine the hybrid action representation. Intuitively, the dynamics predictive representation learned is semantically smooth. In other words, hybrid action representations that are closer in the space reflects similar influence on environmental dynamics of their corresponding original hybrid actions. Therefore, in principle such a representation space can be superior in the approximation and generalization of RL policy and value functions, than that learned purely from VAE reconstruction. The benefits of dynamics predictive representation are also demonstrated in \citep{WilliamF} \citep{MPR}. As shown in the right of Fig.~\ref{figure:2}, HyAR\xspace adopts a subnetwork $h_{\psi_2}$ that is cascaded after the transformation network $f_{\phi_0}$ of the conditional VAE decoder (called \textit{cascaded structure} or \textit{cascaded head} below) to produce the prediction of the state residual of transition dynamics. For any transition sample $(s,k,x_k,s^{\prime})$, the state residual is denoted by $\delta_{s,s^{\prime}}=s^{\prime}-s$. With some abuse of notation (i.e., $p_{\psi} = h_{\psi_2} \circ f_{\psi_0}$ here), the prediction $\tilde{\delta}_{s,s^{\prime}}$ is produced as follows, which completes Eq.~\ref{equation:encode_and_decode}: \begin{equation} \label{equation:prediction} \begin{aligned} \textbf{Prediction:} & \ \ \tilde{\delta}_{s,s^{\prime}} = p_{\psi} ( z_x, s, e_{\zeta,k} ) \quad \ \ \text{for} \ s, e, z_x \end{aligned} \end{equation} Then we minimize the $L_2$-norm square prediction error: \begin{equation} \label{equation:11} L_{\text{Dyn}}(\phi,\psi,\zeta) = \mathbb{E}_{s,k,x_k,s^{\prime}} \left[ \|\tilde{\delta}_{s,s^{\prime}}-\delta_{s,s^{\prime}} \|_{2}^{2} \right]. \end{equation} Our structure choice of cascaded prediction head is inspired by \citep{MYOV}. The reason behind this is that dynamics prediction could be more complex than continuous action reconstruction, thus usual parallel heads for both reconstruction and the state residual prediction followed by the same latent features may have interference in optimizing individual objectives and hinder the learning of the shared representation. So far, we derive the ultimate training loss for hybrid action representation as follows: \begin{equation} \label{equation:12} \begin{aligned} L_{\text{HyAR}}(\phi,\psi,\zeta)= L_{\text{VAE}}(\phi,\psi,\zeta)+\beta L_{\text{Dyn}}(\phi,\psi,\zeta), \end{aligned} \end{equation} where $\beta$ is a hyper-parameter that weights the dynamics predictive representation loss. Note that the ultimate loss depends on reward-agnostic data of environmental dynamics, which is dense and usually more convenient to obtain \citep{StookeLAL21Decouple,YaratsFLP21ProtoRL,Erraqabi21Exploration}. \section{DRL with Hybrid Action Representation} \label{section:drl-approach} In previous section, we introduce the construction of a compact, decodable and semantically smooth hybrid action representation space. As the conceptual overview in Fig.~\ref{figure:conceptual_overview}, the next thing is to learn a latent RL policy in the representation space. In principle, our framework is algorithm-agnostic and any RL algorithms for continuous control can be used for implementation. In this paper, we adopt model-free DRL algorithm TD3 \citep{TD3} for demonstration. Though there remains the chance to build a world model based on hybrid action representation, we leave the study on model-based RL with HyAR for future work. \begin{algorithm}[t] \small Initialize actor $\pi_{\omega}$ and critic networks $Q_{\theta_{1}}, Q_{\theta_{2}}$ with random parameters $\omega, \theta_{1}, \theta_{2}$ Initialize discrete action embedding table $E_{\zeta}$ and conditional VAE $q_{\phi},p_{\psi}$ with random parameters $\zeta,\phi,\psi$ Prepare replay buffer $\mathcal{D}$ \Repeat( Stage \xspace\circled{1}){reaching maximum warm-up training times}{ Update $\zeta$ and $\phi,\psi$ using samples in $\mathcal{D}$ \Comment{see Eq.~\ref{equation:12}}\\ } \Repeat( Stage \xspace\circled{2}){reaching maximum total environment steps}{ \For{t $\leftarrow$ 1 to $ T$}{ \textcolor{blue}{// select latent actions in representation space}\\ $e, z_{x} = \pi_{\omega}(s) + \epsilon_{\rm e}$, with $\epsilon_{\rm e} \sim \mathcal{N}(0,\sigma)$\\ \textcolor{blue}{// decode into original hybrid actions}\\ $k =g_{E}(e), x_{k} = p_{\psi} (z_{x}, s, e_{\zeta,k}) $ \Comment{see Eq. \ref{equation:encode_and_decode}}\\ Execute $(k,x_{k})$, observe $r_t$ and new state $s^{\prime}$\\ Store $\{s, k, x_{k}, e, z_{x}, r, s^{\prime}\}$ in $\mathcal{D}$\\ Sample a mini-batch of $N$ experience\ from $\mathcal{D}$\\ Update $Q_{\theta_{1}}, Q_{\theta_{2}}$ \Comment{see Eq. \ref{equation:critic_update}}\\ Update $\pi_{\omega}$ with policy gradient \Comment{see Eq. \ref{equation:actor_update}}\\ } \Repeat{reaching maximum representation training times}{ Update $\zeta$ and $\phi,\psi$ using samples in $\mathcal{D}$ \Comment{see Eq.~\ref{equation:12}}\\ } } \caption{ HyAR-TD3 } \label{alg:hyar} \end{algorithm} TD3 is popular deterministic-policy Actor-Critic algorithm which is widely demonstrated to be effective in continuous control. As illustrated in the left of Fig.~\ref{figure:2}, with the learned hybrid action representation space, the actor network parameterizes a latent policy $\pi_{\omega}$ with parameter $\omega$ that outputs the latent action vector, i.e., $e,z_x=\pi_{\omega}(s)$ where $e \in \mathbb{R}^{d_1}, z_x \in \mathbb{R}^{d_2}$. The latent action can be decoded according to Eq.~\ref{equation:encode_and_decode} and obtain the corresponding hybrid action $k, x_k$. The double critic networks $Q_{\theta_1},Q_{\theta_2}$ take as input the latent action to approximate hybrid-action value function $Q^{\pi_{\omega}}$, i.e., $Q_{\theta_{i=1,2}}(s,e,z_x) \approx Q^{\pi_{\omega}}(s,k,x_k)$. With a buffer of collected transition sample $(s,e,z_x,r,s^{\prime})$, the critics are trained by Clipped Double Q-Learning, with the loss function below for $i=1,2$: \begin{equation} \label{equation:critic_update} \begin{aligned} L_{\text{CDQ}}(\theta_{i}) & = \mathbb{E}_{s,e,z_x,r,s^{\prime}} \left[ \left( y-Q_{\theta_{i}}(s,e, z_{x}) \right)^{2} \right], & \text{where} \ \ y = r+\gamma \min _{j=1,2} Q_{\bar{\theta}_{j}}\left(s^{\prime}, \pi_{\bar{\omega}}(s^{\prime}) \right), \end{aligned} \end{equation} where $\bar{\theta}_{j=1,2},\bar{\omega}$ are the target network parameters. The actor (latent policy) is updated with Deterministic Policy Gradient \citep{Silver2014DPG} as follows: \begin{equation} \label{equation:actor_update} \nabla_{\omega} J(\omega)=\mathbb{E}_{s} \left[ \nabla_{\pi_{\omega}(s)} Q_{\theta_1}(s, \pi_{\omega}(s)) \nabla_{\omega} \pi_{\omega}(s) \right]. \end{equation} Algorithm \ref{alg:hyar} describes the pseudo-code of HyAR-TD3, containing two major stages: \circled{1} \textit{\textbf{warm-up stage}} and \circled{2} \textit{\textbf{training stage}}. In the warm-up stage, the hybrid action representation models are pre-trained using a prepared replay buffer $\mathcal{D}$ (line 4-6). The parameters the embedding table and conditional VAE is updated by minimizing the VAE and dynamics prediction loss. Note that the proposed algorithm has no requirement on how the buffer $\mathcal{D}$ is prepared and here we simply use a random policy for the environment interaction and data generation by default. In the learning stage, given a environment state, the latent policy outputs a latent action perturbed by a Gaussian exploration noise, with some abuse of notions $e,z_x$ (line 10). The latent action is decoded into original hybrid action so as to interact with the environment, after which the collected transition sample is stored in the replay buffer (line 12-14). Then, the latent policy learning is preformed using the data sampled from $\mathcal{D}$ (line 15-17). It is worth noting that the action representation model is updated concurrently in the training stage to make continual adjustment to the change of data distribution (line 19-21). \begin{wrapfigure}{r}{0cm} \begin{minipage}[t]{.56\linewidth} \centering \vspace{-0.8cm} \hspace{-0.1cm} \includegraphics[width=0.97\textwidth]{two_skill.pdf} \caption{Illustrations of representation unreliability and representation shift. Dots denote the hybrid action representations selected by policy (red) and known by encoder (blue). Gray lines form the areas, among which representations can be well decoded and estimated.} \label{fig:cons} \vspace{-0.4cm} \end{minipage} \end{wrapfigure} One significant distinction of DRL with HyAR described above compared with conventional DRL is that, the hybrid action representation space is learned from finite samples that are drawn from a moving data distribution. The induced \textit{unreliability} and \textit{shift} of learned representations can severely cripple the performance of learned latent policy if they are not carefully handled. Hence, we propose two mechanisms to deal with the above two considerations as detailed below. \paragraph{Latent Space Constraint (LSC)} As the latent representation space is constructed by finite hybrid action samples, some areas in the latent space can be highly unreliable in decoding as well as $Q$-value estimation. Similar evidences are also founded in \citep{PLAS, Notin}. In Fig.~\ref{fig:cons}(a), the latent action representations inside the boundary can be well decoded and estimated the values, while the outliers cannot. Once the latent policy outputs outliers, which can be common in the early learning stage, the unreliability can quickly deteriorate the policy and lead to bad results. Therefore, we propose to constrain the action representation space of the latent policy inside a reasonable area adaptively. In specific, we re-scale each dimension of the output of latent policy (i.e., $[-1, 1]^{d_1 + d_2}$ by tanh activation) to a bounded range $[b_\text{lower}, b_\text{upper}]$. For a number of $s,k,x_k$ collected previously, the bounds $b_\text{lower}, b_\text{upper}$ are obtained by calculating the $c$-percentage central range where $c \in [0,100]$. We empirically demonstrate the importance of LSC. See more details in Appendix~\ref{appendix:LSC_and_RSC} \& \ref{appendix:ablation_curves}. \paragraph{Representation Shift Correction (RSC)} As in Algorithm \ref{alg:hyar}, the hybrid action representation space is continuously optimized along with RL process. Thus, the representation distribution of original hybrid actions in the latent space can shift after a certain learning interval~\citep{Igl}. Fig.~\ref{fig:cons}(b) illustrates the shift (denoted by different shapes). This negatively influences the value function learning since the outdated latent action representation no longer reflects the same transition at present. To handle this, we propose a representation relabeling mechanism. In specific, for each mini-batch training in Eq.\ref{equation:critic_update}, we check the semantic validity of hybrid action representations in current representation space and relabel the invalid ones with the latest representations. In this way, the policy learning is always performed on latest representations, so that the issue of representation shift can be alleviated. Empirically evaluations demonstrate the superiority of relabeling techniques in achieving a better performance with a lower variance. See more details in Appendix~\ref{appendix:LSC_and_RSC} \& \ref{appendix:ablation_curves}. \section{Experiments} We evaluate HyAR\xspace in various hybrid action environments against representative prior algorithms. Then, a detailed ablation study is conducted to verify the contribution of each component in HyAR\xspace. Moreover, we provide visual analysis for better understandings of HyAR\xspace. \subsection{Experiment setups} \begin{figure} \centering \includegraphics[width=0.90\textwidth]{all_environment3.pdf} \caption{Benchmarks with discrete-continuous actions: (a) the agent selects a discrete action (run, hop, leap) and the corresponding continuous parameter (horizontal displacement) to reach the goal; (b) The agent selects a discrete strategy (move, shoot) and the continuous 2-D coordinate to score; (c) The agent selects a discrete action (move, catch) and the continuous parameter (direction) to grab the target point; (d) The agent has $n$ equally spaced actuators. It can choose whether each actuator should be on or off (thus $2^n$ combination in total) and determine the corresponding continuous parameter for each actuator (moving distance) to reach the target area. } \vspace{-2mm} \label{figure:4} \end{figure} \paragraph{Benchmarks} Fig.~\ref{figure:4} visualizes the evaluation benchmarks, including the \textit{Platform} and \textit{Goal} from \citep{WarwickMasson}, \textit{Catch Point} from \citep{ZhouFan2019}, and a newly designed \textit{Hard Move} specific to the evaluation in larger hybrid action space. We also build a complex version of Goal, called \textit{Hard Goal}. All benchmarks have hybrid actions and require the agent to select reasonable actions to complete the task. See complete description of benchmarks in Appendix~\ref{appendix:exp_details_setups}. \paragraph{Baselines} Four state-of-the-art approaches are selected as baselines: HPPO \citep{ZhouFan2019}, PDQN \citep{JiechaoXiong}, PADDPG \citep{HausknechtandStone}, HHQN \citep{Haotian2019}. In addition, for a comprehensive study, we extend the baselines which consists of DDPG to their TD3 variants, denoted by PDQN-TD3, PATD3, HHQN-TD3. Last, we use HyAR-DDPG and HyAR-TD3 to denote our implementations of DRL with HyAR\xspace based on DDPG and TD3. For a fair comparison, the network architecture (i.e., DDPG and TD3) used in associated baselines are the same. For all experiments, we give each baseline the same training budget. For our algorithms, we use a random strategy to interact with the environment for 5000 episodes during the warm-up stage. For each experiment, we run 5 trials and report the average results. Complete details of setups are provided in Appendix~\ref{appendix:exp_details}. \begin{table} \centering \scalebox{0.62}{\begin{tabular}{cc|cccc|cccc} \toprule \multirow{2}{*}{\textbf{ENV}\vspace{-5pt} } & \textbf{HPPO} & \textbf{PADDPG} & \textbf{PDQN} & \textbf{HHQN} & \textbf{HyAR-DDPG} & \textbf{PATD3} & \textbf{PDQN-TD3} & \textbf{HHQN-TD3} & \textbf{HyAR-TD3}\\ \cmidrule{2-10} & \multicolumn{1}{c|}{\textbf{PPO-based}} & \multicolumn{4}{c|}{\textbf{DDPG-based}} & \multicolumn{4}{c}{\textbf{TD3-based}}\\ \midrule Goal & 0.0 $\pm$ 0.0 & 0.05 $\pm$ 0.10 & 0.70 $\pm$ 0.07 & 0.0$\pm$0.0 &0.53$\pm$0.02& 0.0$\pm$0.0 & 0.71$\pm$0.10 &0.0$\pm$0.0 & \textbf{0.78$\pm$0.03} \\ Hard Goal & 0.0 $\pm$ 0.0 & 0.0 $\pm$ 0.0 & 0.0 $\pm$ 0.0 & 0.0$\pm$0.0 &0.30$\pm$0.08 & 0.44$\pm$0.05 & 0.06$\pm$0.07 &0.01$\pm$0.01 & \textbf{0.60$\pm$0.07} \\ Platform & 0.80 $\pm$ 0.02 & 0.36 $\pm$ 0.06 & 0.93 $\pm$ 0.05 & 0.46$\pm$0.25 &0.87$\pm$0.06 & 0.94$\pm$0.10 & 0.93$\pm$0.03&0.62$\pm$0.23 & \textbf{0.98$\pm$0.01} \\ Catch Point & 0.69 $\pm$ 0.09 & 0.82 $\pm$ 0.06 & 0.77 $\pm$ 0.07 & 0.31$\pm$0.06 &0.89$\pm$0.01 & 0.82$\pm$0.10 & 0.89$\pm$0.07 &0.27$\pm$0.05 & \textbf{0.90$\pm$0.03} \\ Hard Move (n = 4) & 0.09 $\pm$ 0.02 & 0.03 $\pm$ 0.01 & 0.69 $\pm$ 0.07 & 0.39$\pm$0.14 &0.91$\pm$0.03 & 0.66$\pm$0.13 &0.85$\pm$0.10&0.52$\pm$0.17 & \textbf{0.93$\pm$0.02} \\ Hard Move (n = 6) & 0.05 $\pm$ 0.01 & 0.04 $\pm$ 0.01 & 0.41 $\pm$ 0.05 & 0.32$\pm$0.17 &0.91$\pm$0.04 & 0.04$\pm$0.02 &0.74$\pm$0.08&0.29$\pm$0.13 & \textbf{0.92$\pm$0.04} \\ Hard Move (n = 8)& 0.04 $\pm$ 0.01 & 0.06 $\pm$ 0.03 & 0.04 $\pm$ 0.01 & 0.05$\pm$0.02 &0.85$\pm$0.06 & 0.06$\pm$0.02&0.05$\pm$0.01&0.05$\pm$0.02 &\textbf{0.89$\pm$0.03} \\ Hard Move (n = 10) & 0.05 $\pm$ 0.01 & 0.04 $\pm$ 0.01 & 0.06 $\pm$ 0.02 & 0.04$\pm$0.01 &\textbf{0.82$\pm$0.06} & 0.07$\pm$0.02 &0.05$\pm$0.02&0.05$\pm$0.02 & 0.75$\pm$0.05 \\ \bottomrule \end{tabular}} \caption{Comparisons of the baselines regarding the average performance at the end of training process with the corresponding standard deviation over 5 runs. Values in bold indicate the best results in each environment.} \label{table:baseline} \vspace{-2mm} \end{table} \subsection{Performance Evaluation} \label{section:evaluation} To conduct a comprehensive comparison, all baselines implemented based on either DDPG or TD3 are reported. To counteract implementation bias, codes of PADDPG, PDQN, and HHQN are directly adopted from prior works. Comparisons in terms of the averaged results are summarized in Tab.~\ref{table:baseline}, where bold numbers indicate the best result. Overall, we have the following findings. HyAR\xspace-TD3 and HyAR\xspace-DDPG show the better results and lower variance than the others. Moreover, the advantage of HyAR is more obvious in environments in larger hybrid action space (e.g., Hard Goal \& Hard Move). Taking Hard Move for example, as the action space grows exponentially, the performance of HyAR\xspace is steady and barely degrades, while the others deteriorate rapidly. Similar results can be found in Goal and Hard Goal environments. This is due to the superiority of HyAR\xspace of utilizing the hybrid action representation space, among which the latent policy can be learned based on compact semantics. These results not only reveal the effectiveness of HyAR\xspace in achieving better performance, but also the scalability and generalization. In almost all environments, HyAR\xspace outperforms other baselines for both the DDPG-based and TD3-based cases. The exceptions are in Goal and Platform environments, where PDQN performs slightly better than HyAR\xspace-DDPG. We hypothesize that this is because the hybrid action space of these two environments is relatively small. For such environments, the learned latent action space could be sparse and noisy, which in turn degrades the performance. One evidence is that the conservative (underestimation) nature in TD3 could compensate and alleviates this issue, achieving significant improvements (HyAR\xspace-TD3 v.s. HyAR\xspace-DDPG). Fig.~\ref{figure:6} renders the learning curves, where HyAR-TD3 outperforms other baselines in both the final performance and learning speed across all environments. Similar results are observed in DDPG-based comparisons and can be found in Appendix~\ref{appendix:hyar_ddpg_curves}. In addition, HyAR\xspace-TD3 shows good generalization across environments, while the others more or less fail in some environments (e.g., HPPO, PATD3, and HHQN-TD3 fail in Fig.~\ref{figure:6}(a) and PDQN-TD3 fails in Fig.~\ref{figure:6}(b)). Moreover, when environments become complex (Fig.~\ref{figure:6}(e-h)), HyAR\xspace-TD3 still achieves steady and better performance, particularly demonstrating the effectiveness of HyAR\xspace in high-dimensional hybrid action space. \begin{figure*}[t] \centering \vspace{-0.2cm} \hspace{-0.3cm} \subfigure[goal]{ \includegraphics[width=0.27\textwidth]{myplot_goal_td3.pdf} } \hspace{-0.7cm} \subfigure[hard goal]{ \includegraphics[width=0.27\textwidth]{myplot_hard_goal_td3.pdf} } \hspace{-0.7cm} \subfigure[platform]{ \includegraphics[width=0.27\textwidth]{myplot_platform_td3.pdf} } \hspace{-0.7cm} \subfigure[catch point]{ \includegraphics[width=0.27\textwidth]{myplot_catch_point_td3.pdf} }\\ \vspace{-0.3cm} \hspace{-0.3cm} \subfigure[hard move (n = 4)]{ \includegraphics[width=0.27\textwidth]{myplot_hard_move_4_td3.pdf} } \hspace{-0.7cm} \subfigure[hard move (n = 6)]{ \includegraphics[width=0.27\textwidth]{myplot_hard_move_6_td3.pdf} } \hspace{-0.7cm} \subfigure[hard move (n = 8)]{ \includegraphics[width=0.27\textwidth]{myplot_hard_move_8_td3.pdf} } \hspace{-0.7cm} \subfigure[hard move (n = 10)]{ \includegraphics[width=0.27\textwidth]{myplot_hard_move_10_td3.pdf} } \caption{Comparisons of algorithms in different environments. The x- and y-axis denote the environment steps ($\times 10^5$) and average episode reward over recent 100 episodes. The curve and shade denote the mean and a standard deviation over 5 runs. } \label{figure:6} \vspace{-2mm} \end{figure*} \subsection{Ablation Study and Visual Analysis} \label{section:ablation} We further evaluate the contribution of the major components in HyAR\xspace: the two mechanisms for latent policy learning, i.e., latent space constraint (LSC) and representation shift correction (RSC), and the dynamics predictive representation loss. We briefly conclude our results as follows. For LSC, properly constraining the output space of the latent policy is critical to performance; otherwise, both loose and conservative constraints dramatically lead to performance degradation. RSC and dynamics predictive representation loss show similar efficacy: they improve both learning speed and convergence results, additionally with a lower variance. Such superiority is more significant in the environment when hybrid actions are more semantically different (e.g., Goal). We also conduct ablation studies on other factors along with hyperparameter analysis. See complete details and ablation results in Appendix~\ref{appendix:dynamics_prediction_curves} \& \ref{appendix:ablation_curves}. \begin{wrapfigure}{r}{0cm} \begin{minipage}[t]{.55\linewidth} \centering \vspace{-0.65cm} \hspace{-0.35cm} \subfigure[Goal]{ \includegraphics[width=0.475\textwidth]{myplot_goal_tsne_state.pdf} } \hspace{-0.1cm} \subfigure[Hard Move (n = 8)]{ \includegraphics[width=0.475\textwidth]{myplot_hard_move_tsne_state.pdf} } \caption{2D t-SNE visualizations of learned representation for original hybrid actions, colored by 1D t-SNE of the corresponding environmental impact.} \label{figure:tsne} \vspace{-0.3cm} \end{minipage} \end{wrapfigure} \begin{comment} \begin{figure} \centering \subfigure[Goal]{ \includegraphics[width=0.22\textwidth]{myplot_goal_tsne_state.pdf} } \hspace{-0.1cm} \subfigure[Hard Move (n = 8)]{ \includegraphics[width=0.22\textwidth]{myplot_hard_move_tsne_state.pdf} } \caption{2D t-SNE visualizations of latent action representations, colored by 1D t-SNE of the corresponding environmental impact. } \label{figure:tsne} \end{figure} \end{comment} Finally, we adopt t-SNE \citep{Maaten2008TSNE} to visualize the learned hybrid action representations, i.e., ($e, z_x$), in a 2D plane. We color each action based on its impact on the environment i.e., $\tilde{\delta}_{s,s^{\prime}}$. As shown in Fig.~\ref{figure:tsne}, we observe that actions with a similar impact on the environment are relatively closer in the latent space. This demonstrates the dynamics predictive representation loss is helpful for deriving dynamics-aware representation for further improving the learning performance, efficacy, and stability (see results in Appendix~\ref{appendix:dynamics_prediction_curves} \& \ref{appendix:visual_results}) \section{Conclusion} In this paper, we propose Hybrid Action Representation (HyAR\xspace) for DRL agents to efficiently learn with discrete-continuous hybrid action space. HyAR\xspace use an unsupervised method to derive a compact and decodable representation space for discrete-continuous hybrid actions. HyAR\xspace can be easily extended with modern DRL methods to leverage additional advantages. Our experiments demonstrate the superiority of HyAR\xspace regarding performance, learning speed and robustness in most hybrid action environment, especially in high-dimensional action spaces. \section*{Acknowledgments} The work is supported by the National Science Fund for Distinguished Young Scholars (Grant No.: 62025602), the National Natural Science Foundation of China (Grant Nos.: 11931015, 62106172), the XPLORER PRIZE, and the New Generation of Artificial Intelligence Science and Technology Major Project of Tianjin (Grant No.: 19ZXZNGX00010).
{'timestamp': '2022-03-17T01:22:31', 'yymm': '2109', 'arxiv_id': '2109.05490', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05490'}
arxiv
\section{Introduction} A number of scientific machine learning (ML) tasks seek to discover a dynamical system whose solution is consistent with data (e.g. constitutive modeling \cite{patel2020thermodynamically,karapiperis2021data,ghnatios2019data,masi2021thermodynamics}, reduced-order modeling \cite{chen2021physics,lee2021deep,wan2018data}, physics-informed machine learning \cite{karniadakis2021physics,wu2018physics}, and surrogates for performing optimal control \cite{alexopoulos2020digital}). A major challenge for this class of problems is the preservation of both numerical stability and physical realizability when performing out of distribution inference (i.e. extrapolation/forecasting). Unlike traditional ML for e.g. image/language processing tasks, engineering and science models pose strict requirements on physical quantities to guarantee properties such as conservation, thermodynamic consistency and well-posedness of resulting models \cite{baker2019workshop}. These structural constraints translate to desirable mathematical properties for simulation, such as improved numerical stability and accuracy, particularly for chaotic systems \cite{lee2021machine,trask2020enforcing}. While so-called physics-informed ML (PIML) approaches seek to impose these properties by imposing soft physics constraints into the ML process, many applications require structure preservation to hold exactly; PIML requires empirical tuning of weighting parameters and physics properties hold only to within optimization error, which typically may be large \cite{wang2020understanding,rohrhofer2021pareto}. Structure-preserving machine learning has emerged as a means of designing architectures such that physics constraints hold exactly by construction \cite{lee2021machine,trask2020enforcing}. By parameterizing relevant geometric or topological structures, researchers obtain more data-efficient hybrid physics/ML architectures with guaranteed mathematical properties. In this work we consider geometric structure preservation for dynamical systems \cite{hairer2006geometric,marsden1995introduction}. Reversible bracket formalisms (e.g. Hamiltonian/Lagrangian mechanics) have been shown effective for learning reversible dynamics \cite{toth2019hamiltonian,cranmer2020lagrangian,lutter2018deep,chen2019symplectic,jin2020sympnets,tong2021symplectic,zhong2021benchmarking,chen2021data,bertalan2019learning}, while dissipative metric bracket extensions provide generalizations to irreversible dynamics in the metriplectic formalism \cite{lee2021machine,desai2021port,hernandez2021structure,yu2020onsagernet,zhong2020dissipative}. Accounting for dissipation in this manner provides important thermodynamic consistency guarantees: namely, discrete versions of the first and second law of thermodynamics along with a fluctuation-dissipation theorem for thermal systems at microscales. Training these models is however a challenge and leads to discovery of non-interpretable \textit{Casimirs} (generalized entropy and energy functionals describing the system). For $\bm{\StateSymb}(t) \in \mathbb{R}^{n}$ denoting the state of a system at time $t$, $\bm{f}$ denoting a velocity with potentially exploitable mathematical structure, and $\Theta$ denoting trainable parameters, we consider learning of dynamics of the form \begin{equation} \dv{\bm{\StateSymb}(t)}{t} = \Velocity_{\Theta}(\bm{\StateSymb}). \end{equation} We synthesize the Sparse Identification of Nonlinear Dynamics (SINDy) formalism \cite{brunton2016discovering} with neural ordinary differential equations (NODEs) \cite{chen2018neural} to obtain a framework for learning dynamics. This sparse dictionary-learning formalism allows learning of either interpretable $\bm{f}$ when learning "black-box" ODEs, or for learning more complicated bracket dynamics for $\bm{f}$ which describe structure-preserving reversible and irreversible systems. Our main technical contributions include: \begin{itemize} \item a novel extension of SINDy into neural ODE settings, including a training strategy with L1 weight decay and pruning, \item the first application of SINDy with structure-preservation, including: black-box, Hamiltonian, GENERIC, and port-Hamiltonian formulations \item empirical demonstration on the effectiveness of the proposed algorithm for a wide array of dynamics spanning: reversible, irreversible, and chaotic systems. \end{itemize} \section{Sparse Identification of Nonlinear Dynamics (SINDy)} The Sparse Identification of Nonlinear Dynamics (SINDy) method aims to identify the dynamics of interest using a sparse set of dictionaries such that \begin{equation} \Velocity_{\Theta}(\bm{\StateSymb}) = (\pmb{\DictionarySymbol}(\bm{\StateSymb})^{\mathsf{T}} \Xi)^{\mathsf{T}}, \end{equation} where $\Xi \in \mathbb{R}^{p\timesn}$ is the coefficient matrix and $\pmb{\DictionarySymbol}(\bm{\HiddenStateSymb}) \in \mathbb{R}^{1\timesp}$ denotes a ``library'' vector consisting of candidate functions, e.g., constant, polynomials, and so on. From measurements of states (and derivatives), we can construct a linear system of equations: \begin{equation} \dot{X} = \Phi(X) \Xi \end{equation} where $X \in \mathbb{R}^{m\timesn}$ and $\dot{X}\in \mathbb{R}^{m\timesn}$ are collections of the states $\bm{\StateSymb}(t)$ and the (numerically approximated) derivatives $\dv{\bm{\StateSymb}}{t}$ sampled at time indices $\{t_1,\ldots,t_{m}\}$ such that \begin{equation} [X]_{ij} = x_j(t_i), \quad \text{and} \quad [\dot{X}]_{ij} = \dv{x_{j}}{t} {}(t_i). \end{equation} A library, $\Phi(X)\in\mathbb{R}^{m\timesp}$, consists of candidate nonlinear functions, e.g., constant, polynomial, and trigonometric terms: \begin{equation} \Phi(X) = \begin{bmatrix} \mathbbm{1} & X & \mathbbm{P}_2(X) & \cdots & \cos(X) & \cdots \end{bmatrix}, \end{equation} where $\mathbbm{P}_2$ is a function of the quadratic nonlinearities such that the $i$th row of $\mathbbm{P}_2 (X)$ is defined as, for example, with $n=3$, \begin{equation} \begin{split} [\mathbbm{P}_2 (X)]^{\mathsf{T}}_{i} = [x_1^2&(t_i), x_1(t_i) x_2(t_i), \\&x_1(t_i)x_3(t_i), x_2^2(t_i), x_2(t_i)x_3(t_i), x_3^2(t_i)]. \end{split} \end{equation} Lastly, $\Xi\in\mathbb{R}^{p\timesn}$ denotes the collection of the unknown coefficients $\Xi = [\xi_1,\ldots,\xi_{n}]$, where $\xi_i\in\mathbb{R}^{p}$, $i=1,\ldots,n$ are sparse vectors. Typically, only $X$ is available and $\dot{X}$ is approximated numerically. Thus, in SINDy, $\dot{X}$ is considered to be noisy, which leads to a new formulation: \begin{equation} \dot{X} = \Phi(X) \Xi + \eta Z, \end{equation} where $Z$ is a matrix of independent identically distributed unit normal entries and $\eta$ is noise magnitude. To compute the sparse solution $\Xi$, SINDy employs either the least absolute shrinkage and selection operator (LASSO) \cite{tibshirani1996regression} or sequential threshold least-squares method \cite{brunton2016discovering}. LASSO is an L1-regularized regression technique and the sequential threshold least-squares method is an iterative algorithm which repetitively zeroes out entries of $\Xi$ and solves least-squares problems with remaining entries of $\Xi$. \section{Neural SINDy} One evident weakness of SINDy is that it requires the derivatives of the state variable either empirically measured or numerically computed. To resolve this issue, we propose to use the training algorithm introduced in neural ordinary differential equations (NODEs) \cite{chen2018neural} with L1 weight decay. In addition, we propose the magnitude-based pruning strategy to retain only the dictionaries with significant contributions. \subsection{Neural Ordinary Differential Equations} NODEs \cite{chen2018neural} are a family of deep neural network models that parameterize the time-continuous dynamics of hidden states $\bm{\HiddenStateSymb}(t)$ using a system of ODEs: \begin{equation} \dv{\bm{\HiddenStateSymb}(t)}{t} = \Velocity_{\Theta} (\bm{\HiddenStateSymb},t), \end{equation} where $\bm{\HiddenStateSymb}(t)$ is a time-continuous representation of a state, $\Velocity_{\Theta}$ is a parameterized (trainable) velocity function, and $\Theta$ is a set of neural network weights and biases. In the forward pass, given the initial condition $\bm{\HiddenStateSymb}(0)$, a hidden state at any time index can be obtained by solving the initial value problem (IVP). A black-box time integrator can be employed to compute the hidden states with the desired accuracy: \begin{equation} \tilde{\bm{\HiddenStateSymb}}(t_1), \ldots, \tilde{\bm{\HiddenStateSymb}}(t_{m}) = \mathrm{ODESolve}(\bm{\HiddenStateSymb}(0), \Velocity_{\Theta},t_1, \ldots,t_{m}). \end{equation} The model parameters $\Theta$ are then updated with an optimizer, which minimizes a loss function measuring the difference between the output and the target variables. \paragraph{Dictionary-based parameterization} As in the original SINDy formulation, we assume that there is a set of candidate nonlinear functions to represent the dynamics \begin{equation}\label{eq:dict} \Velocity_{\Theta}(\bm{\HiddenStateSymb}) = (\pmb{\DictionarySymbol}(\bm{\HiddenStateSymb})^{\mathsf{T}} \Xi)^{\mathsf{T}}, \end{equation} where, again, $\Xi \in \mathbb{R}^{p\timesn}$ is a trainable coefficient matrix and $\pmb{\DictionarySymbol}(\bm{\HiddenStateSymb}) \in \mathbb{R}^{1\timesp}$ denotes a library vector. In this setting, the learnable parameters of NODE become $\Theta=\Xi$. \paragraph{Sparsity inducing loss: L1 weight decay (Lasso)} Following SINDy, to induce sparsity in $\Xi$ we add an L1 weight decay to the main loss objective for the mean absolute error: \begin{equation}\label{eq:loss} \mathcal L = \frac{1}{n_{\mathrm{train}}} \sum_{\ell=1}^{n_{\mathrm{train}}} \sum_{i=1}^{m} \left\| \bm{\HiddenStateSymb}^{(\ell)}(t_i) - \tilde{\bm{\HiddenStateSymb}}^{(\ell)}(t_i) \right\|_1 + \lambda \left\| \Xi \right\|_1, \end{equation} where $ \left\| X \right\|_1 = \sum_{l,k} \left| \left[ X \right]_{lk} \right|$. \paragraph{Pruning} Taking linear combinations of candidate functions in Eq.~\eqref{eq:dict} admits implementation as a linear layer, specified by $\Xi$, which does not have biases or nonlinear activation. To further sparsify the coefficient matrix $\Xi$, we employ the magnitude-based pruning strategy: \begin{equation}\label{eq:prune} [\Xi]_{lk} = 0\quad \mathrm{if}\quad [\Xi]_{lk} < \tau \end{equation} We find that pruning is essential to find the sparse representation of $\Xi$ and will provide empirical evidence obtained from the numerical experiments. In next Section, we detail how we use the pruning strategy during the training process. \subsection{Training} We employ mini-batching to train the proposed neural network architecture. For each training step, we randomly sample $n_{\mathrm{batch}}$ trajectories from the training set and then randomly sample initial points from the selected $n_{\mathrm{batch}}$ trajectories to assemble $n_{\mathrm{batch}}$ sub-sequences of length $\ell_{\mathrm{batch}}$. We solve IVPs with the sample initial points, measure the loss (Eq.~\eqref{eq:loss}), and update the model parameters $\Theta$ via Adamax. After the update, we prune the model parameters using the magnitude-based pruning as shown in \eqref{eq:prune}. Algorithm \ref{alg:train} summarizes the training procedure. \begin{algorithm}[!ht] \small \SetAlgoLined \caption{Neural SINDy training}\label{alg:train} Initialize $\Theta$\\ \For{$(i = 0;\ i <n_{\max} ;\ i = i + 1)$}{ Sample $n_{\mathrm{batch}}$ trajectories randomly from $\DataSet_{\mathrm{train}}$ \\ Sample initial points randomly from the sampled trajectories: $\bm{\StateSymb}^{r}_{s(r)}$, $s(r)\in[0,\ldots,m-\ell_{\mathrm{batch}}-1]$ for $r=1,\ldots,n_{\mathrm{batch}}$\\ $\tilde{\bm{\StateSymb}}(t_1)\!,\ldots,\!\tilde{\bm{\StateSymb}}(t_m) \!\!=\!\! \mathrm{ODESolve}(\bm{\StateSymb}^{r}_{s(r)}, \Velocity_{\Theta},t_1, \!\ldots\!, t_{m})$, for $r=1,\ldots,n_{\mathrm{batch}}$\\ Compute the loss $\mathcal L$ (Eq. \eqref{eq:dict}) \\ Update $\Theta$ via SGD\\ Prune $\Theta$ based on the magnitude (Eq. \eqref{eq:prune}) } \end{algorithm} \begin{table*}[t] \centering \begin{tabular}{l|l|l} \hline Eq. name & Ground truth & Identified \\ \hline \multirow{2}{*}{Hyperbolic} & $\dot{x} = -0.05x$ & $\dot{x} = -0.050006x$\\ & $\dot{y} = x^2-y$ & $\dot{y} = 1.000063 x^2-1.000063y$\\ \hline \multirow{2}{*}{Cubic oscillator} & $\dot{x} = -0.1x^3 +2y^3$ & $\dot{x} = -0.100075x^3 +2.000019y^3$\\ & $\dot{y} = -2x^3 -0.1y^3$ & $\dot{y} = -1.999906 x^3 -0.099915y^3$ \\ \hline \multirow{2}{*}{Van der Pol} & $\dot{x} = y$ & $\dot{x} = 1.000015 y$\\ & $\dot{y} = -x+2y-2x^2y$ & $\dot{y} = -1.000043x+2.000271y-1.999807x^2y$\\ \hline \multirow{3}{*}{Hopf bifurcation} & $\dot{\mu}=0$& $\dot{\mu}=0$\\ & $\dot{x} = \mu x + y - x^3 -xy^2$& $\dot{x} = 0.999237 \mu x + 1.000174 y -0.999523 x^3 -0.999582 xy^2$\\ & $\dot{y} = \mu y - x - yx^2 -y^3$ & $\dot{y} = 0.999515 \mu y -0.999821 x -0.999276 yx^2 -0.999409y^3$\\ \hline \multirow{3}{*}{Lorenz} & $\dot{x} = -10x+10y$ & $\dot{x} = -10.000108x+9.999878y$ \\ & $\dot{y} = 28 x - xz - y$ & $\dot{y} = 27.999895 x -0.999998 xz -0.999883 y$ \\ & $\dot{z} = xy - \frac{8}{3}z$ & $\dot{z} = 1.000017 xy -2.666697 z$ \\ \hline \end{tabular} \caption{[nSINDy experiments] The equation names, the ground truth equations, and the identified equations by using nSINDy.} \label{tab:exp_set1} \end{table*} \section{Experimental results with neural SINDy} We implement the proposed method in \textsc{Python} 3.7.2 and \textsc{PyTorch} 1.9.0 \cite{paszke2019pytorch}. In all training, we use Adamax \cite{kingma2015Adam} with an initial learning rate 0.01 and use exponential learning rate decay with the multiplicative factor, 0.9987. In the following experiments, we set the penalty weight as $\lambda=10^{-4}$ and the pruning threshold as $\tau=10^{-6}$. For \text{ODESolve}, we use the Dormand--Prince method (dopri5) \cite{dormand1980family} with relative tolerance $10^{-7}$ and absolute tolerance $10^{-9}$ unless otherwise specified. All experiments are performed on \textsc{Macbook pro} with \textsc{M1} CPU and 16 GB memory. \paragraph{Dictionary construction} In the following experiment, we employ a set of polynomials, $\mathcal P_{n,\Degree}$, where $n$ is the number of variables and $\Degree$ is the maximal total degree of polynomials in the set. An example set, $\mathcal P_{3,2}$ is given as \begin{equation} \mathcal P_{3,2} = \{ 1, x_1, x_1^2, x_1 x_2, x_1 x_3, x_2, x_2^2, x_2 x_3, x_3^2 \}. \end{equation} \subsection{Experiment set} We examine the performance of the proposed method for a number of dynamical systems (see Table \ref{tab:exp_set1} for the equations): \begin{itemize} \item Hyperbolic example, \item Cubic oscillator, \item Van der Pol oscillator, \item Hopf bifurcation, \item Lorenz system. \end{itemize} To generate data, we base our implementation on the code from \cite{liu2020hierarchical}: generating 1600 training trajectories, 320 validating trajectories, and 320 test trajectories. For the first four example problems, we use time step size $\Delta t=0.01$ and total simulation time $t\in [0,51.20]$. For Lorenz, we use $\Delta t=0.0005$ and $t\in [0,2.56]$. For training, we use $n_{\max}=500$ and $n_{\max}=2000$ for the first four example problems and the last example problem, respectively. In Appendix, a comparison against a ``black-box'' feed-forward neural network with fully-connected layers is presented; we report the performance of both the black-box neural network and the proposed network measured in terms of time-instantaneous mean-squared error (MSE). \begin{figure*}[!tb] \centering \includegraphics[scale=.55]{figs/hyperbolic_example.png} \includegraphics[scale=.55]{figs/cubic_example.png}\\ \includegraphics[scale=.55]{figs/vdp_example.png} \includegraphics[scale=.55]{figs/hopf_example.png}\\ \includegraphics[scale=.55]{figs/lorenz_example.png} \includegraphics[scale=.55]{figs/lorenz_example_timeunit30.png} \caption{[nSINDy experiments] Examples of reference trajectories (solid lines) and computed trajectories (dashed lines) from learned dynamics.} \label{fig:set1} \end{figure*} Table \ref{tab:exp_set1} shows the ground truth equations and equations identified by using neural SINDy. We use $\mathcal P_{2,3}$, $\mathcal P_{3,3}$, and $\mathcal P_{3,2}$, respectively, for the first three example problems, the fourth example problem, and the last example problem. During training, coefficients with small magnitude are pruned (i.e., setting them as 0) and are not presented in Table. We also report the learned coefficients without the pruning strategy in Appendix, which highlights that the pruning is required to zero out the coefficients of small magnitude. Figure \ref{fig:set1} depicts examples of reference trajectories and trajectories computed from identified dynamics, where the trajectories are chosen from the test set. As reported in the Appendix, time-instantaneous MSEs computed by nSINDy are several orders of magnitude smaller ($10^6\sim10^8$ smaller) than those computed by the black-box NODEs. \section{Neural SINDy for structure preserving parameterization} \subsection{GENERIC structure-preserving parameterization} In the following, we present neural SINDy for a structure-preserving reversible and irreversible dynamics modeling approach. An alternative formalism for irreversible dynamics based on port-Hamiltonians is included in the appendix. \paragraph{GENERIC formalism} We begin by reviewing the general equation for the nonequilibrium reversible–irreversible coupling (GENERIC) formalism. \begin{table*}[t] \centering \begin{tabular}{l|c|l|l} \hline Eq. name & Parameterization & Ground truth & Identified \\ \hline \multirow{4}{*}{DNO} & \multirow{3}{*}{nSINDy} & $\dot{q} = p$ & $\dot{q} = 0.999622 p$\\ & & $\dot{p} = -3 \sin(q) - 0.04 p$ & $\dot{p} = -2.8645 \sin(q) -0.04001 p-0.1340 q +0.0190 q^3$\\ & & $\dot{S} = 0.04p^2$ & $\dot{S} = 0.040081 p^2 $\\ \cline{2-4} & nSINDy - GNN & $E = 0.5 p^2 - 3 \cos (q) + S$ & $\TotalEnergy_{\theta_1} = 0.500144 p^2 -2.999785 \cos (q) + 0.998337 S$ \\ \hline \end{tabular} \caption{[GENERIC structure preservation] The equation names, the ground truth equations, and the identified equations by using nSINDy (non structure preserving parameterization) and nSINDy - GNN (GENERIC structure preserving parameterization).} \label{tab:exp_set3} \end{table*} In GENERIC, the evolution of an observable $A(\bm{\StateSymb})$ is assumed to evolve under the gradient flow \begin{equation} \dv{A}{t} = \PoissonBracket{A}{E} + \IrrBracket{A}{S} \end{equation} where $E$ and $S$ denote generalized energy and entropy, and $\PoissonBracket{\cdot}{\cdot}$ and $\IrrBracket{\cdot}{\cdot}$ denote a Poisson bracket and an irreversible metric bracket. The Poisson bracket is given in terms of a skew-symmetric Poisson matrix $L$ and the irreversible bracket is given in terms of a symmetric positive semi-definite friction matrix $M$, \begin{equation}\label{eq:brackets} \PoissonBracket{A}{B} = \PoissonBracketBi{A}{B},\quad \mathrm{and} \quad \IrrBracket{A}{B} = \IrrBracketBi{A}{B}. \end{equation} Lastly, the GENERIC formalism requires two degeneracy conditions defined as \begin{equation}\label{eq:degeneracy_cond} L \pdv{S}{\bm{\StateSymb}} = 0, \quad \mathrm{and} \quad M \pdv{E}{\bm{\StateSymb}}=0. \end{equation} With the state variables $\bm{\StateSymb} = [q,p,S]^{\mathsf{T}}$, the GENERIC formalism defines the evolution of $\bm{\StateSymb}$ as \begin{equation}\label{eq:generic} \dv{\bm{\StateSymb}}{t} = L \pdv{E}{\bm{\StateSymb}} + M \pdv{S}{\bm{\StateSymb}}. \end{equation} \paragraph{Parameterization for GENERIC} Here, we review the parameterization technique, developed in \cite{oettinger2014irreversible} and further extended into deep learning settings in \cite{lee2021machine}. As for the Hamiltonian Eq.~\eqref{eq:hamiltonian}, we parameterize the total energy such as \begin{equation} \TotalEnergy_{\theta_1}(q,p,S) = (\pmb{\DictionarySymbol}(q,p,S)^{\mathsf{T}} \Xi)^{\mathsf{T}}, \end{equation} with $\theta_1 = \Xi$. Then we parameterize the symmetric irreversible dynamics via the bracket \begin{equation} \IrrBracket{A}{B}_{\theta_2} = \zeta_{\alpha\beta,\mu\nu} \pdv{A}{x_\alpha} \pdv{\TotalEnergy_{\theta_1}}{x_\beta} \pdv{B}{x_\mu} \pdv{\TotalEnergy_{\theta_1}}{x_\nu}, \end{equation} where \begin{equation} \zeta_{\alpha\beta,\mu\nu} = \Lambda_{\alpha\beta}^m D_{mn} \Lambda_{\mu\nu}^n. \end{equation} The matrices, $\Lambda$ and $D$, are skew-symmetric and symmetric positive semi-definite matrices, respectively, such that \begin{equation} \Lambda_{\alpha\beta}^m = -\Lambda_{\beta\alpha}^m, \quad \mathrm{and} \quad D_{mn} = D_{nm}, \end{equation} where the skew-symmetry and the symmetric positive semi-definiteness can be achieved by the parameterization tricks \begin{equation} \Lambda = \frac{1}{2}(\tilde \Lambda - \tilde \Lambda^{\mathsf{T}}), \quad \mathrm{and} \quad \quad D = \tilde D \tilde D^{\mathsf{T}}, \end{equation} where $\tilde{\Lambda}$ and $\tilde{D}$ are matrices with learnable entries and, thus, $\theta_2 = [\tilde \Lambda, \tilde D]$. With this parameterization, the irreversible part of the dynamics is given by \begin{equation} \IrrBracket{\bm{\StateSymb}}{S}_{\theta_2} = M_{\theta_2}\pdv{S}{\bm{\StateSymb}}= \zeta_{\alpha\beta,\mu\nu} \pdv{\TotalEnergy_{\theta_1}}{x_\beta} \pdv{S}{x_\mu} \pdv{\TotalEnergy_{\theta_1}}{x_\nu} \end{equation} and, as a result, $\Velocity_{\Theta}$ is now defined as \begin{equation} \Velocity_{\Theta} = \PoissonBracket{\bm{\StateSymb}}{\TotalEnergy_{\theta_1}} + \IrrBracket{\bm{\StateSymb}}{S} = L\pdv{\TotalEnergy_{\theta_1}}{\bm{\StateSymb}} + M_{\theta_2} \pdv{S}{\bm{\StateSymb}}, \end{equation} with $\Theta = [\theta_1, \theta_2]$. \begin{figure}[tb] \centering \includegraphics[scale=.55]{figs/dno_example.png} \caption{[GENERIC structure preservation] Examples of reference trajectories (solid lines) and computed trajectories (dashed lines) from learned dynamics.} \label{fig:set3} \end{figure} \begin{figure}[t] \centering \includegraphics[scale=.55]{figs/dno_dEdt_all_example.png}\\ \includegraphics[scale=.55]{figs/dno_dSdt_all_example.png} \includegraphics[scale=.55]{figs/dno_dSdt_all_example_zoomed.png} \caption{[GENERIC structure preservation] $\dv{E}{t}$ and $\dv{S}{t}$of the reference system (black solid line), the system identified by nSINDy (red dotted line), and the system identified by nSINDy - GNN (lightblue dashed line).} \label{fig:set3_ES} \end{figure} \paragraph{Experiments} An example problem (with their reference mathematical formulations) considered in this paper is: \begin{itemize} \item Damped nonlinear oscillator from \cite{shang2020structure}: the ground truth equation can be written in the GENERIC formalism (Eq.~\eqref{eq:generic}) with the following components: \begin{equation} L = \begin{bmatrix} 0 & 1 & 0\\ -1 & 0 & 0\\ 0 & 0 & 0 \end{bmatrix},\quad M = 0.04 \begin{bmatrix} 0 & 0 & 0 \\ 0 & 1 & -p\\ 0 & -p & p^2 \end{bmatrix}, \end{equation} \begin{equation} \text{and} \quad E(q,p,S) = \frac{p^2}{2} - 3 \cos (q) + S. \end{equation} Alternatively, the equation for the dynamics can be written as \begin{equation} \begin{split} \dot{q} &= p,\\ \dot{p} &= -3 \sin(q) - 0.04 p \\ \dot{S} &= 0.04 p^2. \end{split} \end{equation} \end{itemize} \begin{table*}[t] \centering \begin{tabular}{l|c|l|l} \hline Eq. name & Parameterization & Ground truth & Identified \\ \hline \multirow{3}{*}{Ideal mass-spring} & \multirow{2}{*}{nSINDy} & $\dot{q} = p$ & $\dot{q} = 0.999989 p$\\ & & $\dot{p} = -q$ & $\dot{p} = -1.000030 q$\\ \cline{2-4} & nSINDy - HNN & $\mathcal H(q,p) = 0.5 q^2 + 0.5p^2$& $\mathcal H(q,p) = 0.499991 q^2 + 0.500033p^2$\\ \hline \multirow{3}{*}{Ideal pendulum} & \multirow{2}{*}{nSINDy} & $\dot{q} = p$ & $\dot{q} = 1.000018 p + 0.034095 q -0.004796 q^3$\\ & & $\dot{p} = - 6 \sin(q) $ & $\dot{p} = -5.890695 \sin (q) -0.107052q$ \\ \cline{2-4} & nSINDy - HNN & $\mathcal H(q,p) = 6- 6 \cos( q) + 0.5 p^2$ & $\mathcal H(q,p) = 6-5.999838\cos( q) + 0.500014 p^2$\\ \hline \end{tabular} \caption{[Hamiltonian structure preservation] The equation names, the ground truth equations, and the identified equations by using nSINDy (non structure preserving parameterization) and nSINDy - HNN (Hamiltonian structure preserving parameterization).} \label{tab:exp_set2} \end{table*} In the experiment, we assume that we have knowledge on $L$ and that the measurements on $S$ are available. That is, the nSINDy method with the GENERIC structure preservation seeks the unknown $M$ and $E$. For generating data, we base our implementation on the code from \cite{shang2020structure}. We generate 800 training trajectories, 160 validation trajectories, and 160 test trajectories with $\Delta t = 0.001$ and the simulation time $[0,5.12]$. We use a dictionary consisting of polynomials and trigonometric functions: \begin{equation} \mathcal P = \{\mathcal P_{2,3}, \cos(q),\sin(q),\cos(p),\sin(p)\}. \end{equation} We consider the same experimental settings that are used in the above experiments: Adamax optimizer with the initial learning rate 0.01, exponential learning rate decay with a factor 0.9987, L1-penalty weight $10^{-4}$, pruning threshold $10^{-6}$, dopri5 for the ODE integrator with $10^{-7}$ and $10^{-9}$ for relative and absolute tolerances, and, finally, $n_{\max}=300$. Table \ref{tab:exp_set3} reports the coefficients of the identified systems when nSINDy and nSINDy - GNN are used. With $n_{\max}=300$, nSINDy fails to correctly identify the system, whereas nSINDy - GNN identifies the exact terms correctly and computes the coefficients accurately. Figure \ref{fig:set3} depicts the ground truth trajectory and the trajectory computed from the learned dynamics function (nSINDy - GNN). Figure \ref{fig:set3_ES} shows the advantages of using GENERIC structure preservation via plots of $\dv{E}{t}$ and $\dv{S}{t}$. The difference between structure-preserving and non-structure-preserving parameterization is shown dramatically in the plot of $\dv{E}{t}$; the structure-preserving parameterization produces $\dv{E}{t}=0$, whereas the non-structure-preserving parameterization produces fluctuating values of $\dv{E}{t}$. \begin{comment} \item Two gas container example from \cite{shang2020structure} \begin{equation} L \!=\! \begin{bmatrix} 0 & 1 & 0 & 0\\ -1 & 0 & 0 & 0\\ 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 \end{bmatrix},\, M \!=\! \begin{bmatrix} 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & \frac{1}{T_1^2} & -\frac{1}{T_1 T_2}\\ 0 & 0 & -\frac{1}{T_1 T_2} & \frac{1}{T_2^2} \end{bmatrix}, \end{equation} \begin{equation} \text{and} \quad E(q,p,S_1,S_2) = \frac{p^2}{2} + E_1(S_1) + E_2(S_2), \end{equation} where $E_i = \mathrm{exp} \left(\frac{2}{3} (S_i - \log (\hat{c} V_i)) \right) $. Here, $\hat{c}$ is a constant that is needed to ensure the argument of the logarithm dimensionless and the volumes of two subsystems are given by \begin{equation} V_1 = q, \quad \text{and} \quad V_2 = 2-q. \end{equation} \KL{This should go to the limitations paragraph} \end{comment} \begin{figure}[tb] \centering \includegraphics[scale=.55]{figs/mass_spring_example.png}\\ \includegraphics[scale=.55]{figs/pendulum_example.png} \caption{[Hamiltonian structure preservation]Examples of reference trajectories (solid lines) and computed trajectories (dashed lines) from learned dynamics.} \label{fig:set2} \end{figure} \begin{figure}[tb] \centering \includegraphics[scale=.55]{figs/pendulum_H.png}\\ \includegraphics[scale=.55]{figs/pendulum_H_timeunit100.png} \caption{[Hamiltonian structure preservation] The Hamiltonian function measured by the trajectories computed with nSINDy (red dashed line) and nSINDy-HNN (blue dashed line). Figure below depicts the Hamiltonian functions measured by the trajectories computed for extended numerical simulation time, i.e., 100 seconds (the training simulation time is 9 seconds).} \label{fig:set2_H} \end{figure} \subsection{Hamiltonian structure-preserving parameterization} In the following, we consider the Hamiltonian structure-preserving parameterization technique proposed in Hamiltonian neural networks (HNNs) \cite{Greydanus2019hnn}: parameterizing the Hamiltonian function $\mathcal H(q,p)$ as $\mathcal H_{\Theta}(q,p)$ such that \begin{equation}\label{eq:hamiltonian} \mathcal H_{\Theta} = (\pmb{\DictionarySymbol}(q,p)^{\mathsf{T}} \Xi)^{\mathsf{T}}. \end{equation} With the above parameterization and $\bm{\StateSymb} = [q,p]^{\mathsf{T}}$, the dynamics can be modeled as \begin{equation} \begin{bmatrix} \dv{q}{t}\\[8pt] \dv{p}{t} \end{bmatrix} = \begin{bmatrix*}[r] -\pdv{\mathcal H_{\Theta}}{p}\\[8pt] \pdv{\mathcal H_{\Theta}}{q} \end{bmatrix*}, \end{equation} i.e., $\Velocity_{\Theta}$ is now defined as $\Velocity_{\Theta} = [-\pdv{\mathcal H_{\Theta}}{p}, \pdv{\mathcal H_{\Theta}}{q}]^{\mathsf{T}}$. Then the loss objective can be written as \begin{equation} \left \| \pdv{\mathcal H_{\Theta}}{p} - \dv{q}{t} \right\|_1 + \left \| \pdv{\mathcal H_{\Theta}}{q} + \dv{p}{t} \right\|_1. \end{equation} As noted in \cite{lee2021machine}, with canonical coordinates $\bm{\StateSymb} = [q,p]^{\mathsf{T}}$, and canonical Poisson matrix $L= \begin{bmatrix}0 & 1 \\ -1 & 0\end{bmatrix}$, and $M = \bm{0}$, the GENERIC formalism in Eq.~\eqref{eq:generic} recovers Hamiltonian dynamics. \paragraph{Experiments} We examine the performance of the proposed method with a list of example dynamic systems: \begin{itemize} \item Ideal mass-spring, \item Ideal pendulum. \end{itemize} For generating data, we base our implementation on the code from \cite{Greydanus2019hnn}. We generate 800 training trajectories, 160 validation trajectories, and 160 test trajectories. For the mass spring and the pendulum problem, we use $\Delta t = 0.1$ and $\Delta t = 1/15$, respectively, and the simulation time is set as $[0,3]$ and $[0,9]$, respectively. Table \ref{tab:exp_set2} shows the ground truth equations and equations identified by using neural SINDy. For the mass spring problem, we use $\mathcal P_{2,3}$ and for the pendulum problem we use a dictionary consisting of polynomials and trigonometric functions: \begin{equation} \mathcal P = \{\mathcal P_{2,3}, \cos(q),\sin(q),\cos(p),\sin(p)\}. \end{equation} Again, we use the same experimental settings described above for the GENERIC parameterization. In Table \ref{tab:exp_set2}, we presented results obtained by two different parameterization techniques: 1) the ``plain'' dictionary approach (Eq.~\eqref{eq:dict}) denoted by (nSINDy) and 2) the Hamiltonian approach (Eq~\eqref{eq:hamiltonian}) denoted by (nSINDy - HNN). Figure \ref{fig:set2} depicts examples of reference trajectories and trajectories computed from identified dynamics, where the trajectories are chosen from the test set. Figure \ref{fig:set2_H} depicts how the energy is being conserved in the dynamics learned with nSINDy-HNN, whereas the plain apporach (nSINDy) fails to conserve the energy. \section{Discussion} \paragraph{Limitation} The proposed method shares the same limitations of the original SINDy method: successful identification requires inclusion of the correct dictionaries in the library. Potential alternatives are well-studied in the literature and include either adding an extra ``black-box'' neural network to compensate missing dictionaries or designing a neural network that can learn dictionaries from data (such as in \cite{sahoo2018learning}). The gradient-based parameter update and the magnitude-based pruning could potentially zero out unwanted coefficients in a special case: when the signs of the coefficients need to be changed in the later stage of the training. If the magnitude of the loss term becomes very small (and the gradient as well), the updated coefficients may satisfy the pruning condition shown in \eqref{eq:prune}. Lastly, when adaptive step-size ODE solvers are used (e.g., dopri5), numerical underflow may occur. This can be mitigated by trying different initialization for the coefficients, or smaller batch length $\ell_{\mathrm{batch}}$. However, further study regarding robust initialization is required. \section{Related work} \paragraph{System identification} In \cite{schmidt2009distilling}, the proposed method uses a genetic algorithms to identify governing physical laws (Lagrangian or Hamiltonian) from measurements of real experiments. A seminal work on sparse regression methods for system identification has been proposed in \cite{brunton2016discovering}. Then the sparse regression methods have been extended to various settings, e.g., for model predictive control \cite{kaiser2018sparse}, and for identifying dynamics in latent space using autoencoders \cite{hinton2006reducing} and then learning parsimonious representations for the latent dynamics \cite{champion2019data}. Also, the sparse regression methods have been applied for identifying partial differential equations (PDEs) \cite{rudy2017data,rudy2019data}. For identifying PDEs, deep-learning-based approaches such as physics-informed neural networks \cite{raissi2019physics} and PDE-net \cite{long2018pde} have been studied recently. \paragraph{Structure preserving neural network} Designing neural network architectures that exactly enforces important physical properties has been an important topic and studied extensively. Parameterization techniques that preserve physical structure include Hamiltonian neural networks \cite{Greydanus2019hnn,toth2019hamiltonian}, Lagrangian neural networks \cite{cranmer2020lagrangian,lutter2018deep}, port-Hamiltonian neural networks \cite{desai2021port}, and GENERIC neural networks \cite{hernandez2021structure,lee2021machine}. Neural network architectures that mimic the action of symplectic integrators have been proposed in \cite{chen2019symplectic,jin2020sympnets,tong2021symplectic}, and a training algorithm exploiting physical invariance for learning dynamical systems, e.g., time-reversal symmetric, has been studied in \cite{huh2020time}. \section{Conclusion} We have proposed a simple and effective deep-learning-based training algorithm for a dictionary-based parameterization of nonlinear dynamics. The proposed algorithm is based on the training procedure introduced in neural ordinary differential equations (NODE) \cite{chen2018neural} and employs L1-weight decay of model parameters and magnitude-based pruning strategy, inspired by sparse identification of nonlinear dynamics (SINDy) \cite{brunton2016discovering}. We have further extended the dictionary-based parameterization approach to structure-preserving parameterization techniques, such as Hamiltonian neural networks, GENERIC neural networks, and port-Hamiltonian networks. For a suite of benchmark problems, we have demonstrated that the proposed training algorithm is very effective in identifying the underlying dynamics from data with expected gains from imposing structure-preservation. \section{Acknowledgments} \label{sec:acknowledge} N.~Trask and P.~Stinis acknowledge funding under the Collaboratory on Mathematics and Physics-Informed Learning Machines for Multiscale and Multiphysics Problems (PhILMs) project funded by DOE Office of Science (Grant number DE-SC001924). N.~Trask and K.~Lee acknowledge funding from the DOE Early Career program. Sandia National Laboratories is a multi-mission laboratory managed and operated by National Technology and Engineering Solutions of Sandia, LLC., a wholly owned subsidiary of Honeywell International, Inc., for the U.S. Department of Energy’s National Nuclear Security Administration under contract DE-NA0003525. This paper describes objective technical results and analysis. Any subjective views or opinions that might be expressed in the paper do not necessarily represent the views of the U.S. Department of Energy or the United States Government.
{'timestamp': '2021-09-14T02:16:44', 'yymm': '2109', 'arxiv_id': '2109.05364', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05364'}
arxiv
\section{Introduction} \input{introduction} \section{NP Complexity for Power Structures} \input{power} \section{Explicit Sets of Indices and a Polynomial Verifier for QFBAPA} \input{qfbapa} \section{NP Complexity for QFBAPAI} \input{qfbapai} \section{Combination with the Array Theory} \input{combination} \section{Related Work} \input{related} \section{Conclusion and Future Work} \input{conclusion} \bibliographystyle{splncs04} {\raggedright \subsection{Corollary: Quantifier-Free Skolem Arithmetic is in NP} Although not needed for our final result, the technique of theorem \ref{thm:power} is of independent interest. An example is showing that the satisfiability problem for the quantifier-free fragment of Skolem arithmetic is in NP. This result was first proved by Gr\"adel \cite{gradel_dominoes_1989} using results by Sieveking and von zur Gathen \cite{gathen_bound_1978} with a proof that appears, on the surface, to be specific to the arithmetic theories. Skolem arithmetic is the first-order theory of the structure $\langle \mathbb{N} \setminus \{0\}, \cdot, =, | \rangle$. This structure is isomorphic to the weak direct power \cite{feferman_first_1959,ferrante_computational_1979} of the structure $\langle \mathbb{N}, +, \le \rangle$. Thus, their existential theories coincide. A variation of the verifier in figure \ref{fig:prod-verifier}, ensuring that if $|I|$ is infinite then $0^n$ is a solution of $\varphi_0$ in $\mathcal{M}$, yields the NP complexity bound for the satisfiability of (existential and) quantifier-free formulas.
{'timestamp': '2021-09-14T02:16:41', 'yymm': '2109', 'arxiv_id': '2109.05363', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05363'}
arxiv
\section{Introduction} Since the proposal of AlexNet \cite{krizhevsky2012imagenet}, convolutional neural networks (CNNs) have been the dominant design paradigm in computer vision. This situation has recently been changed by the boom of conv-free vision Transformers. The pioneering work ViT \cite{dosovitskiy2020image} interprets an image as a sequence of patches and processes it by a standard Transformer encoder as used in natural-language processing (NLP). Specifically, an image is divided into non-overlapping patches, and the sequence of linear embeddings of these patches are used as an input to the vision Transformer. The encoding process involves alternate spatial mixing and channel mixing modules implemented by multi-head self-attention and feed forward networks (FFNs), respectively. ViT performs very well on image recognition tasks when pretrained on a very large dataset. Shortly after, DeiT \cite{touvron2021training} further demonstrates that a conv-free vision Transformer can achieve state-of-the-art (SOTA) image recognition accuracy when pretrained on ImageNet-1K, with appropriate data augmentation and model regularization techniques. The conv-free vision transformers are actually promoting two views. First, global dependency modeling is important. Not only that, it could even completely replace local dependency modeling which used to be baked into the model by convolutions. Second, self-attention is important. Despite the good performance of ViT and DeiT, it is clear that academia has not fully embraced both views, and questions about them are often heard. \begin{figure}[t] \centering \includegraphics[width=0.95\columnwidth]{sMLPrange.pdf} \caption{The proposed sparse MLP reduces the computational complexity of MLP by sparse connection and weight sharing. In MLP (a), the token in dark orange interacts with all the other tokens in a single MLP layer. In contrast, in one sMLP layer (b), the dark-orange token only interacts with horizontal and vertical tokens marked in light orange. The interaction with all the other white tokens can be achieved when sMLP is executed twice.} \label{fig:sMLPinteraction} \end{figure} On the one hand, researchers challenge the complete disposal of locality bias. It is natural to ask, since locality is always valid in natural images, why bother learning it through global self-attention modules instead of directly injecting it into the network? Besides, global self-attention has quadratic computational complexity with respect to the number of input tokens. As a result, the network structure does not favor high-resolution input and is not friendly to pyramid structure. These are considered drawbacks of vision Transformers as high-resolution input and pyramid structure have been widely acknowledged to improve the image recognition accuracy. The recent Swin Transformer \cite{liu2021swin} injects locality back into the network by limiting self-attention operations within a local window. This setting also controls the computational complexity and allows for a pyramid structure or multi-stage processing. The superior performance of Swin Transformer demonstrates the value of locality bias and multi-stage processing. On the other hand, researchers also challenge the need for self-attention. MLP-Mixer \cite{tolstikhin2021mlp} recognizes the importance of modeling global dependencies, but it adopts an MLP block, instead of a self-attention module, to achieve it. The overall architecture of MLP-Mixer is similar to ViT. An input image is divided into patches which are then mapped into tokens. The encoder also contains alternating layers for spatial mixing and channel mixing. The only major difference is that the spatial mixing module is implemented by an MLP block. MLP-Mixer inherits all the drawbacks of ViT, besides, it is prone to over-fitting due to the excessive number of parameters. It is not surprising that there is still an accuracy gap between MLP-Mixer and SOTA models, especially on mid-scale datasets such as ImageNet. However, MLP-Mixer's defeat cannot convince us of the need for self-attention. We ask: is it possible for an attention-free network to achieve SOTA performance on image recognition after addressing all the drawbacks? The work to be presented in this paper confirms that the answer to the above question is yes. We design an attention-free network, called sMLPNet, which only uses convolution and MLP as building blocks. sMLPNet adopts a similar architecture as ViT and MLP-Mixer, and the channel mixing module is exactly the same. In each token mixing module, depth-wise convolution is adopted to take advantage of the locality bias and a modified MLP is used to model global dependencies. Specifically, we propose sparse-MLP (sMLP) module which is featured by axial global dependency modeling, as shown in Fig.\ref{fig:sMLPinteraction}, and weight sharing. sMLP significantly reduces the computational complexity and allows us to adopt a pyramid structure for multi-stage processing. As a result, the sMLPNet is capable of achieving top image recognition performance on par with Swin Transformer at an even smaller model size. In a nutshell, in the craze of vision Transformers, we investigate whether the key component of Transformers, known as self-attention, is the true game-changing factor for image understanding. Based on the learning from past vision models, we retain design ideas that are important to image understanding, such as locality and pyramid structure. We also absorb the idea of global dependency modeling, but choose to implement it with a sparse MLP module we propose. We eventually build an attention-free network called sMLPNet which achieves SOTA image recognition performance. Our work suggests that self-attention might not be a core component in vision model design. Instead, proper use of locality, pyramid structure and careful control of computational complexity are the keys to designing a high-performance vision model. \section{Related Work} \subsection{CNN-Based Vision Models} Since the success of AlexNet \cite{krizhevsky2012imagenet}, CNNs have been the mainstream tools in computer vision field. VGG \cite{simonyan2014very} demonstrated that a series of convolutions with a small 3x3 receptive field is sufficient to train state-of-the-art models. Later, ResNet \cite{he2016deep} introduced skip-connections together with the batch normalization layer \cite{ioffe2015batch}, which enabled training of very deep neural networks and further improved performance. The success of these CNN-based vision models prove the effectiveness of locality bias. Besides, these methods are all based on pyramid structure of multi-stage processing which have been widely acknowledged to improve performance. Later, non-local operations \cite{wang2018non} is proposed to explore global context to augment convolutional networks. It shows that researchers from this field have also realized the importance of global dependency modeling. We believe that the experiences obtained in the CNN-based vision models, including taking advantage of locality bias through small-kernel convolutions, the pyramid structure, and exploiting global dependencies, are still valid nowadays. In our architecture, skip connections \cite{he2016deep} and normalization layers \cite{ioffe2015batch,ba2016layer} are also applied. \begin{figure*}[t] \centering \includegraphics[width=\textwidth]{Figs/Architecture.png} \caption{(a) The overall multi-stage architecture of the sMLPNet; (b) The token mixing module.} \label{Architecture} \end{figure*} \subsection{Transformer-Based Vision Models} ViT \cite{dosovitskiy2020image} is the first work to build a purely Transformer-based vision backbone. It shows that, with sufficient training data, a transformer provides better performance than a traditional CNN in vision tasks. DeiT \cite{touvron2021training} introduces several training strategies that allow ViT to be similarly effective using the much smaller ImageNet-1K as the training dataset. These methods demonstrate the power of global dependency modeling by self-attention. Later, some following works introduce the pyramid structure into Transformer, such as PVT \cite{wang2021pyramid}. Just as in CNN-based models, pyramid structure also improves the performance of Transformer-based models for various vision tasks. Based on the pyramid structure, Swin Transformer \cite{liu2021swin} proposes to use self-attention within each local window. This can be regarded as a use of locality bias. Following these local attention mechanism, there are also some variants such as Twins \cite{chu2021twins}, MSG-transformer \cite{fang2021msg}, GG-transformer \cite{yu2021glance} and Shuffle Transformer \cite{huang2021shuffle}. All these methods justify the importance of locality bias. In contrast to the methods mentioned above, our method tries to model global dependencies using an attention-free mechanism. In particular, the mapping weights in self-attention modules are dynamic or data-dependent, but those in our sMLP modules are static. \subsection{MLP-Based Vision Models} Our work is mostly related to MLP-based methods. MLP-Mixer \cite{tolstikhin2021mlp}, a pure MLP-like model for ImageNet classification has been proposed very recently. It uses standard dense matrix multiplications (channel-mixing feed forward networks) to aggregate information across channels. For spatial information, it flattens the 2D spatial dimensions to 1D sequence and apply another matrix multiplications (token-mixing MLPs) to aggregate information across token sequence. Despite that MLP-Mixer has achieved promising results when trained on a huge-scale dataset JFT-300M, it is not as good as its visual Transformer counterparts when trained on a medium-scale dataset such as ImageNet-1K. gMLP \cite{liu2021pay} designs a gating operation to enhance the communications between spatial locations. ResMLP \cite{touvron2021resmlp} proposes an affine transform layer which facilities stacking a huge number of MLP blocks. EA \cite{guo2021beyond} replaces the self-attention module with an external attention which is implemented by a cascade of two linear layers. The complexity in parameter and time of all these methods are quadratic with respect to the input image size when they aggregating the spatial information. Besides, there is still an accuracy gap between MLP-based methods and SOTA. We believe the main reasons are the overlook of locality bias, the absence of pyramid structure, and the over-fitting phenomenon caused by excessive number of parameters. In contrast to the existing MLP-based method, our method try to exploit locality bias and global dependency based on pyramid structure. Since the quadratic computational complexity of global dependency modeling by MLP is not friendly to pyramid structure, we use the proposed sparse MLP module to support the global dependency modeling based on pyramid structure. \section{Method} \subsection{Design Guidelines} In this work, we intend to answer the question whether it is possible to design a high-performance network for image recognition without using self-attention modules. We want to retain some of the important design ideas used in the CNN era, and add new components inspired by Transformers. The followings are the design guidelines we try to follow: \begin{enumerate} \item Adopt a similar architecture as ViT, MLP-Mixer, and Swin Transformer to ensure a fair comparison. \item Explicitly inject the locality bias into the network. \item Explore the global dependencies without the use of self-attention module. \item Perform multi-stage processing in a pyramid structure. \end{enumerate} In the next subsections, we will present the overall architecture of the proposed sMLPNet and detail the key component sMLP module. \subsection{Overall Architecture} Fig.\ref{Architecture}(a) illustrates the overall architecture of our designed network. Similar to ViT, MLP-Mixer, and recent Swin transformer, an input RGB image with spatial resolution $H \times W$ is divided into non-overlapping patches by a patch partition module. We adopt a small patch size of $4 \times 4$ at the first stage of the network. Each patch is first reshaped into a 48-dimensional vector, and then mapped by a linear layer to a C-dimensional embedding. As such, the entire image is expressed as a $\frac{H}{4} \times \frac{W}{4} \times C$ tensor. Note that the patch size in MLP-Mixer is $16 \times 16$. With the same input image resolution, the number of tokens in our network is 16 times that in MLP-Mixer. As we know, the computational complexity of MLP grows in a quadratic way with the number of input tokens. It would be impossible for MLP-Mixer to handle such a large number of tokens if no optimization is applied. The entire network is comprised of four stages. Except for the first stage, which starts with a linear embedding layer, other stages start with a patch merging layer which reduces the spatial dimension by $2 \times 2$ and increases the channel dimension by $2$ times. The patch merging layer is simply implemented by a linear layer which takes the concatenated features of each $2 \times 2$ neighboring patches as input and outputs the features of the merged patch. Then, the new image tokens are passed through a token-mixing module and a channel-mixing module. These two modules do not change the data dimensions. The token-mixing module is illustrated in Fig.\ref{Architecture}(b). In this module, we take advantage of locality bias by using a depth-wise convolution (DWConv) with kernel size 3x3. In fact, after channel processing is decomposed from spatial processing, DWConv becomes a very natural choice to explore locality. This operation is highly efficient in the sense that it contains few parameters and takes few FLOPs during inference. We also try to model global dependencies with the proposed sMLP module. The sparsity and weight-sharing nature makes sMLP less prone to over-fitting than the original MLP module. The greatly reduced computational complexity of sMLP allows us to operate at a spatial resolution of $H/4 \times W/4$ in the first stage. The details of sMLP will be presented in the next subsection. Batch normalization (BN) and skip connections are applied in a standard way in the token-mixing module. The channel-mixing module is implemented by an MLP or so called feed-forward network (FFN), in exactly the same way as that in MLP-Mixer. The FFN is composed of two linear layers separated by a GeLu activation. The first linear layer expands the dimension from $D$ to $\alpha D$, and the second layer reduces the dimension from $\alpha D$ back to $D$. Here $\alpha$ is a tunable hyper-parameter and we find that $\alpha=2$ or $\alpha=3$ works the best in our network. \begin{figure}[t] \centering \includegraphics[width=0.4\textwidth]{Figs/S-MLP.png} \caption{Structure of the proposed sMLP block. It consists of three branches: two of them are responsible for mixing information along horizontal and vertical directions respectively and the other path is the identity mapping. The output of the three branches are concat and processed by a point-wise conv to obtain the final output.} \label{fig:sMLP} \end{figure} \subsection{Sparse MLP (sMLP)} We design a sparse MLP to fix two major drawbacks of the original MLP. First, we want to reduce the number of parameters to avoid over-fitting, especially when the network is trained on moderate-sized dataset as ImageNet-1K. Second, we want to reduce the computational complexity, especially when the number of tokens is large, to enable multi-stage processing in a pyramid structure. In sparse MLP, we use sparse connection and weight sharing to achieve our design goal. As illustrated in Fig.\ref{fig:sMLPinteraction}, instead of interacting with all the other tokens, a token in sMLP only directly interacts with tokens on the same row or the same column. In addition, all rows and all columns can respectively share the same projection weights. Fig.\ref{fig:sMLP} shows the implementation diagram of our designed sMLP block. It consists of three paths. Besides the identity mapping shown in the middle, two other paths are responsible for mixing tokens along horizontal and vertical directions, respectively. Let $X^{in} \in {R}^{H \times W \times C}$ denote the collection of input tokens. In the horizontal mixing path, the data tensor is reshaped into $HC \times W$, and a linear layer with weights $W_{W} \in {R}^{W \times W}$ is applied to each of the $HC$ rows to mix information. Similar operation is applied in the vertical mixing path and the linear layer is characterized by weights $W_{H} \in {R}^{H \times H}$. Finally, the output from the three paths are fused together to produce an output data tensor which has the same dimension as the input tensor. We implement this fusion module with concatenation and a FC layer: \begin{equation} X^{out} = FC(concat(X_{H},X_{W},X)) \end{equation} The PyTorch-like pseudo code for the implementation of sMLP module can be found in Alg.~\ref{alg:algorithm}. This design allows each token to aggregate information across the row and the column it locates. If this module is passed twice, each token can aggregate information across the entire 2D space. In other words, sMLP efficiently obtains global receptive field although the direct connections are sparse. The number of parameters in one sMLP module can be computed as $H^{2} + W ^{2} +3C^{2}$, where $3C^2$ parameters are used in the fusion step. In comparison, the number of parameters in the original MLP module is $2\alpha{(HW)}^{2}$, where $\alpha$ is the expansion ratio of MLP layers which often takes value of 4. When the input image size is $224 \times 224$ and the initial patch is as small as $4 \times 4$, our sMLP module achieves about 3,000x parameter reduction when $C=80$ , which will make a huge difference in preventing the over-fitting phenomenon on moderate-sized dataset. The reduction of computational complexity is also prominent. Specifically, the complexity of one sMLP module is: \begin{equation} \Omega(sMLP) = HWC(H+W)+3HWC^{2}, \end{equation} and that of the token mixing part of MLP-Mixer is: \begin{equation} \Omega(MLP) = 2\alpha(HW)^{2}C \end{equation} The product of $H$ and $W$ is the number of input tokens, denoted by $N$. It is now clear that MLP-Mixer cannot afford a high-resolution input or the pyramid processing, as the computational complexity grows with $N^2$. In contrast, the computational complexity of the proposed sMLP grows with $N\sqrt{N}$. It allows us to process a much larger $N$ and eventually enables the multi-stage processing in a pyramid structure. \begin{algorithm}[tb] \caption{Pseudocode of sMLP (PyTorch-like)} \label{alg:algorithm} \textbf{Input}: x \# input tensor of shape (H, W, C)\\ \textbf{Output}: x \# output tensor of shape (H, W, C)\\ proj\_h = nn.Linear(H,H). \\ proj\_w = nn.Linear(W,W). \\ fuse = nn.Linear(3C,C). \\ def sparse\_mlp(x): \\ \begin{algorithmic} \STATE x\_h = self.proj\_h(x.permute(2,1,0)).permute(2,1,0) \\ x\_w = self.proj\_w(x.permute(0,2,1)).permute(0,2,1) \\ x = torch.concat([x\_h,x\_w,x],dim=2) \\ x = self.fuse(x) \\ return x \end{algorithmic} \end{algorithm} \subsection{Model Configurations} We build three variants of our model, called sMLPNet-T, sMLPNet-S sMLPNet-B to match with the model size of Swin-T, Swin-S, and Swin-B, respectively. The expansion parameter in the FFN for channel mixing is $\alpha = 3$ by default. The architecture hyper-parameters of these models are: \begin{itemize} \item sMLPNet-T: C = 80, number of layers = [2; 8; 14; 2], \item sMLPNet-S: C = 96, number of layers = [2; 10; 24; 2], \item sMLPNet-B: C = 112, number of layers = [2; 10; 24; 2], \end{itemize} where C is the number of channels of the hidden layers in the first stage. The number of layers indicate the number of times the pair of token mixing and channel mixing modules are stacked in each of the four stages. The model size and theoretical computational complexity (FLOPs) of the model variants for ImageNet image classification are listed in Table~\ref{tab:main results}. \section{Experiments} \subsection{Experimental Setup} We evaluate our model based on ImageNet-1K dataset \cite{krizhevsky2012imagenet} which contains 1.2 million training images from one thousand categories and 50 thousand validation images with 50 images in each category. We train our model using AdamW \cite{loshchilov2018decoupled} with weight decay 0.05 and a batch size of 1024. We use a linear warm up and cosine decay. The initial learning rate is 1e-3 and gradually drops to 1e-5 in 300 epochs. We also use label smoothing \cite{szegedy2016rethinking} and DropPath \cite{larsson2016fractalnet}. DropPath rates for our tiny, small, and base models are 0, 0.2, and 0.3, respectively. For data augmentation methods, we use RandAug \cite{cubuk2020randaugment}, repeated augmentation \cite{hoffer2020augment}, MixUp \cite{zhang2018mixup}, and CutMix \cite{zhong2020random}. All training is conducted with 8 NVIDIA Tesla V100 GPU cards. \subsection{Ablation Study} We carry out ablation studies on all three variants of the sMLPNet. Due to space limit, we will only present the numerical results on one variant in each ablation experiment. The trend on other variants is the same if not otherwise stated. Similarly, we also conducted experiments on both choices of the expansion parameter, $\alpha=2$ and $\alpha=3$, in the FFN. We randomly choose one setting to report the numerical results. In order to differentiate, we append a * to the model name when $\alpha=2$. \subsubsection{Local and Global Modeling.} \begin{table}[t] \centering \begin{tabular}{c|c c c c} \hline sMLPNet-T* & Param(M) & FLOPs(B) & Top-1(\%) \\ \hline Local+Global &19.2 &4.0 &81.3 \\ Global only &19.1 &3.9 &80.6 \\ Local only &22.5 &4.4 &80.7 \\ \hline \end{tabular} \caption{Ablation study on the effects of local and global modeling using the tiny model ($\alpha=2$).} \label{tab:local and global} \end{table} In sMLPNet, we use depth-wise convolution (DWConv) to model locality and sMLP to model global dependencies. In order to verify the need to model both types of dependencies, we remove either DWConv or sMLP to check how the top-1 accuracy changes. The base model is the tiny version sMLPNet-T with FFN expansion parameter $\alpha=2$. The top-1 accuracy achieved by this base model is 81.3\%. As we have mentioned, the DWConv operation is extremely lightweight. When we remove it from sMLPNet, the model size only changes from 19.2M to 19.1M and the FLOPs only decrease by 0.1B, as shown in Table \ref{tab:local and global}. However, the image recognition accuracy significantly drops to 80.6\%. This clearly shows that DWConv is a very efficient way to model local dependencies and that a vision model should take advantage of the inductive bias on locality. We then remove the sMLP module to evaluate the performance of a network with local modeling only. Since sMLP is quite heavy, in order to ensure a fair comparison, we increase the number of channels from 80 to 112 to make the model size and FLOPs roughly comparable to the base model. From Table \ref{tab:local and global}, we can see that the local only version only achieves an accuracy of 80.7, although the model being tested is slightly larger than the base model. This experiment confirms that both local and global modeling are important in sMLPNet. \begin{table}[t] \centering \begin{tabular}{c c c c|c c c} \hline S1 & S2 & S3 & S4 & Param(M) & FLOPs(B) & Acc.(\%) \\ \hline \checkmark & \checkmark & \checkmark & \checkmark &65.9 &14.0 &83.4 \\ & \checkmark & \checkmark & \checkmark &65.8 &13.7 &83.2 \\ & & \checkmark & \checkmark &64.3 &12.4 &83.0 \\ & & & \checkmark &49.9 &9.5 &82.2 \\ & & & \textcolor{white}{\checkmark} &45.1 &9.3 &82.0 \\ \hline \end{tabular} \caption{Abation study on the effects of sMLP using sMLPNet-B ($\alpha=3$) as the base model. We remove the sMLP block from the beginning of the network and evaluate the top-1 accuracy. A check mark in the corresponding stage (S1, S2, S3, and S4) means the use of sMLP module.} \label{tab:Local & global} \end{table} After verifying the overall validity of the sMLP module, we further attempt to explore its role in different stages of the network. For this experiment, we use sMLPNet-B as the base model. It has 65.9M parameters and 14.0B FLOPs. The top-1 accuracy is 83.4\%. Then, we start to remove sMLP from stage 1 until stage 4. After removing sMLP from an entire stage, we train the model and report the image recognition results, which are listed in Table.\ref{tab:Local & global}. Note that the first row in the table corresponds to the full base model and the last row is the local only version of sMLPNet-B. It is not quite surprising to see that the top-1 accuracy decreases as we remove sMLP module from more stages. The decrease in accuracy is roughly proportional to the reduction of model size and FLOPs. The largest accuracy drop happens when we remove sMLP from stage 3. The accuracy decreases from 83.0\% to 82.2\% while the model size is reduced from 64.3M to 49.9M and the FLOPs is reduced from 12.4B to 9.5B. Note that, after removing sMLP from the first three stages, the resulting model is obviously inferior to the sMLPNet-S based model which obtains 83.1\% accuracy at a model size of 48.8M. This result emphasizes the necessity of global dependency modeling in early stages of the network. One may wonder why sMLP module brings the most number of parameters and computational cost in stage 3. Besides the fact that stage 3 has the most number of layers, it is mainly caused by the expansion of the fusion module, whose parameter size and computational complexity both grow with the square of the number of channels. It is natural to ask whether there exists a more efficient fusion method than an FC layer. \subsubsection{Fusion in sMLP.} \begin{table}[t] \centering \begin{tabular}{c|c c c c} \hline & Param(M) & FLOPs(B) & Top-1(\%) \\ \hline sMLPNet-S &48.6 &10.3 &83.1 \\ \hline Sum &33.2 &7.0 & 81.5 \\ Weighted sum &33.3 &7.0 &81.8 \\ \hline sMLPNet-T & 24.1 & 5.0 & 81.9 \\ \hline \end{tabular} \caption{Comparison of different fusion methods. Base model is sMLPNet-S ($\alpha=3$) which uses an FC layer for data fusion. Sum and weighted sum are two alternative fusion methods.} \label{tab:Fusion method} \end{table} We try two light-weight operations as the alternatives to the fusion method in sMLPNet. One is element-wise addition, which is parameter-free and costs few FLOPs in run time. The other is weighted sum. Specifically, each channel is multiplied by a learnable weight before addition. The number of parameters in weighted sum operation is also very small and the computational cost almost negligible. We use sMLPNet-S as the base model and the experimental results are shown in Table \ref{tab:Fusion method}. Besides the fusion method, we do not change any other modules in the network, including the number of channels and the number of layers in each stage. Compared to baseline, which has 48.6M parameters and 10.3B FLOPs, the two alternative fusion methods bring much fewer parameters and FLOPs. But the image recognition accuracy also drops from 83.1\% to 81.5\% and 81.8\%. While it is understandable that the accuracy decreases with the decreased size of model, we list the performance of sMLPNet-T as a reference. sMLPNet-T uses the default fusion method and it achieves 81.9\% accuracy at a model size of 24.1M. This confirms that using concatenation and an FC layer as the fusion module achieves the best model size and accuracy trade-off among the different fusion methods we evaluated. \subsubsection{Branches in sMLP.} \begin{table}[t] \centering \begin{tabular}{c|c c} \hline & Parallel & Sequential \\ \hline w Identity &81.3 &81.1 \\ w/o Identity &80.9 &80.6 \\ \hline \end{tabular} \caption{Ablation study on the design of the branches in the sMLP module. We use sMLPNet-T* ($\alpha=2$) as the base model (parallel connection with the identity mapping).} \label{tab:Parallel versus Sequential} \end{table} In the default setting of sMLP, we use three parallel branches for horizontal processing, vertical processing, and identity mapping, respectively. In this experiment, we try a different fashion to connect the horizontal processing and the vertical processing. We also verify the effectiveness of the identity mapping. The base model for this set of experiments is sMLPNet-T with expansion parameter $\alpha=2$. The two choices to connect horizontal and vertical processing are parallel, as in the default setting, and sequential. We combine these two choices with the choice to use or not use the identity mapping to create four settings. The performance of these four settings are shown in Table \ref{tab:Parallel versus Sequential}. If we compare results within each column, we can tell that using identity mapping always brings better results. The improvement is in the range of 0.4\% and 0.5\%, which is considered significant. If we compare results within each row, we can tell that parallel processing is always better than sequential processing. Note that sequential mode can be implemented by horizontal first or vertical first. We tried both settings and got exactly the same results. As such, we validate our selection of parallel mode with identity mapping in the final design of sMLP block. \iffalse \begin{table}[t] \centering \begin{tabular}{c|c c c c} \hline & Param(M) & FLOPs(B) & Top-1(\%) \\ \hline sMLPNet-T($\alpha=2$) &19.2 &3.96 &81.3 \\ w/o Identity &16.71 &3.44 &80.9 \\ \hline \end{tabular} \caption{Ablation study on the influence of identity mapping path in sMLP block. We use sMLPNet-T model with expansion ratio $\alpha=2$ as baseline. w/o Identity: delete the identity mapping path and keep others unchanged.} \label{tab:Identity mapping} \end{table} In order to make sure the effectiveness of identity mapping path in sMLP block, we also try to delete the identity mapping path. The results are shown in table\ref{tab:Identity mapping}. Compared to the proposed sMLPNet-T model, after delete the identity mapping path, the accuracy will reduce from 81.3\% to 80.9\% which shows the effectiveness of the identity mapping. \fi \subsubsection{Multi-Stage Processing in Pyramid Structure.} \begin{table}[t] \centering \begin{tabular}{c|c c c c} \hline & Param(M) & FLOPs(B) & Top-1(\%) \\ \hline sMLPNet-T* &19.2 &4.0 &81.3 \\ Multi-stage MLP &22.7 &4.2 &77.8 \\ Single-stage MLP &30.4 &6.5 &76.8 \\ \hline \end{tabular} \caption{Ablation study on the effects of multi-stage architecture. Multi-stage MLP: sMLP at stage 1 is replaced by depth-wise conv and the sMLP at stage 2,3,4 is replaced by MLP. Single-stage MLP: all of the sMLP is replaced to MLP and multi-stage is replaced to singe-stage with patch size equal to $16\times16$.} \label{tab:multi-stage} \end{table} Enabling multi-stage processing in a pyramid structure is one of the major objectives of our work. Such a design choice has been validated in CNNs for numerous network backbones and downstream tasks. While it is intuitive to stick to this choice when global dependency modeling is added to the network, we still need to verify it through numerical evidence. In this experiment, we are actually comparing the single-stage version and the multi-stage versions of MLP networks. But we built these two models from a base sMLPNet model. Specifically, we take a tiny sMLPNet model ($\alpha=2$) and replace all the sMLP blocks in stage 2, 3, and 4 with the normal MLP blocks. The sMLP blocks in stage 1 is replaced by DWConv, as MLP blocks are too heavy to be used in stage 1. This is referred to as the multi-stage MLP model in Table \ref{tab:multi-stage}. We can see that the top-1 accuracy of this model is only 77.8\%, with 3.5\% performance loss with respect to the base sMLPNet-T model. Then, we flatten the spatial resolutions of all stages and use an initial patch size of $16 \times 16$ to build the single-stage MLP model. Table \ref{tab:multi-stage} shows that it achieves an even lower top-1 accuracy of 76.8\% on ImageNet-1K dataset. This is consistent with the performance reported by MLP-Mixer when it is trained on ImageNet-1K. This experiment clearly shows the advantage of multi-stage processing. In addition, it demonstrates the huge gain we have achieved over the straightforward design of an MLP network. \subsection{Comparison with State-of-the-Art} \begin{table}[t] \centering \begin{tabular}{c|c c c} \hline Model& Params(M)& FLOPs(B) & Top-1(\%) \\ \cline{2-4} & \multicolumn{3}{|c} {ConvNets} \\ \hline ResNet-50 & 25.6 & 4.1 & 76.2 \\ ResNet-152 & 60.2 & 11.5 & 78.3 \\ RegNetY-4GF & 21 & 4.0 & 80.0 \\ RegNetY-8GF & 39.2 & 8.0 & 81.7 \\ RegNetY-16GF & 83.6 & 15.9 & 82.9 \\ \hline & \multicolumn{3}{|c} {Transformers} \\ \hline ViT-B/16 & 86.4 & 17.6 & 79.7 \\ DeiT-S/16 & 22 & 4.6 & 79.8 \\ DeiT-B/16 & 86.4 & 17.6 & 81.8 \\ DeepVit-S & 27 & 6.2 & 81.4 \\ DeepVit-L & 55 & 12.5 & 82.2 \\ Swin-T & 29 & 4.5 & 81.3 \\ Swin-S & 50 & 8.7 & 83.0 \\ Swin-B & 88 & 15.4 & 83.5 \\ \hline & \multicolumn{3}{|c} {MLP-like} \\ \hline Mixer-B/16 & 59 & 12.7 & 76.4 \\ Mixer-L/16 & 207 & 44.8 & 71.8 \\ ResMLP-12& 15 & 3.0 & 76.6 \\ ResMLP-24& 30 & 6.0 & 79.4 \\ ResMLP-36 & 45 & 8.9 & 79.7 \\ gMLP-S& 20 & 4.5 & 79.4 \\ gMLP-B& 73 & 15.8 & 81.6 \\ \hline sMLPNet-T* (ours) &19.2 &4.0 &81.3 \\ sMLPNet-T (ours) &24.1 &5.0 &81.9 \\ sMLPNet-S (ours) &48.6 &10.3 &83.1 \\ sMLPNet-B (ours) &65.9 &14.0 &83.4 \\ \hline \end{tabular} \caption{Comparing the proposed sMLPNet with state-of-the-art vision models. The default expansion parameter in the FFN of sMLPNet is $\alpha=3$. sMLPNet-T* uses $\alpha=2$. All models are trained on ImageNet-1K benchmark without extra data. The resolution of the input image is $224 \times 224$ for all the models.} \label{tab:main results} \end{table} We have validated the various design choices in the proposed sMLPNet. Next, we show how this attention-free network compares with state-of-the-art vision models on the image recognition task. All the models we refer to are trained on ImageNet-1K benchmark only. For fairness, all of them use an input image size of $224 \times 224$. The results are summarized in Table~\ref{tab:main results}. We group the existing methods into three categories, namely CNN-based, Transformer-based, and MLP-like models. Some of the designs have three different model sizes while some others have two. The model size is indicated by the suffix of T (tiny), S (small), B (base), and L (large). We also list the theoretical model size and FLOPs in the table for the comparison across different designs. In the CNN-based vision models, the RegNetY \cite{radosavovic2020designing} series have a large advantage over the classic ResNet series. Transformer-based models \cite{touvron2021training, zhou2021deepvit, liu2021swin}, except the very first ViT model \cite{dosovitskiy2020image}, perform on par with RegNetY series. But most MLP-like models \cite{touvron2021resmlp, liu2021pay} only achieve similar performance as ResNet series. Besides, serious over-fitting phenomenon is observed in Mixer-L model. Its accuracy dramatically drops from 76.4\% of the Mixer-B model to 71.8\%. It explains from the opposite side why sMLPNet achieves good performance by the reduction of parameters. Among these existing models, Swin Transformer performs the best. Our designed model, despite the fact that it belongs to the MLP-like category, performs on par with or even better than Swin Transformer. In particular, sMLPNet-T achieves 81.9\% top-1 accuracy, which is the highest among the existing models with FLOPs fewer than 5B. The performance of sMLPNet-B is also very impressive. It achieves the same top-1 accuracy as Swin-B, but the model size is 25\% smaller (65.9M vs. 88M) and the FLOPs are nearly 10\% fewer (14.0B vs. 15.4B). Remarkably, there is no sign of over-fitting, which is the main problem that plagues the MLP-like methods, when the model size grows to nearly 66M. This shows that an attention-free model could attain SOTA performance, and the attention mechanism might not be the secret weapon in the top-performing Transformer-based models. \section{Conclusion and Discussion} In this paper, we have built an MLP-like architecture for visual recognition based on the novel sMLP block. The sMLP block we have proposed in this work is featured by sparse connection and weight sharing. By separately aggregating information along axial directions, sMLP avoids the quadratic model size and quadratic computational complexity of conventional MLP. Experimental results have shown that this has greatly pushed up the performance boundary of MLP-like vision models. We notice that some concurrent Transformer-based models, such as CSwin \cite{dong2021cswin}, have obtained an even higher accuracy than sMLPNet. For example, 84.2\% top-1 accuracy is achieved with a model of 78M parameters. But this does not affect the value of our work, which challenges the necessity of the self-attention mechanism by demonstrating how well an attention-free network could perform. That being said, we have to admit that MLP-like architecture has its inherent limitation. Due to the fixed nature of FC layers, MLP-like models cannot be easily adapted to process input images with arbitrary resolutions. This makes MLP-like models hard to be applied in some important down-stream tasks such as object detection and semantic segmentation. Again, it is an inherent drawback of MLP-like architecture and is beyond the scope of our work. In the future, we plan to investigate the possibility to build attention-free versatile networks.
{'timestamp': '2022-05-31T02:17:24', 'yymm': '2109', 'arxiv_id': '2109.05422', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05422'}
arxiv
\section{Introduction} \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{toy_example_3-050715.jpg} \caption{Two cases in the Reddit dataset. We use the ConceptNet as the external graph to show concept shifts in the conversation. Nodes are marked in \textcolor{blue}{blue}. Concept relations in the graph and those in the natural conversation are marked with \textcolor{red}{red} solid lines and \textcolor{blue}{blue} dashed lines, respectively.} \label{fig:example} \end{figure} With the rapid development of the natural language generation models \cite{Radford2019language, ZhangSGCBGGLD20, BrownMRSKDNSSAA20} and the increase of the open-domain conversation corpora \cite{RashkinSLB19, CuiWLZZ20, ZhouZHHZ20, KielaWZDUS18}, the quality of the response generated by the chatbot has been significantly improved. However, there still exist a series of challenges in the generative chatbot \cite{GaoLZBGGD19, HuangZG20}. Most of the time, users can still clearly distinguish between a human talker and a machine chatbot. Part of the reason is that the human is good at naturally switching the topics across the utterances, while the chatbot is relatively dull and tends to keep the topic still \cite{fang2018sounding} or throw an unexpected topic \cite{WangHXSN18, TangZXLXH19}. As topic flows in the natural conversation could be observed as the shifts of the mentioned concepts across utterances, \newcite{ZhangLXL20} employ the \textbf{ConceptNet} \cite{SpeerCH17} as the external knowledge graph and suggest that the graph provides relation-based one-hop and two-hop concepts to help the response generation. Their work is established on a restricted logical assumption: people would like to continuously talk on concepts that have commonsense relations to the current concepts in the ConceptNet. We argue the assumption is too simple to imitate topic flows in human conversations. The ConceptNet is a commonsense graph built based on the concepts and their relations in the real world instead of in the natural conversational scenarios. Thus, only introducing the ConceptNet is insufficient for guiding the response generation. Figure \ref{fig:example} presents two instances in the Reddit conversation dataset for further explanation. Nodes and edges in the ConceptNet are marked to show concept shifts in conversations. For some concept relations that are common in the natural conversation, such as from ``\textcolor{blue}{offline}'' to ``\textcolor{blue}{internet}'' and from ``\textcolor{blue}{Harden}'' to ''\textcolor{blue}{rockets}'', there are not corresponding edges in the ConceptNet. Therefore, only exploiting knowledge information in the ConceptNet could not cover topic flows in the natural conversation comprehensively. To address the issue, we propose to reconstruct an enhanced graph that consists of concept relations in both the commonsense knowledge graph and the natural conversation. Specifically, we extract new concepts as nodes and the high-frequency concurrence between concepts as edges from the conversation corpora. We then add these new nodes and new edges to the ConceptNet to reconstruct the enhanced graph, which is used at the training and inference procedure for providing hints for the target response. Besides, we design a novel, powerful, and fast Transformer architecture named \textbf{Edge-Transformer} to encode the enhanced graph, replacing the Graph Neural Networks(GNN). We conduct experiments on the Reddit conversation dataset. The experimental results show our method outperforms strong baselines and achieves new state-of-the-art performances on many metrics. We further conduct a series of analysis experiments, which results individually indicate the effectiveness of our proposed enhanced graph and the Edge-Transformer architecture. Our contributions could be summarized as follows: \begin{itemize} \item To bridge the gap between concept relations in the external knowledge graph and those in the natural conversation, we reconstruct an enhanced graph with new nodes and edges extracted from the conversation corpora. \item We design a novel, powerful and fast architecture named \textbf{Edge-Transformer} that replaces the traditional GNN architecture to encode the enhanced graph. \item Plenty of experiments verify the effectiveness of our method and the importance of concept relations in the conversation corpora. Our method achieves a new state-of-the-art performance on the Reddit conversation dataset. \end{itemize} \section{Related Work} \begin{figure*}[ht] \centering \includegraphics[width=\textwidth]{pipeline_3.png} \caption{The pipeline of our method. Firstly, we extract nodes and edges from the dialog corpora, then merge them with nodes and edges in the ConceptNet, to reconstruct the enhanced graph. Secondly, we retrieve a subgraph $g$ according to the post $X$. We also get a special node $X'$ by the last hidden state of the encoder. $g$ and $X'$ are then encoded by the Edge-Transformer architecture we design. Thirdly, the output of the Edge-Transformer and the output of the encoder are fed into the decoder for response generation. We implement the attention mechanism and the copy mechanism to help generation.} \label{fig2} \end{figure*} The end-to-end generative chatbot \cite{SutskeverVL14} achieves better performance in recent years due to more powerful model architectures\cite{Radford2019language, ZhangSGCBGGLD20, BrownMRSKDNSSAA20} and larger conversation corpora \cite{ZhengCHLZ19, CuiWLZZ20}. However, there also exist a series of challenges in the response generation \cite{HuangZG20}, such as off-topic and uninformative responses\cite{GaoLZBGGD19}. Based on the fact that the natural conversation depends on human knowledge, many works introduce various knowledge, such as background documents \cite{ZhouPB18, GhazvininejadBC18}, commonsense knowledge base\cite{ZhuMZZPY17}, external knowledge graphs\cite{MoonSKS19} for constructing human-like chatbot. \newcite{ZhouHZZL18} exploit concept relations in the ConceptNet, to imitate concept shifts in human conversation. For a post, they retrieve a subgraph from the ConceptNet, which consists of 0-hop nodes, 1-hop nodes, and edges between these nodes. The subgraph is encoded by the GNN architecture and then introduced to the response generation model. Following this work, \newcite{ZhangLXL20} add 2-hop nodes to the subgraph to cover human concept shifts more comprehensively. We also exploit the ConceptNet, but we argue that only utilizing knowledge information in the ConceptNet is not sufficient because of the gap between concept relations in the commonsense knowledge graph and those in the natural conversation. Thus, we propose to enhance the ConceptNet with the conversation corpora. What's more, to encode the enhanced graph, we design a novel, powerful and fast architecture named Edge-Transformer that replaces the traditional GNN architecture. There also exist works that directly construct the conversation graph from the real conversation corpora for improving the response generation \cite{TangZXLXH19, XuWNWCL20}. The conversation graph only contains knowledge in the corpora, so its quality is affected by the corpora. In contrast, our enhanced graph is of higher quality because it is built based on the ConceptNet and contains human commonsense knowledge. \section{Method} We present our method in this section. We first introduce the overview of our method, then describe three steps of the pipeline in detail. \subsection{Overview} Given a conversation corpus $D = \{(X, Y)\}$ where $(X, Y)$ is a dialogue pair in the corpus, we aim to generate the response $Y$ based on the post $X$. With an external knowledge graph $G = (V, E)$ where $V$ and $E$ are nodes and edges in the graph, our task could be formulated as generating best hypothesis $Y'$ which maximizes the following probability: \begin{align} Y' = argmaxP(Y|X, G) \end{align} We propose a three-stage method for the task, and the pipeline is presented in Figure \ref{fig2}. Firstly, to bridge the gap between concept relations in the ConceptNet and those in the human conversation, we enhance the ConceptNet with the conversation corpora and reconstruct an enhanced graph $G_e$. Specifically, we extract new nodes and new edges from the conversation corpora $D$, then add them into the ConceptNet $G$. Secondly, since introducing the whole graph to the generation process is unpractical and unnecessary, we retrieve a subgraph $g$ from $G_e$ according to the post $X$. We then design a novel, powerful and fast architecture named Edge-Transformer to replace the traditional GNN architecture. The subgraph $g$ and a special node $X'$ are fed to the Edge-Transformer architecture. Thirdly, to ensure the generation process is guided by knowledge information in $g$, we apply the attention mechanism and the copy mechanism to the classical encoder-decoder framework so that decoder could give responses based on the subgraph $g$, the output of the Edge-Transformer architecture and the output of the encoder. \subsection{Reconstruct the Enhance Graph} For some concepts not in the ConceptNet,they are important and frequent in the conversation corpora. Therefore, we add them to the ConceptNet as new nodes so that the enhanced ConceptNet could cover more concepts. We set a frequency interval based on the word frequency of nodes in the ConceptNet. To ensure the extracted nodes have rich semantic information, we choose nouns in the interval as new nodes. For some concept relations common in the natural conversation, there are not corresponding edges in the ConceptNet. Therefore, we extract some new edges from the conversation corpus and add them to the ConceptNet, to ensure that the enhanced graph could cover concept shifts more comprehensively. We run the GIZA++ alignment tool \footnote{http://www.statmt.org/moses/giza/GIZA++.html} \cite{och03:asc} to align concepts. For a pair of concepts with high alignment probability, we add a new edge between them in the ConceptNet, and the edge has a new category: ``DialogFlowTo''. More details are given in the Appendix we provide. \subsection{The Edge-Transformer Architecture} We make three novel improvements in the vanilla Transformer architecture and propose our Edge-Transformer architecture, which is presented in Figure \ref{fig3}. Firstly, to model the interaction between the post $X$ and the subgraph $g$, we get a special node $X'$ by encoding $X$. $X'$ is added to $g$ and connected to all nodes in $g$. Secondly, the vanilla Transformer architecture can only be used to model the directed complete graph, because each node can obtain information from all other nodes through the attention mechanism. To address the problem, we alter the attention mask in the architecture. Specifically, if there is no edge $(a, b)$ from node $a$ to node $b$ in the graph, we will mask the attention from $b$ to $a$. In this way, the target node could only get information from its source nodes and the architecture could model any directed graph. Thirdly, the vanilla Transformer architecture could not model edge type information in the graph, while there are various edges in the enhanced ConceptNet. To address the problem, we introduce edges information to the forward calculation process of the architecture, as follows: \begin{align} h_{p}^{(l+1)} &= FFN(h_{p}^{(l)} + u_{p}^{(l)})\\ u_{p}^{(l)} &= \sum\limits_{q \in S(p)} a_{p, q}^{(l)} V^l(h_{q}^{(l)})\\ a_{p, q}^{(l)} &= Q^{(l)}(h_{p}^{(l)})K^{(l)}(h_{q}^{(l)})^T + R^{(l)}(e_{q, p}) \end{align} \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{graph_structure.png} \caption{Our proposed Edge-Transformer architecture. We show how we use the architecture to encode the subgraph $g$ and the special node $X'$. Attention mask corresponds to edges in the graph structure.} \label{fig3} \end{figure} Where $h_{p}^{(l)}$ is the vector of node $p$ in the $l$ layer, and $u_p^{(l)}$ is information from source nodes of $p$ in the $l$ layer. $S(p)$ is source nodes set of $p$, and $a_{p,q}^{(l)}$ is the attention weight. $Q^{(l)}, K^{(l)}, V^{(l)}, R^{(l)}$ are different FFN networks in the $l$ layer, and $e_{q, p}$ is the type of edge $(q,p)$ \footnote{For edges from a node to itself, we give them a new category: ``SelfTO''. For edges from and to $X'$, we give them two new categories: ``FromText'' and ``ToText''.}. \subsection{Response Generation} For the post $X$, the subgraph $g$ contains concepts often thought of in the natural conversation scenario. We implement the attention mechanism on the output of the Edge-Transformer architecture, to ensure the decoder could focus on proper concepts during the generation process. When generating $t$-th response token, the decoder state $s_t$ is updated as follows: \begin{align} s_t = f_{dec}(s_{t-1}, y_{t-1}, c_{t-1}^{text}, c_{t-1}^{graph}) \end{align} Where $y_{t-1}$ is the token generated in the last step. $c_{t-1}^{text}$ and $c_{t-1}^{graph}$ are outputs of the attention mechanism from the post and the subgraph, respectively. $f_{dec}$ are the updating function of the decoder. \begin{table*}[ht] \small \centering \begin{tabular}{c|c|c|c|c|c|c|c|c|c} \hline \multirow{2}{*}{\textbf{graph}} & \multirow{2}{*}{\textbf{nodes}} & \multirow{2}{*}{\textbf{edges}} & \multirow{2}{*}{\textbf{response nodes}} & \multicolumn{2}{c|}{\textbf{0-hop nodes}} & \multicolumn{2}{c|}{\textbf{1-hop nodes}} & \multicolumn{2}{c}{\textbf{2-hop nodes}} \\ \cline{5-10} & & & & amount & golden & amount & golden & amount & golden \\ \hline $G$ & 21471 & 120850 & 5.691 & 5.8129 & 0.5998 & 90.5138 & 1.2064 & 99.7706 & 0.8823 \\ $G_e$ & 21754 & 218478 & 6.192 & 6.3223 & 0.6352 & 100.6227 & 1.4114 & 99.7706 & 0.8823 \\ \hline \end{tabular} \caption{Statistics of graphs coverage on the conversation dataset. Amount and golden are the number of total concepts and concepts appearing in responses, respectively. Obviously, $G_e$ has a higher coverage than $G$.} \label{tab:graph statistics} \end{table*} Humans usually mention concepts related to the current topic during the conversation. To imitate this phenomenon, we implement the copy mechanism so that the decoder could direct copy nodes from the subgraph as output tokens. We design a binary scalar $\sigma$ as a gate to control the generation source: vocabulary or the subgraph. Thus, the generation probability is the sum of probability on these two sources. The calculation process of $t$-th response token could be formulated as follows: \begin{align} \sigma &= FFN(s_t) \\ p_t &= (1 - \sigma) p_t^{vocab} + \sigma p_t^{copy} \\ p_t^{vocab} &= FFN(s_t) \\ p_t^{copy} &= FFN(a_t) \end{align} Where $p_t$, $p_t^{vocab}$ and $p_t^{copy}$ are total prob, prob from vocabulary and prob from the subgraph, respectively. And $a_t$ is the attention weight on the output of the Edge-Transformer architecture. We use the cross-entropy function as the loss to train our model. And the loss of our method contains three parts: the generation loss, the copy loss, and the gate loss, as follows: \begin{align} \mathcal{L} = \mathcal{L}_{gen} + \mathcal{L}_{copy} + \mathcal{L}_{gate} \end{align} \section{Experiment} \subsection{Dataset} We conduct our experiments on Reddit conversation dataset \cite{ZhouYHZXZ18}. The dataset is a single turn open-domain dialogue dataset, and all utterances are collected from Reddit. The dataset contains 3,384,160 training pairs and 10,000 testing pairs. We use the preprocessed ConceptNet as the external knowledge graph \cite{SpeerCH17}, which includes 21,471 nodes and 120,850 edges. And there are 44 types of edges in the graph. \subsection{Baselines} We follow \citet{ZhangLXL20} and use three groups of models as baselines. We list them here: \begin{itemize} \item \textbf{Standard seq2seq model}\cite{SutskeverVL14}. The model is based on the classical encoder-decoder framework. The encoder and the decoder are RNN architectures. \item \textbf{Knowledge enhanced seq2seq models}: MemNet\cite{GhazvininejadBC18}, CopyNet\cite{ZhuMZZPY17}, CCM\cite{ZhouYHZXZ18} and ConceptFlow\cite{ZhangLXL20}. These models introduce knowledge information into the generation process. \item \textbf{Pretraind Models:} GPT-2 lang\cite{ZhangLXL20}, GPT-2 conv\cite{ZhangLXL20}, DialoGPT\cite{ZhangSGCBGGLD20}. These models have a large number of parameters and have been pretrained on large corpus. GPT-2 lang and GPT-2 conv are built based on GPT-2\cite{Radford2019language}. \end{itemize} For seq2seq, MemNet, CopyNet, CCM, GPT-2 lang and GPT-2 conv, we directly use results in ConceptFlow paper \cite{ZhangLXL20}. For ConceptFlow, we run their public codes\footnote{https://github.com/thunlp/ConceptFlow.}. For DialoGPT, we finetune it on the dataset \footnote{https://huggingface.co/microsoft/DialoGPT-medium}. \subsection{Evaluation Metrics} \subsection{Automation Evaluation} \begin{table*}[ht] \small \centering \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c} \hline \textbf{model} & \textbf{Bleu-3} & \textbf{Bleu-4} & \textbf{Nist-3} & \textbf{Nist-4} & \textbf{Rouge-1} & \textbf{Rouge-2} & \textbf{Rouge-L} & \textbf{meteor} & \textbf{PPL} & \textbf{Ent-4} \\ \hline \hline seq2seq & 0.0226 & 0.0098 & 1.1056 & 1.1069 & 0.1441 & 0.0189 & 0.1146 & 0.0611 & 48.79 & 7.6650 \\ \hline MemNet & 0.0246 & 0.0112 & 1.1960 & 1.1977 & 0.1523 & 0.0215 & 0.1213 & 0.0632 & 47.38 & 8.4180 \\ CopyNet & 0.0226 & 0.0106 & 1.0770 & 1.0788 & 0.1472 & 0.0211 & 0.1153 & 0.0610 & 43.28 & 8.4220 \\ CCM & 0.0192 & 0.0084 & 0.9082 & 0.9095 & 0.1538 & 0.0211 & 0.1245 & 0.0630 & 42.91 & 7.8470 \\ ConceptFlow & 0.0495 & 0.0239 & 1.8838 & 1.8896 & 0.2241 & 0.0457 & 0.2032 & 0.0956 & 29.44 & 10.2390 \\ \hline GPT-2(lang) & 0.0162 & 0.0162 & 1.0840 & 1.0844 & 0.1321 & 0.0117 & 0.1046 & 0.0637 & 29.08* & \textbf{11.6500} \\ GPT-2(conv) & 0.0262 & 0.0124 & 1.1745 & 1.1763 & 0.1514 & 0.0222 & 0.1212 & 0.0629 & 24.55* & 8.5460 \\ DialoGPT & 0.0189 & 0.0095 & 0.9986 & 0.9993 & 0.0985 & 0.0117 & 0.0971 & 0.0546 & \textbf{18.65*} & 9.8163 \\ \hline Ours & \textbf{0.0644} & \textbf{0.0331} & \textbf{2.2573} & \textbf{2.2661} & \textbf{0.2592} & \textbf{0.0601} & \textbf{0.2340} & \textbf{0.1091} & 25.98 & 10.8173 \\ \hline \end{tabular} \caption{Evaluation results on automatic metrics. We bold the best scores on each metric. The PPL scores of pretrained models are not comparable because of different tokenization. The results indicate that our method gets the highest scores on most metrics. More results are in the Appendix we provide.} \label{tab:automation} \end{table*} We use following metrics for evaluation: \begin{itemize} \item \textbf{Perplexity} \cite{SerbanSBCP16}: Perplexity measures the fluency of the responses. \item \textbf{Bleu \cite{ChenC14}, Nist \cite{DoddingtonG02}, ROUGE\cite{LinY04}} : These metrics measure the overlap between the generated responses and the ground truth. \item \textbf{Meteor} \cite{AlonAA07}: Meteor measure the relevance between the generated responses and the ground truth. \item \textbf{Entropy} \cite{ZhangGGGLBD18}: Entropy measures the diversity of generated responses. \end{itemize} We implement the above metrics based on the code of \citet{Galley18} \footnote{https://github.com/DSTC-MSR-NLP/DSTC7-End-to-End-Conversation-Modeling}. \subsection{Implementation Details} Since ConceptFlow \cite{ZhangLXL20} has processed the Reddit conversation dataset with the ConceptNet, we rebuild the dataset based on their data, and details could be found in the Appendix we provide. Table \ref{tab:graph statistics} presents the coverage of the ConceptNet and our enhanced graph on the Reddit conversation dataset. For our model, we use two-layer GRUs \cite{ChoMGBBSB14} as the encoder and the decoder. We set the layers of our Edge-Transformer architecture to 3. We choose Adam as the optimizer, and the batch size, learning rate, max gradients norm, dropout are set to 30, 1e-4, 5, 0.2, respectively. We use TransE embedding \cite{BordesUGWY13} and Glove embedding \cite{PenningtonSM14} to initialize the embedding of concepts and words, respectively. We train our method on 8 V100 GPUs, and it takes about 1.5 hours to train an epoch. Our codes are presented in the supplementary materials. \section{Evaluation} \begin{table}[ht] \small \centering \begin{tabular}{c|c|c|c} \hline \multirow{2}{*}{\textbf{}} & \multicolumn{3}{c}{\textbf{Fluency}} \\ \cline{2-4} & \textbf{Average} & \textbf{Best @1} & \textbf{kappa} \\ \hline \textbf{ConceptFlow} & 2.2875 & 0.24 & 0.563 \\ \textbf{Ours} & 2.4325 & 0.30 & 0.603 \\ \textbf{Golden} & \textbf{2.6975} & \textbf{0.69} & \textbf{0.665} \\ \hline \multicolumn{1}{l|}{\multirow{2}{*}{}} & \multicolumn{3}{c}{\textbf{Appropriateness}} \\ \cline{2-4} \multicolumn{1}{l|}{} & \textbf{Average} & \textbf{Best @1} & \textbf{kappa} \\ \hline \textbf{ConceptFlow} & 1.6200 & 0.12 & 0.480 \\ \textbf{Ours} & 1.6850 & 0.16 & 0.563 \\ \textbf{Golden} & \textbf{2.3275} & \textbf{0.81} & \textbf{0.603} \\ \hline \end{tabular} \caption{Evaluation results by human annotators. We also present Fleiss’ Kappa in the table. Kappa values range from 0.4 to 0.6, indicating fair agreement.} \label{tab:human} \end{table} The evaluation results are shown in Table \ref{tab:automation}. Except pretrain models, our method achieves the lowest PPL score, indicating that the responses generated by our model are more fluent. Bleu, Nist, Rouge, and meteor measure the relevance of generated responses and ground truth responses on different aspects. Our method outperforms all baselines by large margins on these metrics, demonstrating the responses generated by our method are more on-topic. For entropy, our method gets the second-highest score, just lower than GPT-2. It proves that our proposed method could generate diverse responses. GPT-lang gets the highest diversity score, but it gets the lowest scores in most relevance metrics like Nist and Rouge. In comparison, our method has a good balance in relevance and diversity. \subsection{Human Evaluation} \begin{table*}[ht] \small \centering \begin{tabular}{c|c|c|c|c|c|c|c|c} \hline \textbf{model} & \textbf{Bleu-3} & \textbf{Bleu-4} & \textbf{Nist-3} & \textbf{Nist-4} & \textbf{Rouge-L} & \textbf{meteor} & \textbf{PPL} & \textbf{Ent-4} \\ \hline \hline Ours($G_e$ + edge-Transformer) & 0.0644 & 0.0331 & 2.2573 & 2.2661 & 0.2340 & 0.1091 & 25.98 & 10.8173 \\ $G$ + edge-Transformer & 0.0615 & 0.0319 & 2.1448 & 2.1541 & 0.2307 & 0.1055 & 26.40 & 10.7081 \\ $G_e$ + GRAFT-Net & 0.0529 & 0.0267 & 1.9270 & 1.9340 & 0.2115 & 0.0976 & 27.81 & 10.4316 \\ ConceptFlow($G$ + GRAFT-Net) & 0.0493 & 0.0246 & 1.8265 & 1.8329 & 0.1888 & 0.0942 & 29.90 & 10.2700 \\ \hline \end{tabular} \caption{Evaluation results of models with different combinations of graphs and graph encoding architectures. The results show that $G_e$ outperforms $G$ and the Edge-Transformer outperforms the GRAFT-Net.} \label{tab:control} \end{table*} \begin{table*}[ht] \small \centering \begin{tabular}{c|c|c|c|c|c|c|c|c} \hline \textbf{model} & \textbf{Bleu-3} & \textbf{Bleu-4} & \textbf{Nist-3} & \textbf{Nist-4} & \textbf{Rouge-L} & \textbf{meteor} & \textbf{PPL} & \textbf{Ent-4} \\ \hline \hline enhanced graph & 0.0644 & 0.0331 & 2.2573 & 2.2661 & 0.2340 & 0.1091 & 25.98 & 10.8173 \\ - edges in bottom 20\% & 0.0634 & 0.0328 & 2.2102 & 2.2194 & 0.2322 & 0.1070 & 27.17 & 10.7391 \\ - edges in bottom 50\% & 0.0502 & 0.0249 & 1.8466 & 1.8528 & 0.2044 & 0.0938 & 30.77 & 10.2637 \\ \hline \end{tabular} \caption{Evaluation results after removing edges in the ConceptNet. More results are in the Appendix.} \label{tab:effective} \end{table*} To further evaluate model performances, we hire four human annotators to judge the quality of generated responses. Annotators are required to score the responses on two aspects: fluency and appropriateness. Fluency evaluates whether a response is fluent or contains any grammar errors, while appropriateness evaluates whether a response is relevant to its post. Specifically, we sample 100 cases for three methods: ConceptFlow, ours, and golden (ground truth responses), and all responses are scored from 1 to 3 on two aspects. Human evaluation result is shown in Table \ref{tab:human}. Obviously, ground truth responses get the highest average scores. The average scores of our method are higher than the scores of ConceptFlow on both aspects, indicating our method could give more fluent and more relevant responses. And the best @1 ratios of our method are also higher than ConceptFlow, demonstrating that humans are more willing to chat with our chatbot. The results of the automatic evaluation and human evaluation prove the effectiveness of our method. With the enhanced graph and the Edge-Transformer architecture, our method could give responses of higher quality. Next, we conduct a series of experiments to study the effectiveness of the enhanced graph and the Edge-Transformer architecture individually. \subsection{Analysis of the Enhanced Graph} \label{graph analysis} In this part, we conduct a series of experiments to study the effectiveness of the enhanced graph $G_e$. \textbf{The enhanced graph VS the ConceptNet.} Considering that our method utilizes the enhanced graph and the edge-Transformer architecture ($G_e$ + edge-Transformer) while ConcpetFlow \cite{ZhangLXL20} utilizes the original ConceptNet and the GNN-based architecture named GRAFT-Net \cite{SunDZMSC18} ($G$ + GRAFT-Net), we conduct two more models to directly compare $G_e$ and $G$. The first model is built on $G$ + Edge-Transformer, and the second is built on $G_e$ + GRAFT-Net. The result is presented in Table \ref{tab:control}. Obviously, with the same graph encoding architecture, models with $G_e$ achieve better performances on all metrics than models with $G$. The comparison results show that $G_e$ is more helpful to the response generation. And the importance of concept relations from the conversation corpora is also proved. \textbf{Concept relations from the conversations corpora VS those in the ConceptNet.} Now that we prove concept relations from the conversation corpora are important for the response generation, there is one more question to answer: Is it enough to only exploit concept relations from the conversation corpora? In other words, is the external commonsense knowledge graph such as the ConceptNet unnecessary? To study the question, we remove some edges in the ConceptNet when reconstructing the enhanced graph, and implementation details are given in the Appendix. The evaluation result is shown in Table \ref{tab:effective}. Our method gets lower scores on all metrics after reducing edges. And reducing more edges results in worse performances. We could infer that concept relations, which are rare in the natural conversations, are also important for guiding topic flows in the response generation process. Thus, knowledge information in both the external graph and the conversation corpora are necessary, and a good way is to merge them like our method. \begin{table}[ht] \small \centering \begin{tabular}{c|c|c} \hline \textbf{model} & \textbf{parameters} & \textbf{training time/epoch} \\ \hline Edge-Transformer & \textbf{34.6M} & \textbf{1.5h} \\ GRAFTGNN & 35.3M & 2.5h \\ \hline \end{tabular} \caption{Computation resources of different graph encoding architectures.} \label{tab:computation} \end{table} \begin{table*}[ht] \small \centering \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c} \hline \textbf{model} & \textbf{Bleu-3} & \textbf{Bleu-4} & \textbf{Nist-3} & \textbf{Nist-4} & \textbf{Rouge-1} & \textbf{Rouge-2} & \textbf{Rouge-L} & \textbf{meteor} & \textbf{PPL} & \textbf{Ent-4} \\ \hline \hline Ours & 0.0644 & 0.0331 & 2.2573 & 2.2661 & 0.2592 & 0.0601 & 0.2340 & 0.1091 & 25.98 & 10.8173 \\ \hline w/o post node & 0.0595 & 0.0305 & 2.1316 & 2.1402 & 0.2487 & 0.0562 & 0.2237 & 0.1044 & 27.00 & 10.7731 \\ w/o edge mask & 0.0573 & 0.0290 & 2.0694 & 2.0771 & 0.2442 & 0.0538 & 0.2201 & 0.1025 & 26.81 & 10.6822 \\ w/o edge emb & 0.0589 & 0.0295 & 2.1394 & 2.1472 & 0.2485 & 0.0547 & 0.2246 & 0.1050 & 26.46 & 10.6871 \\ \hline \end{tabular} \caption{Automation results of ablation models. All ablation models get lower scores than the complete model.} \label{tab:ablation} \end{table*} \begin{table*}[ht] \small \centering \begin{tabular}{c|l} \hline \textbf{\#1 post} & \begin{tabular}[c]{@{}l@{}}I \textcolor{blue}{drove} \textcolor{blue}{home} last \textcolor{blue}{night} , saw my \textcolor{blue}{dad} for the first \textcolor{blue}{time} in 6th \textcolor{blue}{months} , and \textcolor{blue}{slept} all \textcolor{blue}{day} \textcolor{blue}{today} . \\ \textcolor{blue}{Woke} up and \textcolor{blue}{poured} myself a \textcolor{blue}{rum} and \textcolor{blue}{coke} then\textcolor{blue}{started} \textcolor{blue}{watching} \textcolor{blue}{archer} . \textcolor{blue}{Today} was a good day .\end{tabular} \\ \hline DialoGPT & I 'm glad you had a good day. \\ ConcpetFlow & I 'm going to the same \textcolor{blue}{day} . Have a good \textcolor{blue}{night} , \textcolor{blue}{man} . \\ Ours & I 'm going to \textcolor{blue}{watch} the first \textcolor{magenta}{episode} of \textcolor{blue}{archer} and see if i can get a chance to \textcolor{blue}{sleep} . \\ \hline \textbf{\#2 post} & \begin{tabular}[c]{@{}l@{}}What do you mean ? From the \textcolor{blue}{alpha} or from the \textcolor{blue}{beta} ? His \textcolor{blue}{uav} was nerfed like \textcolor{blue}{crazy} in the \textcolor{blue}{beta} , \\ not being able to ping or \textcolor{blue}{find} a \textcolor{blue}{monster} if they 're \textcolor{blue}{sneaking} at all .\end{tabular} \\ \hline DialoGPT & I mean from the alpha . I'm not sure if it was nerfed in the beta, but i'm pretty sure it was. \\ ConcpetFlow & You can see the \textcolor{blue}{alpha} of the \textcolor{blue}{alpha} , but it 's a \textcolor{blue}{bug} . \\ Ours & You can see the \textcolor{magenta}{source} on the \textcolor{magenta}{server} . I think he was just a \textcolor{blue}{bug} . \\ \hline \end{tabular} \caption{Two cases on the testset. We present responses generated by different models. We mark concepts in the original ConceptNet in \textcolor{blue}{blue} and concepts introduced by the enhanced graph in \textcolor{magenta}{magenta}.} \label{tab:case} \end{table*} \textbf{Quality evaluation of the extracted edges.} We conduct a human evaluation to verify the quality of the extracted edges. Specifically, we sample 100 extracted edges, and four human annotators are required to judge whether the target concept is relevant to the source concept. On average, 68 concept relations are marked as relevant edges. And there are 47 edges that all four annotators think relevant. We list some of these high-quality edges in Figure \ref{fig4} and classify them into three categories roughly. The first type corresponds a pair of things that have a realistic relationship, such as \textcolor{blue}{``nurse''} works for \textcolor{magenta}{``hospital''}. The second type corresponds a pair of things in the same kind, such as both \textcolor{blue}{``ps4''} and \textcolor{magenta}{``pc''} are electronic devices. The third type corresponds a pairs of concepts with POS relationship, such as \textcolor{magenta}{``perception''} is the noun form of \textcolor{blue}{``perceptive''}. These three categories are consistent with human common sense, proving our method could get various knowledge information from the real conversation corpora. \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{edges_3.png} \caption{Several examples of high-quality concept relations we extracted from the conversation corpora. We classify them into three categories.} \label{fig4} \end{figure} \subsection{Analysis of the Edge-Transformer Architecture} In this part, we conduct a series of experiments to study the effectiveness of our proposed Edge-Transformer architecture. \textbf{The Edge-Transformer VS the GRAFT-Net.} From evaluation results in Table \ref{tab:control}, we could see that with the same graph, models with the Edge-Transformer achieve higher scores on all metrics than models with the GRAFT-Net. The results demonstrate the Edge-Transformer could encode graphs better. We also compare the parameters and training time of two architectures, which results are shown in Table \ref{tab:computation}. Obviously, our architecture contains fewer parameters with high training speed. The above two comparison shows the Edge-Transformer gets better performances than the GRAFT-Net while costing fewer computation resources. \begin{table}[ht] \small \centering \begin{tabular}{c|c|c} \hline \textbf{words num} & \textbf{concepts in $G_e$} & \textbf{concepts in $G$} \\ \hline 19.1056 & 2.2001 & 2.0593 \\ \hline \end{tabular} \caption{Concepts num in the generated responses.} \label{tab:response_nodes} \end{table} \textbf{Ablation study of the Edge-Transformer Architecture.} We propose three improvements on vanilla Transformer architecture and build the Edge-Transformer architecture. To study the effectiveness of three improvements, respectively, we build corresponding ablation models, as follows: \begin{itemize} \item \textbf{w/o post node.} We remove the special node $X'$, and there is no interaction between the post $X$ and the subgraph $g$. \item \textbf{w/o edge mask.} We remove the edge mask, and the architecture is the vanilla Transformer. \item \textbf{w/o edge embed.} We remove the edge embedding in the architecture, and the edge type information is not introduced. \end{itemize} The evaluation results of these three ablation models are shown in Table \ref{tab:ablation}. All ablation models get lower scores than the complete model on all metrics. The architecture without edge mask gets the lowest scores, indicating graph structure information in the knowledge graph is vital for the response generation and the vanilla Transformer architecture could not encode graph structures well. The results also prove the necessity of interaction between the post and the subgraph, and the importance of the edge type information. \subsection{Case Study} To further study the improvement our method brings, we present two cases in Table \ref{tab:case}. In case 1, DialoGPT and ConcpetFlow generate proper responses, but their responses are not as informative as ours. We could see that our response contains concept ``\textcolor{magenta}{episode}'' from $G_e$, demonstrating that $G_e$ could bring new concepts to the generated responses. In case 2, it seems that DialoGPT and ConceptFlow don't understand the post and give wrong responses. While our method gives high-quality response that contains concepts ``\textcolor{magenta}{source}'', ``\textcolor{magenta}{server}'' and ``\textcolor{blue}{bug}'', which are relevant to the post. Besides, we statistic the concepts in the generated responses on the testset, which is shown in Table \ref{tab:response_nodes}. In generated response, there are 2.2 words in the enhanced graph $G_e$ on average. Compared to the ConceptNet, the enhanced graph indeed introduces new concepts into the responses. The results prove the effectiveness of our method further. \section{Conclusion} Because of the gap between the concept relations in the natural conversation and those in the external commonsense knowledge graph, exploiting the knowledge information in the external knowledge graph is not sufficient to guide topic flows in the response generation. We extract conversation knowledge information from the conversation corpus to enhance the ConceptNet. To improve the knowledge-based response generation, we reconstruct an enhanced graph and design a novel architecture named Edge-Transformer to encode the enhanced graph. Plenty of experiments on the Reddit dataset show our method outperforms other strong baselines, achieving new SOTA results.
{'timestamp': '2021-09-15T02:12:10', 'yymm': '2109', 'arxiv_id': '2109.05406', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05406'}
arxiv
\section{Introduction} Since the release of WikiSQL~\cite{DBLP:journals/corr/abs-1709-00103}, a large-scale text-to-SQL benchmark, single-table text-to-SQL task has become an active research area in recent years. The goal of the task is to transform natural language questions into Structured Query Language (SQL) to query a single table. Although the search space is limited to one table, the task still has a considerable number of application scenarios (e.g., query regional electricity prices or flight schedules). More importantly, it is the basis for more complex text-to-SQL tasks on multi-tables~\cite{DBLP:conf/emnlp/YuZYYWLMLYRZR18}. Therefore, the research on this area is of great significance. Relying on large-scale pre-trained language models~\cite{DBLP:conf/naacl/DevlinCLT19} and a multi-submodule framework, existing approaches~\cite{DBLP:journals/corr/abs-1908-08113,DBLP:journals/corr/abs-1902-01069,DBLP:journals/corr/abs-2008-04759} have made considerable progress on the single-table text-to-SQL task. However, few of them pay attention to the challenge of zero-shot tables whose \textit{schema} are not visible in the training set. Typically, in comparison with the visible tables, zero-shot tables are more challenging because they are not directly involved in training. Their schema cannot be perceived by the model, so that they may be noisy in the test. In fact, with the rapid expansion of business, zero-shot tables are becoming more and more common in realistic scenarios. Therefore, in order to make text-to-SQL land from laboratory to application, it is necessary to make the model learn to handle zero-shot tables. \cite{DBLP:conf/aaai/ChangLT0HZ20} explicitly deals with zero-shot tables for the first time. The core idea of their approach is to design an auxiliary task to model the mapping from the question to the headers (similar to entity linking). However, this approach requires training data to provide the gold mappings that are annotated manually. Undoubtedly, it is a strong limitation in realistic scenarios. \begin{figure} \includegraphics[width=0.48\textwidth]{figure/example.pdf} \caption{An example of table content to help predict headers. Red indicates the matching.} \label{fig_example} \end{figure} In this paper, we propose a new approach called \textit{Meta-Content text-to-SQL} (MC-SQL) to handle zero-shot tables. The motivation comes from the following two intuitions: 1) The first one is that table content can provide abundant information for predicting headers. Figure \ref{fig_example} shows an example. The cell \textit{son} in the table is relevant to the question word ``son", thus reveals the potential header \textit{Relationship to Monarch}. 2) The second one is that meta-learning can help the model learn the generalization ability between different tables from the training data. It is because meta-learning has the capability that only needs a few gradient steps to quickly adapt to new tasks. Specifically, our approach consists of two parts. On the one hand, a table content-enhanced model is employed to encode questions, headers, and table cells at the same time, in order to combine their semantic relevance for the prediction on zero-shot tables. On the other hand, a zero-shot meta-learning algorithm is utilized to train our content-enhanced model instead of the traditional mini-batch strategy. In each training step, the algorithm generalizes the model by two sets of samples that rely on two disjoint table sets, respectively. Finally, to comprehensively evaluate our approach, we conduct experiments on public open-domain benchmark WikiSQL and domain-specific benchmark ESQL. Our approach achieves a significant improvement over the baselines that utilizes the same pre-trained model as ours, and also achieves competitive results over the baselines that utilize the larger or tabular-specific pre-trained model. \section{Preliminaries} The single-table text-to-SQL task can be formally defined as \begin{equation} y = \mathcal{M}(q, \mathcal{T}) \label{eq_task} \end{equation} where $q$ denotes a natural language question and $y$ denotes the corresponding SQL query. $\mathcal{T}=\{h^1,h^2,...,h^l\}$ denotes the table which $q$ relies on, where $h^i$ denotes the $i$-th header in $\mathcal{T}$. The goal of the task is to learn a mapping $\mathcal{M}$ from questions to SQL queries. In addition, this task supposes that no complex SQL syntax (e.g., GROUP BY and nested query) exists and there is only one column in the SELECT clause. Specifically, each $y$ follows a unified skeleton, which is shown in Figure \ref{fig_skeleton}. The tokens prefixed with ``\$" indicate the slots to be filled and ``*" indicates zero or more AND clauses. According to the skeleton, existing approaches~\cite{DBLP:journals/corr/abs-1908-08113,DBLP:journals/corr/abs-1902-01069,DBLP:journals/corr/abs-2008-04759} break the total task into the following six subtasks: \begin{figure} \includegraphics[width=0.48\textwidth]{figure/skeleton.pdf} \caption{Skeleton of SQL in single-table text-to-SQL.} \label{fig_skeleton} \end{figure} \begin{itemize} \item \textbf{Select-Column(SC)} finds the column \$SEL in the SELECT clause from $\mathcal{T}$. \item \textbf{Select-Aggregation(SA)} finds the aggregation function \$AGG ($\in $ \{NONE, MAX, MIN, COUNT, SUM, AVG\}) of the column in the SELECT clause. \item \textbf{Where-Number(WN)} finds the number of where conditions, denoted by $\mathcal{N}$. \item \textbf{Where-Column(WC)} finds the column (header) \$COL of each WHERE condition from $\mathcal{T}$. \item \textbf{Where-Operator(WO)} finds the operator \$OP ($\in \{=,>,<\}$) of each \$COL in the WHERE clause. \item \textbf{Where-Value(WV)} finds the value \$VAL for each condition from the question, specifically, locating the starting position of the value in $q$. \end{itemize} There are dependencies between some tasks. For example, the prediction of \$OP requires \$COL, and the prediction of \$VAL requires both \$COL and \$OP. \begin{figure} \includegraphics[width=0.48\textwidth]{figure/overview.pdf} \caption{Overall framework of our approach.} \label{fig_overview} \end{figure} \begin{figure*} \includegraphics[width=\textwidth]{figure/model.pdf} \caption{Architecture of the table content-enhanced model. WN, WC, and WV are detailed in the orange, purple, and green dotted box, respectively. Blue indicates the processes for table content and gray indicates the processes for headers.} \label{fig_model} \end{figure*} \section{Approach} The framework of our approach is shown in Figure \ref{fig_overview}, which consists of two parts. First, the \textit{table content enhanced model} (left) captures the semantic relevance of questions with headers and cells at the same time, and predict subtasks comprehensively. Further, \textit{zero-shot meta-learning} (right) is leveraged to train the table content enhanced model. In each training batch, the model parameters are updated in two stages to force the model to learn the generalization ability. \subsection{Table Content Enhanced Model} Figure \ref{fig_example} demonstrates that the core of leveraging table content is to find the table cells mentioned in the question. However, the total number of the cells can be very large, far exceeding that of the headers. Consequently, it is impractical to directly embed all of them. To overcome this challenge, we adopt coarse-grained filtering before embedding. Specifically, for each header $h$, only the cell $c$ with the highest literal similarity to question $q$ will be retained. The literal similarity is computed by \begin{equation} {\rm \varphi}(c;q)=\max_{{\rm n}(q)} \frac{{\rm lcs}({\rm n}(q),c)}{2|{\rm n}(q)|}+\frac{{\rm lcs}({\rm n}(q),c)}{2|c|} \label{literal_similarity} \end{equation} where ${\rm n}(q)$ denotes the $n$-gram of $q$, $|x|$ denotes the length of string $x$, and ${\rm lcs}(x,y)$ denotes the length of the \textit{Longest Consecutive Common Subsequence} between the string $x$ and $y$. The intuitive meaning of ${\rm \varphi}(c;q) \in [0, 1]$ is that the larger proportion of the overlap in the two strings, the higher the similarity of them. In addition, if the retained cell whose score is smaller than the threshold $\sigma$, it will be replaced with a special token \#None\#, in order to avoid noise. After filtering, each header has a corresponding cell (or \#None\#). The overall architecture of our table content-enhanced model is shown in Figure \ref{fig_model}. It consists of an encoding module and six sub-modules corresponding to six sub-tasks. Intuitively, table content is mainly helpful to the sub-tasks for the WHERE clause, especially WN, WC, and WV. Therefore, we will detail these three sub-modules that utilize table content. \subsubsection{Encoding Module} The encoding module consists of BERT~\cite{DBLP:conf/naacl/DevlinCLT19} and an embedding layer. BERT is employed to encode the question and the headers. Following the format of BERT, the input is a sequence of tokens, which starts with a special token \texttt{[CLS]} followed by the word tokens of question $q$ and all headers $\{h^i\}$. A special token \texttt{[SEP]} is utilized to separate the $q$ and each $h^i$. For each input token, BERT outputs a hidden vector that holds its context information. In addition to BERT, the embedding layer is utilized to embed the cells. Differing from BERT, the embedding is for characters rather than words. It is because cells are typically some entity names and numerical values, etc. Char-embedding can reduce the number of Out-Of-Vocabulary (OOV) tokens. Specifically, For each cell $c$, its character embedding is denoted by $E_c \in \mathbf{R}^{m \times d_e}$, where $m$ is the character number of $c$ and $d_e$ is the dimension of each embedding. Since $q$ and $c$ should be embedded in the same vector space for calculating their semantic relevance, we also embed $q$ instead of directly using the BERT output of $q$. The char-embedding of $q$ is denoted by $E_q \in \mathbf{R}^{n \times d_e}$. \subsubsection{Where-Number Sub-Module} This sub-module contains two similar processes, which calculate the header-aware and content-aware context vector of the question, respectively. Here detail the process of the latter. First, for each $h$, its content vector $\bm{\tau}_h \in \mathbf{R}^{d}$ is obtained by a BiLSTM on $E_c$ followed by a max-pooling operation ($\mathbf{R}^{m \times d} \to \mathbf{R}^{d}$). Then, the hidden vectors of $q$ is obtained by the other BiLSTM, denoted by $\Gamma_q \in \mathbf{R}^{n \times d}$. In order to make this BiLSTM aware of $c$ when encoding $q$, its initial states $\bm{s} \in \mathbf{R}^{2d}$ is obtained by performing a self-attention on all $\bm{\tau}_h$. \begin{equation} \alpha_h = {\rm softmax}(\bm{\tau}_h W_{\alpha}) \end{equation} \begin{equation} \bm{s} = W_s \sum_{h \in H}^n \alpha_h \bm{\tau}_h \end{equation} Here, $\alpha_h \in \mathbf{R}$ is the attention weight of each header $h$. $W_{\alpha} \in \mathbf{R}^{d \times d}$ and $W_{s} \in \mathbf{R}^{d \times 2d}$ are the trainable parameter matrices. Thereafter, the content-aware question context $\bm{\mu}_q \in \mathbf{R}^d$ is calculated by a self-attention on $\Gamma_q$, which is similar to $\bm{\mu}_h$. As described at the beginning, the header-aware question context $\widehat{\bm{\mu}}_q \in \mathbf{R}^d$ is calculated by the same procedures above on the output of BERT\footnote{In order to distinguish easily, all the vectors obtained from the output of BERT are marked with a hat, such as $\widehat{x}$.}. Finally, the result $\mathcal{N}$ is predicted by combining the header- and content-aware context vectors. \begin{equation} \mathcal{N} = \arg \max_{i} \tanh([\widehat{\bm{\mu}}_q;\bm{\mu}_q] W_{\mu} ) W_o \label{eq_wn} \end{equation} where $W_{\mu} \in \mathbf{R}^{2d \times d}$ and $W_o \in \mathbf{R}^{d \times 1}$ are the trainable parameter matrices. \subsubsection{Where-Column Sub-Module} In this sub-module, the processes of calculating question hidden vectors $\Gamma_q$ and content vectors $\bm{\tau}_h$ are similar to those in WN. The only difference is the initial states of all the BiLSTMs are all random. Thereafter, in order to make the model focus on the parts of $q$ that are relevant to $c$, an attention mechanism is performed on $\Gamma_q$ to calculate content-aware context vector $\bm{\mu}^h_q \in \mathbf{R}^d$. \begin{equation} \bm{\mu}^h_q = \sum_{i=1}^n \alpha^i_q \bm{\gamma}^i_q \end{equation} \begin{equation} \alpha_q^i = {\rm softmax}(\bm{\gamma}^i_q W_{\alpha} {\bm{\tau}_h}^T) \end{equation} where $\bm{\gamma}^i_q \in \mathbf{R}^{d}$ is the $i$-th hidden vector in $\Gamma_q$ and $\alpha_q^i \in \mathbf{R}$ is its attention weight. $W_{\alpha} \in \mathbf{R}^{d \times d}$ is the parameter matrix. Finally, the result \$COL is predicted by \begin{equation} {\rm \$COL} = \arg \max_{h \in \mathcal{T}} \tanh([\widehat{\bm{\mu}}_q^h; \widehat{\bm{\tau}}_h; \bm{\mu}_q^h; \bm{\tau}_h]) W_o \end{equation} where $\widehat{\bm{\tau}}_h$ and $\widehat{\bm{\mu}}_q^h$ are the header vector and header-aware context vector, respectively. They are obtained by decoding the output of BERT with the same steps towards $\bm{\mu}_q^h$ and $\bm{\tau}_h$. \subsubsection{Where-Value Sub-Module} The architecture of this sub-module is almost consistent with that of WC. The difference is that prediction of \$VAL also requires the results of WC and WV, namely \$COL and \$OP. Let $h$ denote \$COL and $op$ denote \$OP, then the starting position $st$ and ending position $ed$ of \$VAL can be calculated by \begin{equation} st = \arg \max_{w^i \in q} \tanh([\widehat{\bm{\mu}}_q^h; \widehat{\bm{\tau}}_h; \bm{\mu}_q^h; \bm{\tau}_h; \bm{\eta}_{op}; \bm{\xi}_q^i]) W_{st} \end{equation} \begin{equation} ed = \arg \max_{w^i \in q} \tanh([\widehat{\bm{\mu}}_q^h; \widehat{\bm{\tau}}_h; \bm{\mu}_q^h; \bm{\tau}_h; \bm{\eta}_{op}; \bm{\xi}_q^i]) W_{ed} \end{equation} Where $w^i$ is the $i$-th word token of $q$. $\widehat{\bm{\mu}}_q^h$, $\widehat{\bm{\tau}}_h$, $\bm{\mu}_q^h$, and $\bm{\tau}_h$ are calculated by the same procedures used in WC. $\bm{\eta}_{op}$ is the one-hot vector of \$OP and $\bm{\xi}_q^i$ is the semantic vector of $w^i$. Here, in order to leverage the content more directly, we propose a Value Linking(VL) strategy for calculating $\bm{\xi}_q^i$. \begin{equation} \bm{\xi}_q^i = [\widehat{\bm{\tau}}_q^i; \bm{t}_q^i] \label{eq_vl} \end{equation} where $\widehat{\bm{\tau}}_q^i \in \mathbf{R}^{d}$ is the hidden vector of $w^i$. It is calculated by a BiLSTM encoding the $q$ output of BERT. $\bm{t}_q^i \in \mathbf{R}^{d_{t}}$ denotes the type embedding of $w^i$. There are only two types, denoted by \texttt{Match} and \texttt{NotMatch}, that indicate whether $w^i$ matches some cells $c$, respectively. Initially, the type of each $w^i$ is labeled as \texttt{NotMatch}. When calculating the literal similarity by (\ref{literal_similarity}), if a cell $c$ is select, all the words of the corresponding n-gram $n(q)$ will be labeled as \texttt{Match}. The architectures of the remaining three modules SC, SA, and WO are almost consistent with WC, except that they do not need the process for table content (i.e., removing the blue process in Figure \ref{fig_model}). All their results are predicted by the classification that depends on the combined context $[\widehat{\bm{\tau}}_h; \widehat{\bm{\mu}}_q^h]$. \subsection{Zero-Shot Meta Learning Framework} Meta-learning is typically leveraged to deal with classification problems and has the ability to adapt quickly between different categories. In our proposed framework, the table that each sample (question) relies on is regarded as an abstract category, in order to create the conditions for applying meta-learning. Furthermore, the traditional meta-learning framework consists of two stages of meta-training and meta-test. However, it is already demonstrated in \cite{DBLP:conf/nips/VinyalsBLKW16,DBLP:conf/nips/SnellSZ17} where without fine-tuning on the meta-test, the meta-learning model shows similar even better performance. Motivated by this, our meta-learning algorithm only retains the meta-training stage. The entire process is formally described in Algorithm \ref{alg_meta_learning}. \begin{algorithm} \caption{Zero-Shot Meta-Learning Framework} \begin{algorithmic}[1] \label{alg_meta_learning} \REQUIRE A set of training samples $\mathcal{D}=\{(q^i, \mathcal{T}^i, y^i)\}$, where $q^i$ is the $i$-th input question, $t^i$ is the table which $q^i$ relies on, and $y^i$ is the gold SQL query of $q^i$. A model $\mathcal{M}(q,\theta)$, where $\theta$ is its parameters. Hyperparameters $\alpha$, $\beta$ and $\gamma$ \WHILE{not done} \FORALL{task} \STATE Sample a support set $\mathcal{S} = \{(q^j, \mathcal{T}^j, y^j)\} \subseteq \mathcal{D}$ \STATE Evaluate $\nabla_{\theta}\mathcal{L}_{\mathcal{S}} = \nabla_{\theta}\Sigma_{j}\mathcal{L}(\mathcal{M}(q^j,\mathcal{T}^j,\theta), y^j)$ \STATE Update parameters with gradient descent: \\$\phi = \theta - \alpha \nabla_{\theta}\mathcal{L}_{\mathcal{S}}$ \STATE Sample a query set $\mathcal{Q} = \{(q^k, \mathcal{T}^k, y^k)\} \subseteq \mathcal{D}$, where $\{\mathcal{T}^j\} \cap \{\mathcal{T}^k\} = \emptyset$ \STATE Evaluate $\nabla_{\theta}\mathcal{L}_{\mathcal{S} \gets \mathcal{Q}} = \nabla_{\theta}\Sigma_{k}\mathcal{L}(\mathcal{M}(q^k,\mathcal{T}^k,\phi), y^k)$ \STATE Update $\theta$ to minimum $\mathcal{L}$ using Adam optimizer with learning rate $\beta$, \\ where $\mathcal{L} = \gamma\mathcal{L}_{\mathcal{S}} + (1-\gamma)\mathcal{L}_{\mathcal{S} \gets \mathcal{Q}}$ \ENDFOR \ENDWHILE \end{algorithmic} \end{algorithm} A task consists of several training samples. It is the basic training unit of our framework and split into a support set and a query set. Here, to simulate the scenario of zero-shot tables, the table set of the support set is disjoint with that of the query set. According to the split, the model experienced a two-stage gradient update during the training of each task. In the first stage, temporary parameters $\phi$ are obtained by calculating the loss of the support set $\mathcal{S}$ and perform the gradient updating on original parameters $\theta$. In the second stage, the loss of the query set $\mathcal{Q}$ is first calculated with $\phi$. Then, the losses of the support set and query set are jointed to calculate the gradient. Finally, original parameters $\theta$ are updated by the gradient. In addition, for sampling $\mathcal{S}$ and $\mathcal{Q}$, we follow the $N$-way $K$-shot setting, i.e, each set covers $N$ tables and there are $K$ samples for each table. Although meta-learning has also been utilized in \cite{DBLP:conf/naacl/HuangWSYH18} on text-to-SQL, there are two key differences between our proposed approach and their method: First, \cite{DBLP:conf/naacl/HuangWSYH18} focuses on sampling support sets according to types of the questions (e.g., COUNT, MIN), but we sample according to different tables, so as to capture the potential relationship between questions and tables. Second, we ensure that the tables in the support set do not intersect with those in the query set to simulate a zero-shot environment. Following this setting, the model needs to learn the generic knowledge between two different sets of tables and perform a joint optimization, thus it can be forced to learn the generalization ability. \section{Experiments} \subsection{Experimental Setup} Our models are trained and evaluated over the following two text-to-SQL benchmarks: \textbf{WikiSQL}~\cite{DBLP:journals/corr/abs-1709-00103} is an English open-domain text-to-SQL benchmark, containing more than 20K tables. Each question corresponds to a table, which is extracted from the Wikipedia page. The data set is divided into 56,355 training questions, 8,421 development questions, and 15,878 test questions\footnote{https://github.com/salesforce/WikiSQL}. In order to focus on evaluating the performance on zero-shot tables, we conduct experiments on the remaining 30\% of tables (zero-shot subset) released by \cite{DBLP:conf/aaai/ChangLT0HZ20}\footnote{https://github.com/JD-AI-Research-Silicon-Valley/auxiliary-task-for-text-to-sql}. \textbf{ESQL} is a Chinese domain-specific text-to-SQL dataset built by ourself. Its format imitates WikiSQL, containing 17 tables. These tables are related to the field of electric energy, including information such as electricity sales and prices\footnote{Due to commercial secrets, we first desensitize the original dataset and then release it and all the codes of MC-SQL on https://github.com/qjay612/meta\_learning\_NL2SQL, and all the results in this paper are obtained from the desensitized version.}, etc. Although the number of tables in ESQL is small, the number of headers in each table is several times that in a WikiSQL table, thus still covers a wealth of information. The dataset is divided into 10,000 training questions, 1,000 development questions, and 2,000 test questions. In order to simulate the challenge of zero-shot tables, the training set contains only 10 tables of all, while the development set and the test set contain all the tables. We respectively extract the questions from the development and test set that rely on the remaining 7 tables as the zero-shot subsets. Following previous approaches~\cite{DBLP:journals/corr/abs-1709-00103,DBLP:journals/corr/abs-1902-01069}, we adopt logical form (LF) accuracy and execution (EX) accuracy as the evaluation metrics. Here, LF evaluates the literal accuracy of the total SQL query and its clauses, and EX evaluates the accuracy of the results by executing the SQL query. \subsubsection{Implementation Details} We perform all the experiments on NVIDIA Tesla V100 GPU. In the experiments, all the BERT models are of \textit{base} version. The following hyperparameters are tuned on development sets: (1) Fitlering threshold $\sigma$ is set to 0.9 for both datasets. (2) The layer number of all BiLSTMs is set to 2. (3) The hidden state size $d$ is set to 100. (4) The character embedding size $d_e$ is set to 128. (5) The type embedding size $d_t$ is set to 32. (6) The number of sampling tasks is set to 10,000 for WikiSQL, 2,500 for ESQL. (7) For WikiSQL, both $N$ and $K$ in the $N$-way $K$-shot setting are set to 4. For ESQL, they are set to 1 and 4, respectively. (8) $\gamma$ in Algorithm \ref{alg_meta_learning} is set to 0.3 for WikiSQL, 0.5 for ESQL. (9) For $\alpha$ in Algorithm \ref{alg_meta_learning}, BERT and sub-modules are trained with two kinds respectively. Specifically, $\alpha_{\rm BERT}$ is set to $1 \times 10^{-5}$ and $\alpha_{\rm sub}$ is set to $1 \times 10^{-3}$. Similarly, $\beta_{\rm BERT}$ is set to $1 \times 10^{-5}$ and $\beta_{\rm sub}$ is set to $1 \times 10^{-3}$. \subsection{Overall Results on WikiSQL} \begin{table} \begin{center} \scalebox{0.9}{ \begin{tabular}{ccccc} \hline \rule{0pt}{12pt} Approach & Dev LF & Dev EX & Test LF & Test EX \\ \hline \\[-6pt] Seq2SQL & 49.5 & 60.8 & 48.3 & 59.4 \\ Coarse2Fine & 72.5 & 79.0 & 71.7 & 78.5\\ Auxiliary Mapping & 76.0 & 82.3 & 75.0 & 81.7 \\ SQLova (-)& 80.3 & 85.8 & 79.4 & 85.2 \\ SQLova (*) & 81.6 & 87.2 & 80.7 & 86.2 \\ X-SQL (*) & 83.8 & 89.5 & 83.3 & 88.7 \\ HydratNet (*) & 83.6 & 89.1 & \textbf{83.8} & 89.2 \\ TaBERT-k1 (-) & 83.1 & 88.9 & 83.1 & 88.4 \\ TaBERT-k3 (-) & 84.0 & 89.6 & 83.7 & 89.1 \\ \hline \\[-6pt] MC-SQL (-) & \textbf{84.1} & \textbf{89.7} & 83.7 & \textbf{89.4} \\ \hline \\[-6pt] \end{tabular}} {\caption{Overall results on WikiSQL. ``x(-)" denotes the model x with BERT-base. ``x(*)" denotes the model x with BERT-large or larger pre-trained model, such as MT-DNN~\cite{DBLP:conf/acl/LiuHCG19} in X-SQL. k1 and k3 indicate that the model considers 1 and 3 rows of related content for one question, respectively. }\label{tab_overall_wiksql}} \end{center} \end{table} \begin{table*} \begin{center} \scalebox{0.9}{ \begin{tabular}{clccccccc} \hline \rule{0pt}{12pt} Dataset &Model &SC &SA &WN &WC &WO &WV &LF \\ \hline \\[-6pt] \multirow{7}{*}{WikiSQL} &SQLova &96.7 / 96.3 &90.1 / 90.3 &98.4 / 98.2 &94.1 / 93.6 &97.1 / 96.8 &94.8 / 94.3 &80.2 / 79.7\\ &TaBERT-k1 &97.2 / \textbf{97.1} &90.5 / 90.6 &98.9 / 98.8 &96.1 / 96.1 &\textbf{97.9} / \textbf{97.8} &\textbf{96.7} / 96.6 &83.1 / 83.1\\ &TaBERT-k3 &\textbf{97.3} / \textbf{97.1} &\textbf{91.1} / \textbf{91.2} &98.8 / 98.7 &96.6 / 96.4 &97.5 / 97.5 &96.6 / 96.2 &83.9 / \textbf{83.7}\\ &MC-SQL &96.9 / 96.4 &90.5 / 90.6 &\textbf{99.1} / \textbf{98.8} &97.9 / \textbf{97.8} &97.5 / \textbf{97.8} &\textbf{96.7} / \textbf{96.9} &\textbf{84.1} / \textbf{83.7}\\ &\quad w/o TC &97.0 / 96.5 &89.8 / 90.0 &98.6 / 98.3 &94.5 / 93.7 &97.2 / 97.0 &94.7 / 94.7 &79.9 / 79.2\\ &\quad w/o VL &97.0 / 96.7 &90.4 / \textbf{90.8} &99.0 / 98.7 &\textbf{98.0} / 97.6 &97.5 / 97.2 &95.6 / 95.5 &82.9 / 83.0\\ &\quad w/o ML &96.5 / 96.2 &90.4 / 90.4 &98.9 / 98.7 &97.8 / 97.4 &97.5 / 97.4 &96.5 / 96.1 &83.2 / 82.9\\ \\[-10pt] \hline \\[-6pt] \multirow{5}{*}{ESQL} &SQLova &96.2 / 95.9 &98.9 / 99.0 &98.5 / 98.4 &84.6 / 84.1 &96.5 / 95.8 &89.9 / 89.6 &72.0 / 71.5\\ &MC-SQL &\textbf{97.2} / \textbf{97.3} &99.1 / \textbf{99.2} &\textbf{98.9} / \textbf{98.9} &\textbf{93.6} / 93.3 &\textbf{97.5} / 96.8 &\textbf{92.9} / \textbf{92.6} &\textbf{82.8} / \textbf{82.7}\\ &\quad w/o TC &95.9 / 96.1 &99.2 / 99.1 &98.8 / 98.3 &84.5 / 84.4 &96.7 / 96.2 &90.5 / 90.3 &72.9 / 72.1\\ &\quad w/o VL &96.5 / 96.7 &\textbf{99.3} / 98.9 &\textbf{98.9} / 98.8 &93.5 / \textbf{93.5} &97.4 / \textbf{96.9} &92.0 / 91.8 &82.1 / 81.9\\ &\quad w/o ML &96.2 / 96.0 &98.8 / 98.9 &\textbf{98.9} / 98.8 &92.4 / 92.7 &\textbf{97.5} / 96.7 &92.7 / 92.3 &82.3 / 81.9\\ \\[-10pt] \hline \\[-6pt] \multirow{7}{*}{\tabincell{c}{WikiSQL\\(zero-shot)}} &SQLova &95.8 / 95.2 &89.7 / 89.3 &97.6 / 97.4 &91.1 / 90.4 &95.9 / 95.7 &90.1 / 90.5 &74.7 / 72.8\\ &TaBERT-k1 &96.6 / \textbf{96.4} &91.0 / 91.0 &98.6 / \textbf{98.4} &94.8 / 94.6 &\textbf{97.7} / \textbf{97.5} &\textbf{95.3} / \textbf{94.6} &81.3 / 80.5\\ &TaBERT-k3 &\textbf{96.7} / \textbf{96.4} &\textbf{91.6} / \textbf{91.5} &98.2 / 98.2 &95.1 / 95.0 &96.8 / 97.0 &94.9 / 94.2 &82.0 / \textbf{81.2}\\ &MC-SQL &\textbf{96.4} / 95.5 &91.1 / 91.0 &\textbf{98.7} / 98.1 &96.6 / \textbf{96.3} &97.1 / 96.7 &94.8 / 94.2 &\textbf{82.4} / 80.5 \\ &\quad w/o TC &96.2 / \textbf{95.7} &91.0 / 90.5 &97.6 / 97.7 &91.5 / 90.7 &96.2 / 96.1 &90.5 / 90.8 &75.8 / 73.6\\ &\quad w/o VL &96.2 / 95.8 &90.6 / 90.9 &\textbf{98.7} / 98.0 &\textbf{97.1} / \textbf{96.3} &97.1 / 96.3 &91.7 / 92.1 &79.0 / 79.1\\ &\quad w/o ML &95.7 / 95.0 &90.4 / 90.2 &98.5 / 98.2 &96.0 / 95.8 &96.8 / 96.7 &94.0 / 93.5 &81.2 / 79.4\\ \\[-10pt] \hline \\[-6pt] \multirow{5}{*}{\tabincell{c}{ESQL\\(zero-shot)}} &SQLova &94.3 / 94.0 &97.8 / 97.9 &97.3 / 97.0 &80.5 / 80.7 &95.9 / 94.6 &87.8 / 86.7 &62.9 / 61.2\\ &MC-SQL &\textbf{94.6} / \textbf{94.2} &98.0 / 98.0 &\textbf{97.5} / \textbf{97.3} &\textbf{93.7} / \textbf{92.0} &\textbf{96.2} / \textbf{94.8} &\textbf{91.9} / \textbf{90.5} &\textbf{76.7} / \textbf{74.8}\\ &\quad w/o TC &94.4 / 94.1 &\textbf{98.1} / \textbf{98.2} &97.1 / 97.2 &80.7 / 80.6 &95.5 / 94.2 &88.4 / 87.6 &64.7 / 63.3\\ &\quad w/o VL &93.8 / 94.0 &98.0 / 98.1 &97.4 / 97.2 &92.6 / 91.1 &95.1 / \textbf{94.8} &90.9 / 90.1 &75.7 / 73.7\\ &\quad w/o ML &93.5 / 93.0 &97.7 / 97.9 &97.4 / 96.9 &93.2 / 91.8 &96.0 / 94.3 &91.2 / 90.2 &75.2 / 72.9\\ \\[-10pt] \hline \end{tabular}} {\caption{Results of sub-tasks on WikiSQL and ESQL. $x$/$y$ denotes the results of the dev/test sets.}\label{tab_submodule}} \end{center} \end{table*} We first compared our approach with several existing text-to-SQL approaches on public benchmark WikiSQL. Seq2SQL~\cite{DBLP:journals/corr/abs-1709-00103}, Coarse2Fine~\cite{DBLP:conf/acl/LapataD18}, and Auxiliary Mapping~\cite{DBLP:conf/aaai/ChangLT0HZ20} are all sequence-to-sequence (Seq2Seq) based models. SQLova~\cite{DBLP:journals/corr/abs-1902-01069} replaces the Seq2Seq framework with the multi-submodule framework. X-SQL~\cite{DBLP:journals/corr/abs-1908-08113} and HydratNet~\cite{DBLP:journals/corr/abs-2008-04759} improve this framework by MT-DNN~\cite{DBLP:conf/acl/LiuHCG19} and a pair-wise ranking mechanism respectively, thus achieve better results. TaBERT~\cite{DBLP:conf/acl/YinNYR20} is a state-of-the-art language model used to encode tabular data. It is pre-trained on a massive number of question-tabular corpus and also uses content information. In this paper, we ignore all the results with execution guiding (EG) trick~\cite{DBLP:journals/corr/abs-1807-03100}. It is because EG works on the premise that the generated SQL query must not be empty, which is unreasonable in realistic scenarios. The overall experimental results on WikiSQL are reported in Table \ref{tab_overall_wiksql}. Except for TaBERT, where we use official API, all the other comparison results are directly taken from the original paper. On LF accuracy, our approach achieves state-of-the-art results on the development set and ranks second only to HydratNet (-0.1\%) on the test set. On EX accuracy, our approach achieves state-of-the-art results on both the sets. Notably, our results are achieved by only utilizing the \textit{base} version of BERT. After ignoring the baselines that use larger pre-trained models (``(*)" in Table \ref{tab_overall_wiksql}), our approach achieves significant improvements on both LF (4.3\%) and EX (4.2\%) accuracy when testing. In addition, compared with the table-specific pre-trained model, our model still has advantages without pre-training on table corpus. The performance of Seq2SQL, Coarse2Fine, and Auxiliary Mapping is limited by the decoding without SQL syntax constraints. SQLova, X-SQL, and HydratNet ignore the abundant information from table content, thus their performance is also limited. TaBERT makes use of content information and performs tabular-specific pre-training, thus achieving better results. There are two possible reasons why our approach outperforms TaBERT. On the one hand, TaBERT uses table information coarsely (SELECT-clause actually does not require content information), while we provide a more fine-grained usage (only WHERE-clause). On the other hand, the mandatory meta-learning process gives the model a stronger generalization ability. \subsection{Detailed Analysis} \subsubsection{Ablation Test} To explore the contributions of various components of our MC-SQL model, we compared the following settings on both the datasets. \begin{itemize} \item \textbf{w/o table content(TC)} We removed all the processes in WN, WC, and WV that related to table content. For example, (\ref{eq_wn}) is converted to $p_{wn}(i | q, \mathcal{T}) = \tanh(\widehat{\bm{\mu}}_q W_{\mu} ) W_o$. \item \textbf{w/o value linking(VL)} We retained the processes related to TC but removed the value linking in WV, i.e., (\ref{eq_vl}) is converted to $\bm{\xi}_q^i = \widehat{\bm{\tau}}_q^i$ after removing. \item \textbf{w/o meta-learning(ML)} We replaced the meta-learning strategy with the traditional mini-batch strategy. \end{itemize} The detailed results on the full sets of WikiSQL and ESQL\footnote{The SQL query in ESQL also includes other keywords such as ORDER BY. We design modules similar to SELECT and WHERE above to solve them. The detailed results of these sub-tasks are available on the data set homepage.} are shown in the upper two blocks of Table \ref{tab_submodule}, respectively. MC-SQL equipped with all the components achieves the optimal results on LF accuracy and most sub-tasks, which significantly improves the baseline SQLova on both WikiSQL (4.0\%) and ESQL (10.2\%). Compared with TaBERT, our approach also has advantages on the overall performance on WikiSQL (0.2\% on Dev.) by the improvement on WC. This is probably due to the fine-grained use of content information for specific modules. By removing TC, the overall performance (LF) declined approximately 3.5\% and 10.6\% on both the datasets. It demonstrates the significance of content. Here, the performance drop by removing VL also proves the contribution of value linking. Removing ML brings a certain drop on both the datasets, however, the drop on ESQL (-1.8\%) is sharper than that on WikiSQL (-0.8\%). The reason can be that WikiSQL is an open-domain dataset, thus it is more difficult for generalization capability than domain-specific ESQL. By further observation, it can be found that the contribution of TC is mainly reflected in the four sub-tasks of WN, WC, and WV. The improvement on WO is mainly attributed to the improvement on WC, because the former depends on the result of the latter. In addition, meta-learning is helpful for all sub-tasks and has the most significant improvements on the sub-tasks that are not enhanced by table content, such as SC and SA. Interestingly, the performance sometimes becomes better on WC and WO after removing VL, which reveals that VL can be noisy for predicting \$COL. However, due to its significant improvement on WV, VL is still helpful for the overall performance. \subsubsection{Zero-shot Test} We evaluated our model on the zero-shot subsets of both the datasets. The results are shown in the bottom two blocks of Table \ref{tab_submodule}. In terms of overall results, MC-SQL achieves greater improvements over SQLova on the zero-shot subsets of both WikiSQL (7.7\% vs 4.0\%) and ESQL (13.6\% vs 10.2\%). It proves that our approach is promising for enhance the model to handle zero-shot tables. Furthermore, the improvement on each subtask is also increased, especially WC and WV. The contribution of table content is greater on zero-shot tables, which is consistent with our intuition. The relatively more drastic performance drop caused by removing ML also proves that our meta-learning strategy is suitable for dealing with zero-shot tables. Notably, in addition to SC and SA, meta-learning is also contributing to the WHERE clause when handling zero-shot tables. It is interesting that the performance on ESQL is generally lower than that on WikiSQL, whereas the improvement brought by meta-learning on ESQL is greater than that of WikiSQL. We speculate that it is because fewer training tables result in poor performance, and meta-learning, which has the characteristic of suitable for a few samples, achieves greater improvements. Compared to TaBERT, our approach leads on the zero-shot development set (0.4\%) but lags behind on the zero-shot test set (-0.7\%). Specifically, TaBERT works better on the two sub-tasks of SA and WO. It benefits from its joint pre-training with tabular data and problems, thereby learning a stronger mapping capability between aggregation operators and questions. \subsubsection{Varied Sizes of Training Data} \begin{figure} \includegraphics[width=0.45\textwidth]{figure/partial_wikisql.pdf} \caption{LF on WikiSQL with proportions of training data.} \label{fig_partial_wikisql} \end{figure} \begin{figure} \includegraphics[width=0.45\textwidth]{figure/partial_esql_new.pdf} \caption{LF on ESQL with proportions of training data.} \label{fig_partial_esql} \end{figure} To simulate the scenario of zero-shot tables from another aspect, we tested the performance of the model using different proportions of training data. The results of WikiSQL and ESQL are shown in Figure \ref{fig_partial_wikisql} and Figure \ref{fig_partial_esql}, respectively. The MC-SQL equipped with all components always maintains optimal performance with different sizes of training data. When the training data is small, the improvement achieved by MC-SQL over SQLova is more significant, especially on WikiSQL. In addition, the results on both datasets demonstrate that the less training data, the more significant the improvement brought by meta-learning. Note that changes in training data have less impact on ESQL than that on WikiSQL. It is probably because of the few tables and the specific domain of ESQL. \section{Related Work} In recent research, mainstream text-to-SQL approaches mainly include two directions. One direction is represented by Spider~\cite{DBLP:conf/emnlp/YuZYYWLMLYRZR18}, which is a benchmark to deal with the multi-table text-to-SQL task~\cite{DBLP:conf/naacl/YuLZZR18,DBLP:journals/corr/abs-1711-04436,DBLP:journals/corr/abs-1810-05237,DBLP:conf/acl/GuoZGXLLZ19,DBLP:conf/acl/WangSLPR20}. However, even if the evaluation does not require to recognize the value in WHERE clause, the state-of-the-art performance (65.6\% achieved by \cite{DBLP:conf/acl/WangSLPR20}) on this task is still far from realistic applications. The other direction is represented by WikiSQL~\cite{DBLP:journals/corr/abs-1709-00103}, which is a benchmark to deals with the single-table text-to-SQL task. This paper focuses on this task. Previous single-table text-to-SQL approaches~\cite{DBLP:journals/corr/abs-1709-00103,DBLP:journals/corr/abs-1711-04436,DBLP:conf/naacl/YuLZZR18,DBLP:conf/acl/LapataD18,DBLP:conf/aaai/ChangLT0HZ20} are mainly based on the Seq2Seq framework but ignore the characteristics of the SQL skeletons, thus their performance is limited. \cite{DBLP:journals/corr/abs-1902-01069} breaks the total task into several subtasks for the first time. They propose enables each sub-module to focus on the corresponding subtasks, thereby overcoming the bottleneck caused by a single model. In addition, the large-scale pre-trained language model~\cite{DBLP:conf/naacl/DevlinCLT19} also greatly improved model performance. Thereafter, almost all work on WikiSQL follows this framework of pre-trained models with multi-submodules. \cite{DBLP:journals/corr/abs-1908-08113} leverages the type information of table headers and replaces BERT with MT-DNN, which is a stronger pre-trained model trained from multi-task learning. \cite{DBLP:journals/corr/abs-2008-04759} proposes a pair-wise ranking mechanism for each question-header pair, and achieve better results on WikiSQL. The significant difference between our work and these approaches is that we take advantage of the content information. The closest work to ours is TABERT, which also encodes table content and utilizes a large number of question-table pairs for pre-training. However, their use of content lacks specificity, i.e., content-encoding is used for all subtasks. intuitively, the content information is helpful only for WHERE-clause predictions. Based on this intuition, our approach only uses content information on specific subtasks, thus it is more accurate. In addition, the use of meta-learning further promotes our model to obtain stronger generalization capabilities. More importantly, our approach can still play an important role in scenarios where lack of pre-trained models from massive tabular data (such as Chinese tables). \section{Conclusion} In this paper, we propose a new single-table text-to-SQL approach MC-SQL, which focuses on handling zero-shot tables. On the one hand, our approach takes advantage of table content to enhance the model. The potential header can be inferred by the semantic relevance of questions and content. On the other hand, our approach learns the generalization capability from different tables by meta-learning. It utilizes a two-stage gradient update to force the model to learn generic knowledge. The experimental results show that our approach improves the baselines on multiple benchmarks. More importantly, the improvements further increase on zero-shot tables. In future work, we will try to classify different tables and combine meta-learning and reinforcement learning to further explore the generalization capabilities. \section{Acknowledgements} Research in this paper was partially supported by the National Key Research and Development Program of China under grants (2018YFC0830200, 2017YFB1002801), the Natural Science Foundation of China grants (U1736204), the Judicial Big Data Research Centre, School of Law at Southeast University.
{'timestamp': '2021-09-14T02:18:04', 'yymm': '2109', 'arxiv_id': '2109.05395', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05395'}
arxiv
\section{Introduction}\label{sec:intro} Beamforming is an attractive technology to filter out those interfering (or jamming) signals which are spatially apart from the signal of interest. It has a long history (see e.g., \cite{trees02_book}) and has been applied to a wide range of applications including radar, sonar, wireless communications, acoustics, electroencephalography (EEG), among many others. For the upcoming fifth generation (5G) wireless network and Internet of things (IoT) technologies, for instance, beamforming is considered as a key component to revolutionize connectivity as well as massive MIMO (multiple input multiple output) and millimeter wave \cite{sun14,taiwo19,bana19}. The minimum-variance distortionless response (MVDR) beamformer minimizes the variance of the beamformer output under a linear constraint to preserve the desired signal undistorted \cite{van1997localization}. The MVDR beamformer is known to achieve the optimal performance among all linear beamformers in the absence of correlations among sources. In many applications, however, the sources have {\em temporal correlation}, which makes MVDR no longer optimal \cite{hui2010identifying}. Throughout the paper, unless otherwise stated explicitly, the term ``correlation'' means a temporal correlation between the desired and interfering sources. The zero-forcing (ZF) beamformer (aka.~the nulling beamformer) \cite{dalal2006modified,hui2010identifying,hui2006linearly,piotrowski19} minimizes the output variance under multiple linear constraints to preserve the desired signal undistorted and, at the same time, to nullify the interfering signals. Although it could attain better performance than MVDR in the correlated-source settings with high signal to noise ratio (SNR), its performance becomes even worse than MVDR in low SNR cases as it amplifies the noise \cite{hui2006linearly}. The MVDR and ZF beamformers are particular examples of the linearly constrained minimum variance (LCMV) beamformer \cite{Frost72:ProcIEEE,van1997localization}, and can be implemented by efficient adaptive algorithms such as the constrained normalized least mean square (CNLMS) algorithm \cite{apolinario1998constrained}. The studies of the temporal correlation between the desired and interfering signals date back at least to 1970's \cite{owsley74} in the communication area. The major causes of the correlation are multipath propagation which may also happen in other applications such as acoustics) and/or ``smart'' jammers which aim to transmit antiphase replicas of the desired signal for jamming the transmission. In the worst case, the desired and interfering signals would be coherent; i.e., one source signal is an amplitude-scaled phase-shifted version of another one, or in other words the correlation coefficient has a unit amplitude. To alleviate this problem, {\em spatial smoothing} and its improved versions have been proposed, and the impacts of the correlation coefficient on the performance have been investigated in the literature (see \cite[Section 6.12]{trees02_book} and the references therein). This technique, however, has several limitations. For instance, it is only applicable to a regular array geometry such as uniform linear arrays, and/or it requires twice as many sensors as signal sources. An efficient beamformer design that can manage the correlated interference would be beneficial in the future wireless network systems to enhance the connectivity. Another primary application of beamformers is in inverse problems in EEG and magnetoencephalography (MEG), which are imaging modalities that provide a direct measure of the brain activity by measuring the voltage with a set of sensors placed at various locations on the scalp of the subject. The EEG inverse problem aims to localize and reconstruct the sources of brain electrical activity from the EEG measurements. It is widely known that neighboring brain activities (sources) have strong correlations typically, and the signal correlation still remains a challenging issue to be addressed in the brain signal processing area. Focusing on EEG, this is especially true for applications requiring online processing of beamformer output such as brain-computer interface (BCI) \cite{Wittevrongel2016BCI,Mahmoodi2017BCI} and source-space EEG neurofeedback, which is currently another hot topic in brain signal processing \cite{Boe2014neurofeedback,Gepper2017neurofeedback}. To date, the dominant beamforming technique used in these fields has been the MVDR beamformer, see, e.g., \cite{Mullen2015BCI,Hartmann2014neurofeedback,vanLutterveld2017neurofeedback}. Therefore, an introduction of a beamformer design which suppresses efficiently interfering activity, includes as special cases the MVDR and ZF beamformers, and is amenable to efficient adaptive implementation, should bring significant benefits to BCI and source-space EEG neurofeedback. Let us now turn our attention to the relaxed zero forcing (RZF) beamformer \cite{yukawa2011adaptive,yukawa2013dual}. Despite its close link to the ZF beamformer, RZF has solely been studied under the assumption that the source signals are mutually {\em uncorrelated} in time domain. In this case, MVDR is the optimal linear beamformer, and hence no other linear beamformer can outperform it.\footnote{ For clarification, the term ``linear'' here means that the beamformer output is linear in terms of the received vector (the input to the beamformer). RZF is a ``linear beamformer'' involving a ``nonlinear (quadratic) constraint'' in its formulation.} In fact, the key point of the previous works of RZF lies in its adaptive implementation. The central theme addressed therein is an efficient use of the side information about the interference channel for enhancing the convergence speed of adaptive algorithms. The side information is accommodated in the RZF formulation as an ellipsoidal constraint that bounds the contribution of interference in the output using the interference channel information. The RZF beamformer contains MVDR and ZF as its two extremes: MVDR does not consider the correlation explicitly, while ZF annihilates the interfering signals completely. The RZF beamformer belongs to the class of linearly and quadratically constrained minimum variance (LQCMV) beamformer due to the presence of the quadratic constraint as well as the typical distortionless constraint in its formulation. The classical adaptive algorithms such as CNLMS or its projective extension using the projection onto a nonlinear constraint set cannot be applied to RZF since the projection onto the ellipsoidal constraint set admits no closed-form expression. Fortunately, however, it can be implemented efficiently by the multi-domain adaptive learning method \cite{ysy_ieice10_multi}, which implements the ellipsoidal constraint via the projection onto a closed ball in a transform domain. The multi-domain method applied to RZF is referred to as the dual-domain adaptive algorithm (DDAA) \cite{ysy_ieice10_multi,yukawa2013dual}, in which the side information plays a role of guiding the update direction of adaptive beamformer towards the optimal one and thereby yielding remarkably fast convergence. As mentioned already, RZF has not yet been studied under the correlated interference which permits some other linear beamformer to be superior to MVDR. For clarification, the superiority is discussed here in terms of the mean squared error (MSE) performance {\em in the batch setting}, {\em not} in terms of convergence speed of adaptive algorithms. Our central research question is whether the RZF beamformer can be superior to MVDR and ZF, and, if the answer is positive, under what conditions it may happen. The major contributions of the present paper are summarized below. \begin{enumerate} \item A rederivation of the RZF beamformer is presented based on a decomposed form of the MSE function in the presence of temporally correlated interference. \item A theoretical analysis of the RZF beamformer is presented for the tractable case of a single interfering signal that is correlated with the desired signal. Here, the analysis relies on the isomorphism between ${\mathbb C}^2$ and the two dimensional subspace spanned by the channel vectors of the desired and interfering sources under some mapping preserving the norms and inner products. \item The performance of the RZF beamformer is studied through extensive simulations for the general case of multiple correlated interfering signals. \item Consequently, the RZF beamformer is shown to outperform the MVDR and ZF beamformers, in the batch setting, in the presence of correlated interference also in an EEG setup, where the beamformers are used for online reconstruction of brain bioelectrical activity from realistically simulated EEG measurements. It should be emphasized that this is a remarkable difference from the previous studies \cite{yukawa2011adaptive,yukawa2013dual} for uncorrelated interference, which only allows RZF to outperform MVDR in terms of the convergence speed of adaptive algorithms. \end{enumerate} The MSE function can actually be decomposed into the following three terms: (i) the output variance, (ii) the desired-signal-power dependent term, and (iii) the interaction with interference (which will be referred to as the interference term). The interference term here depends on the correlation between the desired and interfering signals (as well as the beamformer outputs of the interference channel vectors). No prior knowledge is assumed available about the correlation, and the primitive idea is mitigating (to some reasonable extent), but {\it not completely annihilating}, the interference term. Although the interference term cannot be suppressed directly, it is mitigated indirectly by a certain quadratic constraint that bounds the total power of the beamformer outputs for the interference channel vectors. The resultant beamformer coincides with the RZF beamformer, although its motivation as well as the underlying assumption is totally different from the original work \cite{yukawa2011adaptive,yukawa2013dual}. The MSE of RZF for the single-interference case is analyzed, and its explicit formula is derived in terms of the spatio-temporal correlations between the desired and interference sources as well as the variances of noise and interference. The analysis reveals that RZF achieves the minimum MSE (MMSE) under certain conditions, and it also clarifies under what conditions RZF outperforms MVDR and ZF, respectively. Numerical examples show that the RZF beamformer achieves significant gains over the whole range of SNR and that its performance is fairly close to the theoretical bound for high SNRs, and it significantly outperforms the MVDR and ZF beamformers. To examine the possibility of exploiting the temporal correlations to enhance the performance further, we also investigate the approximate minimum MSE (A-MMSE) beamformer relying on the availability of some erroneous estimates of the correlations between the desired and interfering sources as well as the availability of an estimate of the signal power. It turns out that A-MMSE is sensitive to the errors in those estimates, while RZF is fairly insensitive to the choice of the power-bounding parameter. We emphasize that the present study is the first work that investigates the RZF beamformer in the correlated-interference scenario, demonstrating its efficacy in managing such interference. Compared to the preliminary version \cite{kono_icassp19}, the new features of this paper include (i) treatment of complex signals, (ii) comprehensive treatment of beamforming problems (rather than focusing on the specific EEG application), (iii) theoretical studies of RZF (Section \ref{sec:analysis}), and (iv) extensive simulation studies including an EEG application, together with considerations of the A-MMSE beamformer (Section \ref{sec:exp}). \section{System Model and Assumptions} \label{sec:prelim} Throughout, $\mathbb{R}$, ${\mathbb C}$, and $\mathbb{N}$ denote the sets of real numbers, complex numbers, and nonnegative integers, respectively. Given a matrix $\signal{A}$, $\signal{A}^{\sf T}$ and $\signal{A}^{\sf{H}}$ denote its transpose and Hermitian transpose, respectively, and $\sigma_{{\rm max}}(\signal A)$ denotes its largest singular value. The identity matrix is denoted by $\signal{I}$, and the zero vector by $\signal{0}$. Given vectors $\signal{x},\signal{y} \in {\mathbb C}^{m}$ of arbitrary dimension $m \in \mathbb{N}^{*} := \mathbb{N}\setminus\{ 0 \}$, define the inner product by $\langle {\signal x},\signal{y} \rangle := \signal{x}^{\sf H}\signal{y}$, and the induced norm by $\|\signal{x}\| := \langle \signal{x},\signal{x} \rangle^{\frac{1}{2}}$. The expectation is denoted by $E(\cdot)$. We consider the situation when $J+1$ spatially-separated sources transmit signals towards a uniform linear array\footnote{ Different types of antenna arrays have also been studied such as nonuniform linear arrays, nested array, coprime arrays, or the maximum inter-element spacing constraint (MISC) arrays (see, e.g., \cite{hoctor90, piya10, liu16, zhou18, zheng19, li20}). An extension to those different arrays is beyond the scope of the current work.} with $N$ antenna sensors. The received signal at sensors at time instant $k\in\mathbb{N}$ is modeled as \begin{eqnarray} \signal{y}(k)=\sum_{j=0}^{J} s_j(k) \signal{h}_j + \signal{n}(k) \in {\mathbb C}^{N}. \label{eq:eeg_model} \end{eqnarray} Here, $\signal{h}_j:=[h_{j,1},h_{j,2},\cdots,h_{j,N}]^{\sf T} \in {\mathbb C}^{N}$ is the channel vector of the $j$th source such that $\norm{\signal{h}_j}=1$, $s_j(k)\in {\mathbb C}$ the $j$th transmit signal, and ${\mathbb C}^{N}\ni\signal{n}(k):=[n_1(k),n_2(k),\cdots,n_N(k)]^{\sf T} \sim \mathcal{CN} (\signal{0},\sigma_n^2\signal{I}) $ the noise vector. Without loss of generality, $s_0(k)$ is supposed to be the desired signal, and all the others are interference. The goal of beamforming is to reconstruct the desired signal $s_0(k)$ from the measurements $\signal{y}(k)$ with the channel information. The assumptions that will be used in the current study are listed below. \begin{assump}\label{assmuption:signal} {}~ \begin{enumerate} \item All the signals $s_j(k)$ and noise are zero-mean weakly-stationary stochastic processes. \item The interfering signals $s_j(k)$, $j=1,2,\cdots,J$, are correlated with the desired signal $s_0(k)$, i.e., \begin{equation} c_j:=E[s_0^*(k)s_j(k)]\neq 0, ~~~j=1,2,\cdots,J. \end{equation} \item The noise is uncorrelated with the signals, i.e., $E[s_j^*(k)\signal{n}(k)] = \signal{0}$ for $j=0,1,\cdots,J$. \item All the channel vectors $\signal{h}_j$ are available.\footnote{This is a realistic assumption in uplink communication in wireless networks and also in EEG applications.} \item The correlations $c_j$ and the signal power $\sigma_0^2:=E(\abs{s_0(k)}^2)$ are completely unknown. \end{enumerate} \end{assump} We note that the model in \refeq{eq:eeg_model} actually gives the forward model in the EEG/MEG inverse problem, which aims to reconstruct the activity of the desired source $s_0(k)$ from the EEG/MEG measurements $\signal{y}(k)$. In this interpretation of the model in \refeq{eq:eeg_model}, for each source $j$, the channel vector $\signal{h}_j:=\signal{h}(\signal{r}_j,\signal{u}_j)\in{\mathbb R}^{N}$ corresponds to the so-called leadfield vector depending on the source position $\signal{r}_{j}$ and the orientation unit vector $\signal{u}_{j}$, $s_j(k)\in {\mathbb R}$ is the electric/magnetic dipole moment at time instant $k$, and the noise vector $\signal{n}(k) \in {\mathbb R}^{N}$ represents the background brain activity along with the noise recorded at the sensor array. We will use this fact in Section \ref{subsec:eeg}, where the performance of beamformers under consideration will be evaluated in this context. \section{Relaxed Zero-forcing Beamformer Rederived to Manage Temporally-correlated Interference} \label{sec:rzf} Under Assumption \ref{assmuption:signal}, the MSE function can be written as \begin{align} \hspace*{-2em}J_{{\rm MSE}}(\signal{w}) :=&~ E\left[\abs{\signal{w}^{\sf H}\signal{y}(k) - s_0(k)}^2\right]\nonumber\\ =&~ \signal{w}^{\sf H} \signal{R} \signal{w} + \sigma_0^2(1-\signal{w}^{\sf H}\signal{h}_0-\signal{h}_0^{\sf H}\signal{w}) - \sum_{j=1}^{J} (c_j \signal{w}^{\sf H}\signal{h}_j + c_j^* \signal{h}_j^{\sf H}\signal{w}), ~\signal{w}\in {\mathbb C}^N, \label{eq:mse_cost} \end{align} where $\signal{R}:=E[\signal{y}(k)\signal{y}(k)^{\sf H}]$. Under the distortionless constraint \begin{equation} \signal{w}\in C := \{\signal{w}\in {\mathbb C}^{N} \mid \signal{w}^{\sf H}\signal{h}_0 = 1\}, \label{eq:def_C} \end{equation} \eqref{eq:mse_cost} reduces to \begin{equation} J_{{\rm MSE}}(\signal{w}) = \underbrace{\signal{w}^{\sf H} \signal{R} \signal{w}}_{\mbox{output variance}} - \underbrace{\sigma_0^2}_{\mbox{signal power}} - \underbrace{\sum_{j=1}^{J} (c_j \signal{w}^{\sf H}\signal{h}_j + c_j^* \signal{h}_j^{\sf H}\signal{w}).}_{\mbox{interaction with interference}}\label{eq:mse_cost_dr} \end{equation} In the absence of correlated sources, the third term of \refeq{eq:mse_cost_dr} disappears, and hence MSE (under the distortionless constraint) can be minimized by minimizing the output variance. This is the reason why the MVDR beamformer, the minimizer of \eqref{eq:mse_cost_dr} under \eqref{eq:def_C}, is optimal. In the presence of correlated sources, on the other hand, the third term makes significant differences and MVDR is no longer optimal. In this case, one may consider to annihilate the third term by imposing the nulling constraints $\signal{w}^{\sf H}\signal{h}_j=0$ for all $j=1,2,\cdots,J$. This is the so-called ZF beamformer. Unfortunately, the ZF beamformer is known to amplify the noise, and its performance degrades seriously under noisy environments. To circumvent the noise amplification problem while exploiting the channel information of the interfering signals, we impose a quadratic constraint, in addition to the linear constraint \eqref{eq:def_C}, that bounds the amount of interference leakage by a certain threshold $\varepsilon \geq 0$, rather than annihilating those signals completely. The RZF beamformer is formally given as follows: \begin{subequations} \label{eq:rzf} \begin{align} \hspace*{-2em}&{\rm minimize~~~} \signal{w}^{\sf H} \signal{R} \signal{w} \label{eq:rzf1}\\ \hspace*{-2em}&{\rm ~subject ~ to~}\left\{ \begin{array}{l} \signal{w}^{\sf H}\signal{h}_0 = 1 ~~~(\Leftrightarrow \signal{w}\in C),\\ \|\signal{H}_{\rm I}^{\sf H}\signal{w}\|^{2}\leq \varepsilon ~~~ (\Leftrightarrow \signal{H}_{\rm I}^{\sf H} \signal{w}\in B_{\varepsilon} :=\{\signal{s}\in {\mathbb C}^{J} \mid \|\signal{s}\|^{{\rm 2}}\leq \varepsilon\}), \end{array}\right. \label{eq:rzf2} \end{align} \end{subequations} where $\signal{H}_{\rm I} := [\signal{h}_1~\signal{h}_2\cdots \signal{h}_J]$ is the interference channel matrix. Let $\signal{R}_{\varepsilon}:= \signal{R} + \lambda_{\varepsilon}\signal{H}_{\rm I} \signal{H}^{\sf H}_{\rm I}$ with the Lagrange multiplier $\lambda_{\varepsilon}\geq 0$ satisfying $\norm{\signal{H}^{\sf H}_{\rm I}\signal{w}_{\rm RZF}}^2= \norm{ \dfrac{\signal{H}_{\rm I}^{\sf H} (\signal{R} + \lambda_{\varepsilon}\signal{H}_{\rm I}\signal{H}^{\sf H}_{\rm I})^{{\rm -1}}{\signal h}_{{\rm 0}}} {\signal{h}_{{\rm 0}}^{\sf H} (\signal{R} + \lambda_{\varepsilon}\signal{H}_{\rm I}\signal{H}^{\sf H}_{\rm I})^{{\rm -1}} \signal{h}_{{\rm 0}}}}^2=\varepsilon$, $\signal{H}:=[\signal{h}_0~\signal{H}_{\rm I}]\in{\mathbb C}^{N\times (J+1)}$, and $\signal{c}:=[1,\signal{0}^{\sf T}]^{\sf T}\in\{0,1\}^{J+1}$. The solution to the problem in \refeq{eq:rzf} is then given by \cite{yukawa2013dual} \begin{equation} \signal{w}_{\rm RZF}=\begin{cases} \dfrac{\signal{R}_{\varepsilon}^{{\rm -1}}{\signal h}_{{\rm 0}}} {\signal{h}_{{\rm 0}}^{\sf H}\signal{R}_{\varepsilon}^{{\rm -1}}\signal{h}_{{\rm 0}}}, & \mbox{ if } \varepsilon>0, \\ \signal{w}_{{\rm ZF}}:=\signal{R}^{-1} \signal{H}\left(\signal{H}^{\sf H}\signal{R}^{-1}\signal{H}\right)^{-1}\signal{c}, & \mbox{ if } \varepsilon=0. \end{cases} \label{eq:wrzf_analytic_solution} \end{equation} For the particular choice of $\lambda_{\varepsilon}:=0$, RZF reduces to the MVDR beamformer $\signal{w}_{\rm MVDR}:= \dfrac{ \signal{R}^{{\rm -1}}{\signal h}_{{\rm 0}}} {\signal{h}_{{\rm 0}}^{\sf H} \signal{R}^{\rm -1}\signal{h}_{{\rm 0}}}$, of which the corresponding $\varepsilon$ is $\varepsilon_{\rm MVDR}:= \norm{ \signal{H}_{\rm I}^{\sf H} \signal{w}_{\rm MVDR}}^2$. In contrast, as $\lambda_{\varepsilon}\rightarrow + \infty$, the corresponding $\varepsilon$ vanishes. In fact, $\lambda_{\varepsilon}\in[0,+\infty)$ is a strictly monotone decreasing function of $\varepsilon\in (0,\varepsilon_{\rm MVDR}]$, and thus the correspondence is one to one. The RZF beamformer attains significantly better performance than MVDR and ZF and could achieve (near) optimal performance in some cases, as shown in Sections \ref{sec:analysis} and \ref{sec:exp}. For self-containedness, an adaptive implementation of RZF by the dual-domain adaptive algorithm \cite{ysy_ieice10_multi} is given in the appendix. \begin{remark}[On Unbiasedness] \label{remark:unbiasedness} Let $\mu_j\in{\mathbb C}$ denote the mean value of $s_j(k)$; i.e., $\mu_j:=E[s_j(k)]$, $j=0,1,\cdots,J$. Although $\mu_j:=0$, $j=0,1,\cdots,J$, is assumed in Assumption \ref{assmuption:signal}, we also consider the general case here to clarify the statistical assumptions required for unbiasedness. We discuss the unbiasedness of a linear estimator $\widehat{s}_0(k):=\signal{w}^{\sf H} \signal{y}(k)$ of a random variable $s_0(k)$ with a beamforming vector $\signal{w}$ subject to the distortionless constraint $\signal{w}^{\sf H} \signal{h}_0=1$. This includes the case of the RZF beamformer in \eqref{eq:rzf}. Inserting \eqref{eq:eeg_model} into $\widehat{s}_0(k)=\signal{w}^{\sf H} \signal{y}(k)$ yields \begin{equation} \label{reveal} \widehat{s}_0(k)=\signal{w}^{\sf H} \signal{h}_0 s_0(k)+\sum_{j=1}^J \signal{w}^{\sf H} \signal{h}_j s_j(k)+ \signal{w}^{\sf H} \signal{n}(k). \end{equation} Since $s_0(k)$ is modeled as a random variable, the unbiasedness condition of the estimator $\widehat{s}_0(k)$ is given by \cite{kailath00}: \begin{equation*} E[\widehat{s}_0(k)] = \mu_0. \end{equation*} Due to the zero-mean assumption $E[\signal{n}(k)]=\signal{0}$ for noise as well as the distortionless constraint $\signal{w}^{\sf H} \signal{h}_0=1$, it follows that \begin{equation} E[\widehat{s}_0(k)] = \mu_0+\sum_{j=1}^J \signal{w}^{\sf H} \signal{h}_j\mu_j. \end{equation} This means that $\widehat{s}_0(k)$ is an unbiased estimator of $s_0(k)$ if $\sum_{j=1}^J\signal{w}^{\sf H} \signal{h}_j\mu_j=0$. We thus obtain the following observations. \begin{enumerate} \item Suppose that all interfering signals have zero mean, i.e., if $\mu_j(:=E[s_j(k)])$ $=0$ for $j=1,2,\dots,n$. In this case, \emph{any} estimator of the form $\widehat{s}_0(k):=\signal{w}^{\sf H} \signal{y}(k)$ is unbiased under the distortionless constraint. This applies to the present study, since the conditions are clearly satisfied under Assumption \ref{assmuption:signal}. Note here that the only statistical assumptions required to draw this conclusion is the zero-mean assumptions of the interfering signals and the noise vector. \item Suppose that some interfering signal(s) has (have) non-zero mean. In this case, the unbiasedness condition $\sum_{j=1}^J\signal{w}^{\sf H} \signal{h}_j\mu_j=0$ can be achieved, e.g., by using the zero-forcing constraints $\signal{w}^{\sf H} \signal{h}_j=0$ for $j=1,\dots,n$, or only for those interfering signals with non-zero means (if known). \end{enumerate} \end{remark} \begin{remark}[Tips for $\epsilon$-Parameter Design] \label{remark:epsilon_design} Below are some tips on how to choose the $\epsilon$ parameter. \begin{itemize} \item In the high SNR regime, $\epsilon$ should be set to a small value, since the impact of noise on MSE is small (see \eqref{eq:jmse_distortionless} in Lemma \ref{lemma:mse}). \item When one (or more) of the interfering signals, say the first one, is spatially correlated to the desired signal, i.e., $\abs{\innerprod{\signal{h}_0}{\signal{h}_1}}\approx 1$, $\epsilon$ should be set to a large value. The reason is the following: if $\epsilon$ is small in such a situation, the beamforming vector $\signal{w}$ needs to be nearly orthogonal to the interference channel vectors including $\signal{h}_1$, i.e., $\innerprod{\signal{w}}{\signal{h}_1}\approx0$, but at the same time it also needs to satisfy $\innerprod{\signal{w}}{\signal{h}_0}=1$, and those two requirements under $\abs{\innerprod{\signal{h}_0}{\signal{h}_1}}\approx 1$ make the norm $\norm{\signal{w}}$ unacceptably large and thus cause serious noise amplification. \end{itemize} Adaptation of $\epsilon$ is left as an interesting open issue. \end{remark} \section{Analytical Study of RZF Beamformer for Single Interference Case} \label{sec:analysis} After some general discussions about the MSEs of beamformers, we present the MSE analysis of RZF for the single-interference case. The proofs are finally given together with some remarks. \subsection{General Discussions} It is straightforward to verify the following lemma. \begin{lemma} \label{lemma:mse} Let $c_{l,j}:=E(s_l^*(k)s_j(k))$, $l,j=1,2,\cdots J$. Then, the MSE defined in \eqref{eq:mse_cost} can be rewritten as \begin{align} \hspace*{-0em} J_{\rm MSE}(\signal{w})= &~ \sigma_0^2 \left(1+\abs{\signal{w}^{\sf H}\signal{h}_0}^2 - \signal{w}^{\sf H}\signal{h}_0 - \signal{h}_0^{\sf H}\signal{w} \right) + \sigma_n^2 \norm{\signal{w}}^2 \nonumber\\ \hspace*{-0em}&+\sum_{j=1}^{J} c_j (\signal{h}_0^{\sf H}\signal{w} -1) \signal{w}^{\sf H}\signal{h}_j +\sum_{j=1}^{J} c_j^* (\signal{w}^{\sf H}\signal{h}_0 -1) \signal{h}_j^{\sf H}\signal{w} \nonumber\\ \hspace*{-0em}&+\sum_{l=1}^{J}\sum_{j=1}^{J}c_{l,j} \signal{h}_l^{\sf H} \signal{w} \signal{w}^{\sf H} \signal{h}_j, ~~~\signal{w}\in {\mathbb C}^N. \end{align} Under the distortionless constraint \eqref{eq:def_C}, MSE reduces to \begin{equation} J_{\rm MSE}(\signal{w})= \sigma_n^2 \norm{\signal{w}}^2+\sum_{l=1}^{J}\sum_{j=1}^{J}c_{l,j} \signal{h}_l^{\sf H} \signal{w} \signal{w}^{\sf H} \signal{h}_j,~\signal{w}\in C. \label{eq:jmse_distortionless} \end{equation} The minimizer of \eqref{eq:jmse_distortionless} is given by \begin{equation} \signal{w}_{\rm MMSE\mathchar`-DR}:=\frac{\widetilde{\signal{R}}^{-1}\signal{h}_0} {\signal{h}_0^{\sf H}\widetilde{\signal{R}}^{-1}\signal{h}_0}, \label{eq:mmsedr} \end{equation} which will be referred to shortly as MMSE-DR (MMSE under distortionless response constraint), where $\widetilde{\signal{R}}:= \sigma_n^2 \signal{I} + \sum_{l=1}^{J}\sum_{j=1}^{J}c_{l,j} \signal{h}_j\signal{h}_l^{\sf H}$. \end{lemma} In the analysis of the RZF beamformer, the following observation is useful: \begin{equation} \signal{w}_{\rm RZF}\in {\rm span}\{\signal{h}_j\}_{j=0}^J:=\left\{ \sum_{j=0}^{J}\zeta_j \signal{h}_j\mid \zeta_j\in {\mathbb C}\right\}, \label{eq:wrzf_property} \end{equation} which can easily be verified by applying the matrix inversion lemma \cite{horn_johnson85} twice in \eqref{eq:wrzf_analytic_solution}, first to $\signal{R}_{\varepsilon}^{-1}$ and then to $\signal{R}^{-1}$ which appears in the outcome of the first application of the lemma. In the rest of this section, we restrict our attention to the tractable case of $J:=1$. In this case, \eqref{eq:wrzf_property} implies that $\signal{w}_{\rm RZF}$ belongs to the two dimensional subspace ${\rm span}\{\signal{h}_0,\signal{h}_1\}$, and hence the problem reduces completely to the two dimensional case of $N:=2$ by considering the isomorphism between the two dimensional subspace ${\rm span}\{\signal{h}_0,\signal{h}_1\}$ of ${\mathbb C}^N$ and ${\mathbb C}^2$ under some mapping preserving the norms and inner products. We shall discuss first about the real case, and then move to the complex case. \subsection{Real Case for $J:=1$} We present analyses of RZF for the real-signal case under the presence of single interference below. \begin{theorem} \label{theorem:rzf_real_Nd} Let $J:=1$, $\norm{\signal{h}_0}=\norm{\signal{h}_1}=1$, $\innerprod{\signal{h}_0}{\signal{h}_1}=\sin \tau\in(-1,1)$, the spatial-separation factor $\tau\in(-\pi/2,\pi/2)$, the powers $\sigma_0^2>0$, $\sigma_1^2>0$, $\sigma_n^2>0$ of the desired signal $s_0$, the interference $s_1$, and noise, respectively, and the correlation factor $c_1(:=E[s_0^*(k)s_1(k)]) \in[-\sigma_0\sigma_1,\sigma_0\sigma_1]$.\footnote{The correlation coefficient satisfies $\rho_1:=c_1/\sigma_0\sigma_1\in [-1,1]$ in general.} Note here that the trivial case of $\sin\tau=\pm 1$ is excluded, since there is no spatial separation between $\signal{h}_0$ and $\signal{h}_1$ in this case. The MSE of the RZF beamformer is given, as a function of the Lagrange multiplier $\lambda_\varepsilon$, by \begin{equation} {\rm MSE}(\lambda_\varepsilon) = \frac{\delta^2(\sigma_1^2 \cos^2\tau + \sigma_n^2)}{g^2(\lambda_{\varepsilon})} - \frac{2\sigma_n^2 \delta\tan\tau}{g(\lambda_{\varepsilon})} + \sigma_n^2(\tan^2\tau +1), \label{eq:theorem_mse} \end{equation} where \begin{align} \delta:=&~\sigma_n^2\tan \tau-c_1 \cos\tau, \label{eq:def_delta}\\ g(\lambda_{\varepsilon}):=&~\cos^2\tau \lambda_\varepsilon + \sigma_1^2 \cos^2\tau+\sigma_n^2>0. \label{eq:def_g} \end{align} \begin{enumerate} \item Assume that $\delta=0$. Then, the MSE reduces to $\sigma_n^2 (\tan^2\tau+1)$, which is constant in $\lambda_{\varepsilon}$. \item Assume that $\delta\neq0$. If \begin{equation} \gamma:=\dfrac{\sigma_n^2\tan\tau}{\delta}\leq 0, \label{eq:def_gamma} \end{equation} ${\rm MSE}(\lambda_\varepsilon)$ is monotonically decreasing, and the ZF beamformer (corresponding to the limit of $\lambda_\varepsilon\rightarrow +\infty$) is optimal in the MSE sense. If $\gamma> 0$ ($\Rightarrow \sin\tau\neq 0$), ${\rm MSE}(\lambda_\varepsilon)$ is minimized by \begin{equation} \lambda_{\varepsilon}:= \begin{cases} -\dfrac{c_1(\sigma_1^2\cos^2\tau + \sigma_n^2)}{\sigma_n^2\sin\tau}>0, & \mbox{if } \gamma\in(0,1),\\ 0, & \mbox{if } \gamma\geq 1. \end{cases} \label{eq:theorem_lambda} \end{equation} Note here by \refeq{eq:def_delta} and \eqref{eq:def_gamma} that $0<(\gamma^{-1}-1)/\cos^2 \tau = -c_1/(\sigma_n^2\sin\tau)$ for $\gamma\in(0,1)$. \end{enumerate} \end{theorem} \begin{theorem}[Achieved MSE in real case] \label{theorem:real_mse} Assume that $\delta(:=\sigma_n^2\tan \tau-c_1 \cos\tau) = 0$. Then, it holds that $\mbox{MSE}_{\rm RZF}= \mbox{MSE}_{\rm ZF}=\mbox{MSE}_{\rm MVDR}$ for any $\lambda_\varepsilon\geq 0$. Assume now that $\delta\neq 0$. Then, with the optimal Lagrange multiplier $\lambda_\varepsilon$, it holds that \begin{equation} \mbox{MSE}_{\rm RZF}= \begin{cases} \mbox{MSE}_{\rm ZF}, & \mbox{if } \gamma\left(:=(\sigma_n^2\tan\tau)/\delta\right)\leq 0,\\ \mbox{MSE}_{\rm MMSE\mathchar`-DR}, & \mbox{if } \gamma\in(0,1),\\ \mbox{MSE}_{\rm MVDR}, & \mbox{if } \gamma\geq 1, \end{cases} \label{eq:mse_rzf_real} \end{equation} where \begin{align} \mbox{MSE}_{\rm MVDR} =&~ \frac{\sigma_n^2(\sigma_1^2+\sigma_n^2) +\abs{c_1}^2\cos^2\tau}{\sigma_1^2\cos^2\tau+\sigma_n^2}, \label{eq:mse_mvdr_real} \\ \mbox{MSE}_{\rm ZF} =&~ \sigma_n^2(\tan^2\tau +1), \label{eq:mse_zf_real} \\ \mbox{MSE}_{\rm MMSE\mathchar`-DR} =&~ \frac{\sigma_n^2(\sigma_1^2+\sigma_n^2)}{\sigma_1^2\cos^2\tau+\sigma_n^2} \label{eq:mse_mmsedr_real}\\ =&~ \mbox{MSE}_{\rm MVDR} - \frac{\abs{c_1}^2\cos^2\tau}{\sigma_1^2\cos^2\tau+\sigma_n^2} \label{eq:mse_mmsedrmvdr_real}\\ =&~ \mbox{MSE}_{\rm ZF} - \frac{\sigma_n^4\tan^2\tau}{\sigma_1^2\cos^2\tau+\sigma_n^2}. \label{eq:mse_mmsedrzf_real} \end{align} \end{theorem} The expression in \eqref{eq:mse_mvdr_real} implies that, when $c_1\neq 0$ (in the presence of temporal correlations between the desired and interfering sources), the MSE of MVDR does not decrease monotonically in general and may even increase as the noise power $\sigma_n^2$ decreases. This is also true for the case of many users as shown in Section \ref{sec:exp}. \subsection{Complex Case for $J:=1$} In an analogous way to the real case, the following theorems can be verified. \begin{theorem} \label{theorem:rzf_complex_Nd} Let $J:=1$, $\norm{\signal{h}_0}=\norm{\signal{h}_1}=1$, $\innerprod{\signal{h}_0}{\signal{h}_1}=\sin \tau e^{i\phi_z}$, the spatial-separation factor $\tau\in[0,\pi/2)$, $\phi_z\in[0,2\pi)$, $\sigma_0^2>0$, $\sigma_1^2>0$, $\sigma_n^2>0$, and the correlation factor $c_1:=\abs{c_1}e^{i\phi_c}\in\{c\in {\mathbb C}\mid \abs{c}\leq \sigma_0\sigma_1\}$, $\phi_c\in[0,2\pi)$.\footnote{The range $[0,\pi/2)$ of $\tau$ is a half of the range $(-\pi/2,\pi/2)$ in Theorem \ref{theorem:rzf_real_Nd} as the other half $(-\pi/2,0)$ is covered by letting $\phi_z:=\pi$.} Here, the trivial case of $\sin\tau=1$ is excluded as in Theorem \ref{theorem:rzf_real_Nd}. Then, the MSE is given, as a function of the Lagrange multiplier $\lambda_\varepsilon$, by \begin{equation} {\rm MSE}(\lambda_\varepsilon) = \frac{\abs{\delta_2}^2(\sigma_1^2 \cos^2\tau + \sigma_n^2)}{g^2(\lambda_{\varepsilon})} - \frac{2\sigma_n^2 \delta_1\tan\tau}{g(\lambda_{\varepsilon})} + \sigma_n^2(\tan^2\tau +1). \label{eq:theorem_mse_complex} \end{equation} Here, $g(\lambda_{\varepsilon})$ is defined in \eqref{eq:def_g} and \begin{align} \delta_1:=&~\sigma_n^2 \tan\tau - \abs{c_1}\cos\tau\cos(\phi_c+\phi_z), \label{eq:delta1}\\ \delta_2:=&~\sigma_n^2 \tan\tau - \abs{c_1}\cos\tau\exp[i(\phi_c+\phi_z)]. \label{eq:delta2} \end{align} \begin{enumerate} \item Assume that $\delta_2=0$ ($\Rightarrow \delta_1=0$). Then, the MSE reduces to $\sigma_n^2 (\tan^2\tau+1)$, which is constant in $\lambda_{\varepsilon}$. \item Assume that $\delta_2\neq0$. \begin{enumerate} \item If \begin{equation} \gamma:=\dfrac{\delta_1\sigma_n^2\tan\tau}{\abs{\delta_2}^2} \leq 0~ (\Leftrightarrow \delta_1 \tan\tau\leq 0), \end{equation} ${\rm MSE}(\lambda_\varepsilon)$ is monotonically decreasing, and the ZF beamformer is optimal in the MSE sense. \item If $\gamma \geq 1$, ${\rm MSE}(\lambda_\varepsilon)$ is monotonically increasing, and thus is minimized by $\lambda_\varepsilon:=0$. \item If $\gamma \in (0,1)$, ${\rm MSE}(\lambda_\varepsilon)$ is minimized by \begin{equation} \lambda_{\varepsilon}:= \dfrac{\sigma_1^2\cos^2\tau + \sigma_n^2}{\cos^2\tau} \left(\frac{1-\gamma}{\gamma}\right) >0. \label{eq:theorem_lambda_comp} \end{equation} \end{enumerate} \end{enumerate} \end{theorem} \begin{theorem}[Superiority of RZF] \label{theorem:rzf_superiority} Under the same settings as in Theorem \ref{theorem:rzf_complex_Nd}, the RZF beamformer with the optimal Lagrange multiplier $\lambda_\varepsilon$ gives a strictly smaller MSE than the MVDR and ZF beamformers (and achieves the minimum MSE under the distortionless constraint) if and only if $0<\delta_1\tan\tau<\abs{\delta_2}^2$. Moreover, the same is true if (but not only if) $c_1\neq 0$ and $\sin\tau\cos(\phi_c+\phi_z)<0$. \end{theorem} \begin{theorem}[Achieved MSE in complex case] \label{theorem:complex_mse} Assume the same settings as in Theorem \ref{theorem:rzf_complex_Nd}. If $\delta_2(:=\sigma_n^2 \tan\tau - \abs{c_1}\cos\tau\exp[i(\phi_c+\phi_z)]) = 0$, it holds that $\mbox{MSE}_{\rm RZF}= \mbox{MSE}_{\rm ZF}=\mbox{MSE}_{\rm MVDR}$ for any $\lambda_\varepsilon\geq 0$. Assume that $\delta_2\neq 0$. Then, with the optimal Lagrange multiplier $\lambda_\varepsilon$, it holds that \begin{equation} \mbox{MSE}_{\rm RZF}= \begin{cases} \mbox{MSE}_{\rm ZF}, & \hspace*{-6em}\mbox{if } \gamma\left(:=\dfrac{\delta_1\sigma_n^2\tan\tau}{\abs{\delta_2}^2}\right)\leq 0,\\ \mbox{MSE}_{\rm MMSE\mathchar`-DR} + \left(1-\abs{\dfrac{\delta_1}{\delta_2}}^2\right) \dfrac{\sigma_n^4\tan^2\tau}{\sigma_1^2\cos^2\tau+\sigma_n^2}, & \mbox{if } \gamma\in(0,1),\\ \mbox{MSE}_{\rm MVDR}, & \mbox{if } \gamma\geq 1, \end{cases} \label{eq:MSE_complex} \end{equation} where the MSEs of the MVDR, ZF, and MMSE-DR beamformers are given by the same expressions as in Theorem \ref{theorem:real_mse}. \end{theorem} \begin{remark} [On Theorem \ref{theorem:complex_mse}: single-interference case] \label{remark:theorem_complex_mse} ~ \begin{enumerate} \item Suppose that $\delta_1\neq 0$ ($\Rightarrow \delta_2\neq 0$), $\tau\in(0,\pi/2)$, $\sigma_n^2>0$, and $c_1\neq 0$. Then, it can be shown that MSE$_{\rm RZF}=$ MSE$_{\rm MMSE\mathchar`-DR}$ (i.e., RZF is optimal) if and only if $\cos(\phi_c+\phi_z)=-1$ ($\Leftrightarrow \delta_1=\delta_2$ and $\gamma\in(0,1)$). \item The ratio between ZF and MMSE-DR is given by \begin{equation*} \frac{ \mbox{MSE}_{\rm MMSE\mathchar`-DR}}{\mbox{MSE}_{\rm ZF}}= 1-\frac{1}{[1+(\sigma_1^2/\sigma_n^2)\cos^2\tau](1+\tan^{-2}\tau)}, \end{equation*} which approaches zero as $\cos^2\tau\rightarrow 0$. \item The ratio between MVDR and MMSE-DR is given by \begin{equation*} \frac{ \mbox{MSE}_{\rm MMSE\mathchar`-DR}}{\mbox{MSE}_{\rm MVDR}}= \frac{1}{1 + \dfrac{\abs{c_1}^2\cos^2\tau}{\sigma_n^2(\sigma_1^2+\sigma_n^2)}} \in\Bigg( \frac{\sigma_n^2}{\sigma_n^2+1},1 \Bigg], \end{equation*} where the lower bound corresponds to the extreme case of $\abs{c_1}^2=\sigma_1^2$ and $\cos^2 \tau=1$ in the limit of $\sigma_1^2\rightarrow \infty$, and this lower bound approaches zero as $\sigma_n^2\rightarrow 0$. The ratio increases as $(\sigma_1^2/\sigma_n^2)\abs{c_1/\sigma_1}^2\cos^2\tau$ increases. \item The MSE of MVDR increases as the amplitude $\abs{c_1}$ of the correlation does, while those of MMSE-DR and ZF are independent of the correlation. The performance of RZF depends on $\abs{c_1}$ in general but is less sensitive than that of MVDR, as shown in Section \ref{sec:exp}. \item It holds that $\mbox{MSE}_{\rm RZF}=\mbox{MSE}_{\rm MVDR}$ when $c_1=0$ (there is no correlation between the desired and the interfering signals), $\sigma_n^2\rightarrow +\infty$ (the noise power is huge), or $\cos^2\tau=0$ ($\signal{h}_0$ and $\signal{h}_1$ are completely aligned). This is consistent with Theorems \ref{theorem:rzf_real_Nd} and \ref{theorem:rzf_complex_Nd}. In sharp contrast, $\mbox{MSE}_{\rm RZF}=\mbox{MSE}_{\rm ZF}$ when $\sigma_n^2=0$ (the signal is noise free), $\sin^2\tau=0$ ($\signal{h}_1$ is orthogonal to $\signal{h}_0$), or $\sigma_1^2\rightarrow +\infty$ (the interference power is huge). \end{enumerate} \end{remark} \subsection{Proofs} The proofs of Theorems 1 -- 5 are given below. \subsubsection{Proof of Theorem \ref{theorem:rzf_real_Nd}} In the case of $J=1$, \eqref{eq:jmse_distortionless} reduces to \begin{equation} J_{\rm MSE}(\signal{w})= \sigma_n^2 \norm{\signal{w}}^2+\sigma_1^2 |\signal{h}_1^{\sf H} \signal{w}|^2, ~\signal{w}\in C. \label{eq:J_MSE_2dimcase} \end{equation} Now, applying the matrix inversion lemma to \refeq{eq:wrzf_analytic_solution}, one can easily verify that $\norm{\signal{w}_{\rm RZF}}^2$ and $\abs{\innerprod{\signal{h}_1}{\signal{w}_{\rm RZF}}}^2$ depend only on the norms ($\norm{\signal{h}_0}$ and $\norm{\signal{h}_1}$) and the inner product $\innerprod{\signal{h}_0}{\signal{h}_1}$. This simple observation implies that the MSE of the RZF beamformer in the theorem can be expressed analytically via analyzing the two-dimensional case\footnote{The dimensionality reduction can also be understood through the isomorphism between ${\rm span}\{\signal{h}_0,\signal{h}_1\}\subset {\mathbb C}^N$ and ${\mathbb C}^2$. Indeed, the pair $(\signal{h}_0,\signal{h}_1)$ of vectors in Theorem \ref{theorem:rzf_real_Nd} has the same geometric structure as in Lemma \ref{lemma:rzf_real}.} with such unit vectors $\signal{h}_0\in{\mathbb C}^2$ and $\signal{h}_1\in{\mathbb C}^2$ that satisfy $\innerprod{\signal{h}_0}{\signal{h}_1}=\sin \tau$. The proof is thus completed by proving the following lemma. \begin{lemma} \label{lemma:rzf_real} Let $N:=2$, $J:=1$, $\signal{h}_0:=[0,1]^{\sf T}$, $\signal{h}_1:=[\cos \tau,\sin \tau]^{\sf T}$, $\tau\in(-\pi/2,\pi/2)$, $\sigma_0^2>0$, $\sigma_1^2>0$, $\sigma_n^2>0$, and $c_1\in[-\sigma_0\sigma_1,\sigma_0\sigma_1]$. The RZF beamformer is then given by \begin{equation} \signal{w}_{\rm RZF}= \left[ \begin{array}{c} -\dfrac {\cos \tau\left[(\sigma_1^2+\lambda_{\varepsilon})\sin\tau + c_1\right]} {(\sigma_1^2+\lambda_{\varepsilon}) \cos^2\tau + \sigma_n^2} \\ 1 \end{array} \right], \label{eq:theorem_wrzf} \end{equation} for which the MSE is given by \eqref{eq:theorem_mse}. \begin{enumerate} \item[(i)] Assume that $\delta=0$. Then, MSE is given by $\sigma_n^2 (\tan^2\tau+1)$, which is constant in $\lambda_{\varepsilon}$. \item[(ii)] Assume that $\delta\neq0$. If $\gamma:=\dfrac{\sigma_n^2\tan\tau}{\delta}\leq 0$, ${\rm MSE}(\lambda_\varepsilon)$ is monotonically decreasing, and the ZF beamformer (corresponding to the limit of $\lambda_\varepsilon\rightarrow +\infty$) is optimal in the MSE sense. If $\gamma> 0$ ($\Rightarrow \sin\tau\neq 0$), ${\rm MSE}(\lambda_\varepsilon)$ is minimized by \eqref{eq:theorem_lambda}. Note here that $0<(\delta/(\sigma_n^2 \tan\tau)-1)/\cos^2 \tau = -c_1/(\sigma_n^2\sin\tau)$. \end{enumerate} \end{lemma} {\it Proof:} For the sake of simple notation, we let $c:=\cos\tau$ and $s:=\sin\tau$. By $\signal{R}= \sigma_0^2\signal{h}_0\signal{h}_0^{\sf T} +\sigma_1^2\signal{h}_1\signal{h}_1^{\sf T} + c_1(\signal{h}_0\signal{h}_1^{\sf T} + \signal{h}_1\signal{h}_0^{\sf T}) +\sigma_n^2\signal{I}$, we can verify that \begin{equation} \signal{R}_\varepsilon= \left[ \begin{array}{cc} (\sigma_1^2 + \lambda_{\varepsilon})c^2+\sigma_n^2 & (\sigma_1^2 + \lambda_{\varepsilon})cs + c_1c \\ (\sigma_1^2 + \lambda_{\varepsilon})cs + c_1 c & ~(\sigma_1^2 + \lambda_{\varepsilon})s^2+2c_1s+\sigma_n^2+\sigma_0^2 \\ \end{array} \right], \end{equation} from which it follows that \begin{equation} \signal{R}_\varepsilon^{-1}\signal{h}_0 \sim \left[ \begin{array}{c} -c\left[ (\sigma_1^2 + \lambda_{\varepsilon})s+c_1 \right]\\ ~(\sigma_1^2 + \lambda_{\varepsilon})c^2+\sigma_n^2 \\ \end{array} \right]. \end{equation} Hence, we obtain \begin{equation} \signal{w}_{\rm RZF}= \dfrac{\signal{R}_{\varepsilon}^{{\rm -1}}{\signal h}_{{\rm 0}}} {\signal{h}_{{\rm 0}}^{\sf T}\signal{R}_{\varepsilon}^{{\rm -1}}\signal{h}_{{\rm 0}}} = \left[ \begin{array}{c} -\dfrac{c\left[ (\sigma_1^2 + \lambda_{\varepsilon})s+c_1\right]} {(\sigma_1^2 + \lambda_{\varepsilon})c^2+\sigma_n^2} \\ 1 \end{array} \right]. \label{eq:w_rzf_2dimcase} \end{equation} Substituting \eqref{eq:w_rzf_2dimcase} into \eqref{eq:J_MSE_2dimcase} yields \eqref{eq:theorem_mse}. In the rest of the proof, we solely consider the case of $\delta\neq 0$, as the case of $\delta=0$ is clear. In this case, define $x:=1/g(\lambda_\varepsilon)\in(0,1/(\sigma_1^2 \cos^2\tau+\sigma_n^2)]$ for $\lambda_\varepsilon\in[0,+\infty)$. Then, MSE can be seen as a quadratic function of $x$, and its minimum over ${\mathbb R}$ is achieved by \begin{equation} x^*:= \frac{1}{\sigma_1^2 \cos^2\tau+\sigma_n^2}\times \frac{\sigma_n^2\tan\tau}{\underbrace{\sigma_n^2\tan\tau - c\cos\tau}_{=\delta}}. \end{equation} If $\gamma(:=(\sigma_n^2\tan\tau)/\delta)\leq 0$, $x^*\leq 0$ and hence MSE is a monotonically increasing function of $x$ within the actual range $x\in(0,1/(\sigma_1^2 \cos^2\tau+\sigma_n^2)]$. If, on the other hand, $\dfrac{\sigma_n^2\tan\tau}{\delta}\geq 1$, $x^*\geq 1/(\sigma_1^2 \cos^2\tau+\sigma_n^2)$ and hence MSE is a monotonically decreasing function of $x$ within the range. In this case, the minimum is clearly achieved by $x:= 1/(\sigma_1^2\cos^2\tau+\sigma_n^2) \Leftrightarrow \lambda_\varepsilon:=0$. If $\dfrac{\sigma_n^2\tan\tau}{\delta}\in(0,1)$, $x^*$ lies in the range, and its corresponding $\lambda_\varepsilon$ is given by $\lambda_\varepsilon := -c_1\left[(\sigma_1^2/\sigma_n^2)\cos^2\tau + 1\right]/\sin\tau$. \hspace*{\fill} $\Box $ \subsubsection{Proof of Theorem \ref{theorem:real_mse}} \label{subsubsec:proof_Theorem2} We first prove the following proposition. \begin{proposition} \label{proposition:mmsedr} Under the same settings as Lemma \ref{lemma:rzf_real}, the MMSE beamformer under $\signal{w}\in C$ are given respectively by \begin{align} \signal{w}_{\rm MMSE\mathchar`-DR} =&~ \left[ \begin{array}{c} -\dfrac {\sigma_1^2 \sin\tau\cos\tau} {\sigma_1^2\cos^2\tau + \sigma_n^2} \\ 1 \end{array} \right], \label{eq:mmsedr_2dim_real}\\ \signal{w}_{\rm MVDR} =&~ \left[ \begin{array}{c} -\dfrac{\cos\tau (\sigma_1^2 \sin\tau+ c_1)} {\sigma_1^2\cos^2\tau + \sigma_n^2} \\ 1 \end{array} \right] \nonumber\\ = &~ \signal{w}_{\rm MMSE\mathchar`-DR}- \left[ \begin{array}{c} \dfrac {c_1 \cos\tau} {\sigma_1^2\cos^2\tau + \sigma_n^2} \\ 0 \end{array} \right]. \label{eq:mvdr_2dim_real} \end{align} \end{proposition} {\it Proof:} Equation \eqref{eq:mmsedr_2dim_real} can be verified by substituting the following equations into \eqref{eq:mmsedr}: \begin{align} \widetilde{\signal{R}} =& ~\signal{Q} \signal{\Lambda} \signal{Q}^{\sf T},\nonumber\\ \signal{h}_0 =&~ \signal{Q}\signal{h}_1^{\perp}, \end{align} where \begin{align} \signal{Q}:=&~\left[\signal{h}_1 ~ \signal{h}_1^{\perp}\right]:= \left[\begin{array}{cc} \cos\tau &\sin\tau \\ \sin\tau & - \cos\tau \end{array}\right], \nonumber\\ \signal{\Lambda}:=&~ \left[\begin{array}{cc} \sigma_1^2 + \sigma_n^2 & 0 \\ 0 & \sigma_n^2 \end{array}\right]. \end{align} Note here that the matrix $\signal{Q}$ is symmetric; i.e., $\signal{Q}^{\sf T}=\signal{Q}$. Equation \eqref{eq:mvdr_2dim_real} can readily be verified by substituting $\lambda_\varepsilon:=0$ into \eqref{eq:w_rzf_2dimcase}. \hspace*{\fill} $\Box $ \noindent{\it Proof of Theorem \ref{theorem:real_mse}:} Substituting \eqref{eq:mmsedr_2dim_real} and \eqref{eq:mvdr_2dim_real} into \refeq{eq:J_MSE_2dimcase} yields \eqref{eq:mse_mvdr_real} and \eqref{eq:mse_mmsedr_real}. The MSE \eqref{eq:mse_zf_real} of ZF is verified by considering the limit of $\lambda_\varepsilon\rightarrow +\infty$ in \eqref{eq:theorem_mse}. The rest to prove is \eqref{eq:mse_rzf_real}, in which the cases of $\gamma\leq 0$ and $\gamma\geq 1$ can be verified straightforwardly from Theorem \ref{theorem:rzf_real_Nd}. The case of $\gamma\in (0,1)$ can be verified by substituting \eqref{eq:def_delta} -- \eqref{eq:theorem_lambda} into \eqref{eq:theorem_mse}. \begin{figure}[t!] \centering \psfrag{w1}[Bl][Bl][0.9]{$w_1$} \psfrag{w2}[Bl][Bl][0.9]{$w_2$} \subfigure[$c_1:=0.99$, $\tau:=\pi/6$ ($\gamma=-$2.0619)]{ \hspace*{-1.5em}\includegraphics[width =.7\textwidth]{fig1a.eps} } \centering \subfigure[$c_1:=-0.2$, $\tau:=\pi/6$ ($\gamma=$0.7692)]{ \hspace*{-1.5em}\includegraphics[width =.7\textwidth]{fig1b.eps} } \subfigure[$c_1:=0.1$, $\tau:=\pi/6$ ($\gamma=$1.1765)]{ \hspace*{-1.5em}\includegraphics[width =.7\textwidth]{fig1c.eps} } \caption{The $w_1$ coordinate for $N:=2$ and $J:=1$ with $\signal{h}_0:=[0,1]^{\sf T}$ under $\sigma_1^2 := \sigma_n^2 := 1.0$. For RZF, $\lambda_\varepsilon:=10^\alpha$, where $\alpha$ changes from $-2$ to $3$ at interval $0.1$.} \label{fig:1jam} \end{figure} \begin{figure}[t!] \psfrag{ZF}[Bl][Bl][0.9]{ZF} \psfrag{RZF}[Bl][Bl][0.9]{RZF} \psfrag{MVDR}[Bl][Bl][0.9]{MVDR} \psfrag{MMSE-DR}[Bl][Bl][0.9]{MMSE-DR} \psfrag{w1}[Bl][Bl][0.9]{$w_1$} \psfrag{w2}[Bl][Bl][0.9]{$w_2$} \psfrag{h0}[Bl][Bl][0.9]{$\signal{h}_0$} \psfrag{o}[Bl][Bl][0.9]{$\signal{0}$} \psfrag{C}[Bl][Bl][0.9]{$C$} \centering \subfigure[]{ \includegraphics[width =.7\textwidth]{fig2a.eps} } \centering \subfigure[]{ \psfrag{MMSE-DR}[Bl][Bl][.9]{\hspace*{1em}MMSE-DR} \includegraphics[width =.7\textwidth]{fig2b.eps} } \caption{A possible situation in two-interference case with $\signal{h}_0:=[0,0,1]^{\sf T}$ ($N:=3$, $J:=2$): (a) a schematic illustration and (b) the projections of the beamformers on $C$ onto the $w_1$-$w_2$ plane for $\sigma_1^2:=\sigma_n^2:=1.0$, $c_1:=c_2:=c_{1,2}:=0.6$, $\signal{h}_1:=[0,\cos(3\pi/5),\sin(3\pi/5)]$, and $\signal{h}_2:=[\cos(5\pi/6),\sin(5\pi/6)\cos(5\pi/6),\sin(5\pi/6)\sin(5\pi/6)]$. For RZF, $\lambda_\varepsilon:=10^\alpha$ with $\alpha$ changing from $-2$ to $3$ at interval $0.05$.} \label{fig:3d} \end{figure} \begin{remark} \label{remark:noiseamp_real} Figure \ref{fig:1jam} illustrates the three cases of $\gamma$ in Theorem \ref{theorem:rzf_real_Nd} for $N:=2$: (a) $\gamma\leq 0$, (b) $\gamma\in (0,1)$, and (c) $\gamma\geq 1$. If $c_1:=0$ for $J:=1$, the $w_1$ components of the MVDR, ZF, RZF, and MMSE-DR beamformers have the same sign as $-\sin\tau$; note here that $\cos\tau>0$. This is clear from the nulling constraint for ZF; see Lemma \ref{lemma:rzf_real} and Proposition \ref{proposition:mmsedr} for the other beamformers. If $c_1\neq 0$, on the other hand, the MVDR, RZF, and MMSE-DR beamformers may have the opposite sign from $-\sin\tau$ (see Figure \ref{fig:1jam}(b)), while only the ZF beamformer sticks to the same sign as $-\sin\tau$. This means that RZF may have a smaller norm than MVDR (and also than ZF), implying that it may suppress the noise better than MVDR. This also applies to the case of $J\geq 2$ as illustrated in Figure \ref{fig:3d}, in which some of the RZF beamformers have a smaller norm than MVDR. The MSE expression given in \eqref{eq:jmse_distortionless} implies that the MSE (under the distortionless constraint) depends on the norm $\norm{\signal{w}}^2$ of the beamformer and the interference leakage $\innerprod{\signal{w}}{\signal{h}_j}$. In the particular case of $J:=1$, MSE is given by the simple sum of $\sigma_n^2\norm{\signal{w}}^2$ and $\sigma_1^2\abs{\innerprod{\signal{w}}{\signal{h}_1}}^2$. To attain a small MSE (under the distortionless constraint), $\signal{w}$ needs to be as close as possible to the origin, and orthogonal to $\signal{h}_1$ as much as possible, simultaneously. The optimal beamformer has the best balance between those two terms, while ZF over-weights the second one. Indeed, RZF may attain better noise-and-interference suppression performance than MVDR for multiple interfering sources, as shown in Section \ref{sec:exp}. \end{remark} \subsubsection{Proof of Theorem \ref{theorem:rzf_complex_Nd}} The claim can be verified by proving the following lemma due to the same arguments as given in the proof of Theorem \ref{theorem:rzf_real_Nd}. \begin{lemma} \label{lemma:rzf_complex} Let $N:=2$, $J:=1$, $\signal{h}_0:=[0,1]^{\sf T}$, $\signal{h}_1:=[\cos \tau, z]^{\sf T}:=[\cos \tau,\sin\tau e^{i\phi_z}]^{\sf T}$ with $\tau\in[0,\pi/2)$ and $\phi_z\in[0,2\pi)$, $\sigma_0^2>0$, $\sigma_1^2>0$, $\sigma_n^2>0$, and $c_1:=\abs{c_1}e^{i\phi_c}\in\{c\in {\mathbb C}\mid \abs{c}\leq \sigma_0 \sigma_1\}$, $\phi_c\in[0,2\pi)$.\footnote{One may consider the more general case of $\cos \tau e^{i\phi}$ for some $\phi\in[0,2\pi)$, instead of $\cos \tau$ of zero phase. However, the results in the theorem (excluding the expression of $\signal{w}_{\rm RZF}$) are independent of the choice of $\phi$, and we can thus assume that $\phi:=0$ without any essential loss of generality.} The RZF beamformer is then given by \begin{equation} \signal{w}_{\rm RZF}= \left[ \begin{array}{c} -\dfrac {\cos \tau\left[(\sigma_1^2+\lambda_{\varepsilon})z^* + c_1\right]} {(\sigma_1^2+\lambda_{\varepsilon}) \cos^2\tau + \sigma_n^2} \\ 1 \end{array} \right], \label{eq:theorem_wrzf} \end{equation} for which the MSE is given by \eqref{eq:theorem_mse_complex}. \begin{enumerate} \item[(i)] Assume that $\delta_2=0$ ($\Rightarrow \delta_1=0$), where $\delta_1$ and $\delta_2$ are defined in \eqref{eq:delta1} and \eqref{eq:delta2}, respectively. Then, the MSE is given by $\sigma_n^2 (\tan^2\tau+1)$, which is constant in $\lambda_{\varepsilon}$. \item[(ii)] Assume that $\delta_2\neq0$. \begin{enumerate} \item If $\gamma:=\dfrac{\delta_1\sigma_n^2\tan\tau}{\abs{\delta_2}^2} \leq 0$ ($\Leftrightarrow \delta_1 \tan\tau\leq 0$), ${\rm MSE}(\lambda_\varepsilon)$ is monotonically decreasing, and the ZF beamformer is optimal in the MSE sense. \item If $\gamma \geq 1$, ${\rm MSE}(\lambda_\varepsilon)$ is monotonically increasing, and thus is minimized by $\lambda_\varepsilon:=0$. \item If $\gamma \in (0,1)$, ${\rm MSE}(\lambda_\varepsilon)$ is minimized by \eqref{eq:theorem_lambda_comp}. \end{enumerate} \end{enumerate} \end{lemma} {\it Proof:} The claim can be verified in an analogous way to the proof of Lemma \ref{lemma:rzf_real}. \hspace*{\fill} $\Box $ \subsubsection{Proof of Theorem \ref{theorem:rzf_superiority}} The former part is clear from the proof of Lemma \ref{lemma:rzf_real}; note that the necessary and sufficient condition $0<\delta_1\tan\tau<\abs{\delta_2}^2$ implies $\delta_2\neq 0$ and $\dfrac{\delta_1\sigma_n^2\tan\tau}{\abs{\delta_2}^2} \in (0,1)$. To verify the latter part (the sufficient condition), we assume that $c_1\neq 0$ and $\sin\tau\cos(\phi_c+\phi_z)<0$. Then, we immediately have \begin{align} \delta_1\tan\tau =&~ (\sigma_n^2 \tan\tau - \abs{c_1}\cos\tau\cos(\phi_c+\phi_z))\tan\tau \nonumber\\ =&~\sigma_n^2 \tan^2\tau - \abs{c_1}\sin\tau\cos(\phi_c+\phi_z)>0. \end{align} Observing that \begin{equation} \abs{\delta_2}^2= \delta_1^2 + (\abs{c_1}\cos\tau\sin(\phi_c+\phi_z))^2, \end{equation} we can verify that \begin{align} \hspace*{-1.5em}&0< -\abs{c_1}\cos^2\tau\frac{\cos(\phi_c+\phi_z)}{\sin\tau} + \frac{ (\abs{c_1}\cos\tau\sin(\phi_c+\phi_z))^2}{\delta_1\tan\tau} \nonumber\\ \hspace*{-2em}&\Leftrightarrow \sigma_n^2< \frac{\delta_1}{\tan\tau} + \frac{ (\abs{c_1}\cos\tau\sin(\phi_c+\phi_z))^2}{\delta_1\tan\tau} \nonumber\\ \hspace*{-2em}&\Leftrightarrow \sigma_n^2< \frac{\abs{\delta_2}^2}{\delta_1\tan\tau}, \end{align} from which it follows readily that $\delta_2\neq 0$ and $\dfrac{\delta_1\sigma_n^2\tan\tau}{\abs{\delta_2}^2}<1$. \subsubsection{Proof of Theorem \ref{theorem:complex_mse}} In an analogous way to the proof of Theorem \ref{theorem:real_mse}, the claim is verified with the following proposition. \begin{proposition} \label{proposition:mmsedr_complex} Under the same settings as in Lemma \ref{lemma:rzf_complex}, the MMSE-DR and the MVDR beamformers are given respectively by \begin{align} \signal{w}_{\rm MMSE\mathchar`-DR} =&~ \left[ \begin{array}{c} -\dfrac {\sigma_1^2 z^* \cos\tau} {\sigma_1^2\cos^2\tau + \sigma_n^2} \\ 1 \end{array} \right], \label{eq:mmsedr_2dim}\\ \signal{w}_{\rm MVDR} =&~ \left[ \begin{array}{c} -\dfrac{\cos\tau (\sigma_1^2 z^* + c_1)} {\sigma_1^2\cos^2\tau + \sigma_n^2} \\ 1 \end{array} \right] \nonumber\\ = &~ \signal{w}_{\rm MMSE\mathchar`-DR}- \left[ \begin{array}{c} \dfrac {c_1 \cos\tau} {\sigma_1^2\cos^2\tau + \sigma_n^2} \\ 0 \end{array} \right]. \label{eq:mvdr_2dim} \end{align} \end{proposition} {\it Proof:} The claim can be verified in an analogous way to the proof of Proposition \ref{proposition:mmsedr}. \hspace*{\fill} $\Box $ \begin{remark} \label{remark:noiseamp_complex} In the case of $c_1:=0$, the $w_1$ components of the MVDR, ZF, RZF, and MMSE-DR beamformers have the same ``phase'' as $-\cos\tau z^*$ (see Lemma \ref{lemma:rzf_complex} and Proposition \ref{proposition:mmsedr_complex}; cf.~Remark \ref{remark:noiseamp_real}). If $c_1\neq 0$, on the other hand, the MVDR, RZF, and MMSE-DR beamformers have different phases in general from $-\cos\tau z^*$, while the ZF beamformer sticks to the same phase as $-\cos\tau z^*$. Hence, RZF, which resides between ZF and MVDR, possibly has a strictly smaller norm than those two ends, as in the real case. This implies that RZF has a potential to suppress the noise, as well as the interference, more efficiently than MVDR, because the impact of noise on the MSE is proportional to $\norm{\signal{w}}^2$ (see \eqref{eq:jmse_distortionless} in Lemma \ref{lemma:mse}). Compared to ZF, RZF with an appropriate $\lambda_\varepsilon$ can achieve a significantly better noise suppression performance while suppressing the interference at the same level approximately, as shown in Section \ref{sec:exp}. \end{remark} \begin{figure}[t!] \psfrag{c}[Bl][Bl][0.9]{$\rho_j$} \centering \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[ $N=16$, $J=7$]{ \includegraphics[width =0.52\textwidth]{fig3a.eps}} & \hspace*{-2em} \subfigure[ $N=64$, $J=19$]{ \includegraphics[width =0.52\textwidth]{fig3b.eps}} \end{tabular} \vspace{-5pt} \caption{Performances across $\rho_j$ for $\beta:=0.8$, $\varepsilon_\rho:=0.1$, and $\varepsilon_\phi:=\pi/12$ under SNR 0 dB and SIR 0 dB. } \label{fig:change_rhoj} \end{figure} \begin{figure}[t!] \psfrag{e}[Bl][Bl][0.9]{$\varepsilon$} \centering \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[ $N=16$, $J=7$]{ \includegraphics[width = 0.52\textwidth]{fig4a.eps}} & \hspace*{-2em} \subfigure[ $N=64$, $J=19$]{ \includegraphics[width =0.52\textwidth]{fig4b.eps}} \end{tabular} \vspace{-5pt} \caption{Sensitivity of RZF to the parameter $\varepsilon$ ($\rho_j:=0.6$, $\beta:=0.8$, $\varepsilon_\rho:=0.1$, $\varepsilon_\phi:=\pi/12$, SNR 0 dB, SIR 0 dB).} \label{fig:rzf} \end{figure} \begin{figure}[t!] \centering \vspace*{5pt} \psfrag{b}[Bl][Bl][0.9]{$\beta$} \psfrag{c}[Bl][Bl][0.9]{$\varepsilon_\rho$} \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[]{ \includegraphics[width = 0.52\textwidth]{fig5a.eps}} & \hspace*{-2em} \subfigure[]{ \includegraphics[width =0.52\textwidth]{fig5b.eps}} \end{tabular} \vspace{-5pt} \caption{Sensitivity of the A-MMSE beamformer to the errors $\varepsilon_\rho$ and $\beta$ ($\rho_j:=0.6$, SNR 0 dB, SIR 0 dB).} \label{fig:approximate_mmse} \end{figure} \section{Simulation Study of RZF Beamformer for Multiple Interference Case} \label{sec:exp} The basic performance of the RZF beamformer is studied with toy models, and its efficacy is then shown in application to brain activity reconstruction with EEG measurements. We define SNR and the signal to interference ratio (SIR) as the ratios of the power of desired signal projected onto sensors to the power of noise and interference counterparts, respectively; i.e., SNR $:=\sum_{i=1}^{N}E(\abs{h_{0,i}s_0(k)}^2)/\sum_{i=1}^{N}E(\abs{n_i(k)}^2)$, and ${\rm SIR}:=\sum_{i=1}^{N}E(\abs{h_{0,i}s_0(k)}^2)/$ $\sum_{i=1}^{N}E(|\sum_{j=1}^{J}h_{j,i}s_j(k)|^2)$. The parameter $\epsilon$ is tuned manually by grid search for each setting in all simulations but the one which studies the sensitivity of RZF to the value of $\epsilon$ to show the potential performance of RZF. \subsection{Basic Performance with Toy Model} \label{subsec:communication} The uniform linear array is considered with the array response $\signal{h}_j:= \signal{h}(\theta_j):= \frac{1}{\sqrt{N}}[1,e^{2\pi i\frac{d}{\lambda} \cos\theta_j}, \cdots,e^{2\pi i (N-1) \frac{d}{\lambda}\cos\theta_j}]^{\sf T}\in{\mathbb C}^N$ at the receiver, where $\theta_j\in[0,\pi]$ is the direction of arrival (DOA) of the $j$th signal, $\lambda$ is the carrier wavelength, and $d:=\lambda/2$ is the antenna spacing \cite{trees02_book}. Two scenarios are considered regarding the array size: (a) $N=16$ and $J=7$ (middle array size), and (b) $N=64$ and $J=19$ (large array size). In each setting, we let $\{\theta_j\}_{j=0}^J = \{(j+1)\pi/(J+2)\}_{j=0}^J$ with $\theta_0 := \lceil (J+1)/3 \rceil\pi/(J+2)$. The desired signal is drawn from the i.i.d.~standard complex Gaussian distribution, i.e., $s_0(k)\sim \mathcal{CN}(0,1)$. For convenience in controlling the correlation between $s_0(k)$ and $s_j(k)$, the interfering signals are generated as \begin{equation} s_j(k):=\dfrac{\sigma_j e^{i\phi_j}}{\sqrt{1+\sigma_v^2}} (s_0(k) + v_j(k)), \label{eq:sjk_generation} \end{equation} where $\sigma_j^2:=E(\abs{s_j(k)}^2)$, $v_j(k)\sim \mathcal{CN}(0,\sigma_v^2)$, and the relative phase of the $j$th source is set to $\phi_j:=0$. In this case, the correlation coefficient between $s_0(k)$ and $s_j(k)$ is given by \begin{equation} \rho_j:=c_j/(\sigma_0 \sigma_j) = e^{i\phi_j}/\sqrt{1 + \sigma_v^2}\in\{c\in{\mathbb C}\mid \abs{c}\in(0,1]\}. \end{equation} The desired-signal power is fixed to $\sigma_0^2:=1$, and the powers of the interference and noise are changed according to the SIR and SNR, respectively. \begin{figure}[t!] \centering \vspace*{5pt} \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[$N=16$, $J=7$, SIR $=$ 0 dB]{ \includegraphics[width = 0.52\textwidth]{fig6a.eps}} & \hspace*{-2em} \subfigure[$N=64$, $J=19$, , SIR $=$ 0 dB]{ \includegraphics[width =0.52\textwidth]{fig6b.eps}} \end{tabular} \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[$N=16$, $J=7$, SIR $=$ 10 dB]{ \includegraphics[width = 0.52\textwidth]{fig6c.eps}} & \hspace*{-2em} \subfigure[$N=64$, $J=19$, SIR $=$ 10 dB]{ \includegraphics[width =0.52\textwidth]{fig6d.eps}} \end{tabular} \vspace{-5pt} \caption{Performances across SNR for $\rho_j:=0.6$, $\beta:=0.8$, $\varepsilon_\rho:=0.1$, $\varepsilon_\phi:=\pi/12$.} \label{fig:different_snr} \end{figure} \begin{figure}[t!] \centering \vspace*{5pt} \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[$N=16$, $J=7$, SNR $=$ 0 dB]{ \includegraphics[width = 0.52\textwidth]{fig7a.eps}} & \hspace*{-2em} \subfigure[$N=64$, $J=19$, SNR $=$ 0 dB]{ \includegraphics[width =0.52\textwidth]{fig7b.eps}} \end{tabular} \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[$N=16$, $J=7$, SNR $=$ 10 dB]{ \includegraphics[width = 0.52\textwidth]{fig7c.eps}} & \hspace*{-2em} \subfigure[$N=64$, $J=19$, SNR $=$ 10 dB]{ \includegraphics[width =0.52\textwidth]{fig7d.eps}} \end{tabular} \vspace{-5pt} \caption{Performances across SIR for $\rho_j:=0.6$, $\beta:=0.8$, $\varepsilon_\rho:=0.1$, $\varepsilon_\phi:=\pi/12$.} \label{fig:different_sir} \end{figure} A fresh look at the MSE expression in \eqref{eq:mse_cost_dr} may suggest that one might ``exploit'' the temporal correlations to reduce the MSE further, rather than bounding the leakage of interference. To see whether this active approach works, we consider an approximate MMSE (A-MMSE) beamformer under the assumption that some erroneous estimates $\hat{c}_j\in {\mathbb C}$ and $\hat{\sigma}_0^2>0$ of the correlation $c_j(:=E[s_0^*(k)s_j(k)])$ and the signal power $\sigma_0^2(:=E[\abs{s_0(k)}^2])$ are available. To be precise, the erroneous estimates $\hat{\sigma}_0^2$ and $\hat{c}_j=\abs{\hat{c}_j}e^{i \hat{\phi}_j}$ are generated, respectively, by $\hat{\sigma}_0^2:= \beta\sigma_0^2$ and $\abs{\hat{c}_j} := \abs{c_j} + \varepsilon_\rho \sigma_0 \sigma_j$, and $\hat{\phi}_j:=\phi_j + \varepsilon_\phi$, where $\beta\in(0,+\infty)$, $\varepsilon_\rho\in(-\rho_j,1-\rho_j)$, and $\varepsilon_\phi\in(-\pi,\pi]$. In this case, being free from the distortionless constraint, the MSE $J_{{\rm MSE}}(\signal{w})$ in \eqref{eq:mse_cost} can be approximated by $\hat{J}_{{\rm MSE}}(\signal{w}) := \signal{w}^{\sf H} \signal{R} \signal{w} + \hat{\sigma}_0^2 (1-\signal{w}^{\sf H}\signal{h}_0-\signal{h}_0^{\sf H}\signal{w}) - \sum_{j=1}^{J} (\hat{c}_j \signal{w}^{\sf H}\signal{h}_j + \hat{c}_j^* \signal{h}_j^{\sf H}\signal{w})$, of which the minimizer is given by $\signal{w}_{\rm A\mathchar`-MMSE}:= \signal{R}^{-1} \left(\hat{\sigma}_0^2\signal{h}_0 + \sum_{j=1}^{J} \hat{c}_j \signal{h}_j\right)$. The matrix $\signal{R}$ is computed from 8,000 samples for all the beamformers. Figure \ref{fig:change_rhoj} depicts the performance of the beamformers under different temporal-correlations for SNR 0 dB and SIR 0 dB. It is seen that RZF exhibits remarkably better performances than MVDR in the strong correlation cases (cf.~Remark \ref{remark:theorem_complex_mse}.5). See Section \ref{subsec:discussions} for discussions about the gap between the MSEs of RZF and MMSE-DR. Figure \ref{fig:rzf} shows how the performance of RZF changes according to the choice of $\varepsilon$ for SNR 0 dB and SIR 0 dB. It is seen that a wide range of the $\varepsilon$ parameter yields lower MSEs than the conventional MVDR and ZF beamformers. Figure \ref{fig:approximate_mmse} shows how the performance of A-MMSE changes due to the estimation errors in $\hat{c}_j$ and $\hat{\sigma}_0^2$ for $N=16$, SNR 0 dB, and SIR 0 dB. In Figure \ref{fig:approximate_mmse}(a), $\varepsilon_\phi:=0$ and $\beta:=1$. In Figure \ref{fig:approximate_mmse}(b), $\varepsilon_\rho:=\varepsilon_\phi:=0$. In contrast to the case of RZF, the performance of A-MMSE degrades by slight errors in the estimates. Figures \ref{fig:different_snr} and \ref{fig:different_sir} depict the performances for $\rho_j:=0.6$ under different SNR conditions with SIR 0 dB and 10 dB, and under different SIR conditions with SNR 0 dB and 10 dB, respectively. The results show that RZF yields near optimal performances in the case of $N:=16$ (excluding the low-SIR case in Figure \ref{fig:different_sir}(c)), and that it outperforms MVDR and ZF significantly over the whole settings in the case of $N:=64$. Note here that the performance of RZF for $N:=64$ is suboptimal because the large $J$ makes the minimal angular separation between the desired interfering sources be rather small. Comparing the performances of RZF for SIR $=$ 0 dB and 10 dB in Figure \ref{fig:different_snr}, the tendency is nearly the same; precisely, for high SNR, closer performance to MMSE is achieved in the case of SIR $=$ 10 dB than the case of SIR $=$ 0 dB. Turning our attention to Figure \ref{fig:different_sir}, we observe that (i) the maximum gain to MVDR is 10 dB approximately for SNR $=$ 0 dB while it is 20 dB approximately for SNR $=$ 10 dB, and (ii) MSE of RZF increases towards that of ZF as SIR decreases, more clearly for SNR $=$ 10 dB. The first observation is due to the fact that RZF as well as ZF benefits significantly from the reduction of noise. The second one is also reasonable since the zero-forcing strategy (i.e., $\epsilon:=0$) will be optimal as the interference power approaches infinity. \subsection{EEG Application} \label{subsec:eeg} Using the interpretation of the model in \refeq{eq:eeg_model} as the forward model used to solve the EEG inverse problem (\emph{cf.} Section~\ref{sec:prelim}), we consider the situation when there are $J+1$ dipole sources $(J:=29)$ of brain activity and the signals are measured by an array of $N:=128$ EEG sensors. HydroCel Geodesic Sensor Net model is used as a realistic EEG cap layout. The source signals and forward model were generated using SupFunSim library \cite{rykaczewski21}, which utilizes FieldTrip toolbox \cite{FieldTrip2011} for generation of volume conduction model and leadfields. The activity $s_0(k)$ of the desired source is generated by an autoregressive (AR) model of order $6$, where the coefficients for each order are set to $0.2$. The interfering activities are generated by \eqref{eq:sjk_generation} with $\phi_j:=0$. The source activities are supposed to change in time, while their positions and orientations are assumed known and remain the same during the measurement period. The following two cases are considered: the low correlation case ($\rho_j := 0.5$) and the high correlation case ($\rho_j := 0.95$). Throughout the experiments, the power of the desired signal is fixed to $\sigma_0^2:=1$, and those of the interference and noise are changed depending on SNR and SIR, respectively. The relaxation parameter $\varepsilon$ of RZF is optimized for each SNR and SIR. \begin{figure}[t!] \centering \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[$\rho_j := 0.5$]{ \includegraphics[width = 0.52\textwidth]{fig8a.eps}} & \hspace*{-2em} \subfigure[$\rho_j := 0.95$]{ \includegraphics[width =0.52\textwidth]{fig8b.eps}} \end{tabular} \caption{Performances for EEG application under low and high correlations (SIR $0$ dB).} \label{fig: SNR_MSE} \end{figure} \begin{figure}[t!] \centering \centerline{\includegraphics[width = 0.52\textwidth]{fig9.eps}} \caption{Performance in EEG application under low correlation $\rho_j := 0.5$ (SNR $0$ dB).} \label{fig: SIR_MSE} \end{figure} Figure \ref{fig: SNR_MSE} shows the results for SIR $0$ dB under different SNR conditions in the cases of (a) low correlation ($\rho_j:=0.5$) and (b) high correlation ($\rho_j:=0.95$). Figure \ref{fig: SIR_MSE} shows the results for SNR $0$ dB under different SIR conditions in the case of low correlation ($\rho_j:=0.5$). (The results for $\rho_j:=0.95$ are omitted as the results are similar.) It is seen that the RZF beamformer attains significant gains compared to the MVDR and ZF beamformers. It is also seen that its performance is fairly close to the theoretical bound (MMSE-DR) in the low correlation case with low SIR. See Section \ref{subsec:discussions} for discussions about the MSE gap between RZF and MMSE-DR together with that for the wireless-network case. Figure \ref{fig: bar} shows the powers of noise and interfering activities remaining in the beamformer output for SNR $ -2$ dB and SIR $0$ dB. It is seen that RZF attains an excellent tradeoff; it attains reasonably small noise-leakage by allowing some slight (invisible) leakage of the interfering activities. In Figure \ref{fig: bar}(a), the total leakage of RZF is slightly lower than the noise leakage of MVDR (see Remark \ref{remark:noiseamp_real}). Figure \ref{fig: epsilon_MSE}(a) plots the MSE performance of RZF for each relaxation parameter $\varepsilon$ under SNR $-2$ dB, SIR $0$ dB, and $\rho_j:=0.5$. Within the range of $ 1.0 <\varepsilon< 1.0 \times 10^{3}$, the MSE of RZF is below $-7.5$ dB. This implies that RZF is reasonably insensitive to the choice of $\varepsilon$. Figure \ref{fig: epsilon_MSE}(b) provides more precise information, plotting the power of noise/interference leakage contained in the beamformer output for different $\varepsilon$ values. It is seen that both noise and interference are suppressed simultaneously by RZF for an appropriately chosen $\varepsilon$. This supports the results of Figure \ref{fig: bar}(a). \begin{figure}[t!] \centering \subfigure[$\rho_j := 0.5$]{\includegraphics[width=.3\textwidth]{fig10a.eps}} \subfigure[ $\rho_j := 0.95$]{\includegraphics[width=.3\textwidth]{fig10b.eps}} \caption{Powers of noise/interference leakage for EEG application under low and high correlations (SNR $-2$ dB, SIR $0$ dB).}\medskip \label{fig: bar} \setlength{\belowcaptionskip}{-1em} \vspace{-0.5em} \end{figure} \begin{figure}[t!] \centering \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[]{ \psfrag{e}[Bl][Bl][0.9]{$\varepsilon$} \includegraphics[width = 0.52\textwidth]{fig11a.eps}} & \hspace*{-2em} \subfigure[]{ \psfrag{a}[Bl][Bl][0.9]{$\varepsilon$} \includegraphics[width =0.52\textwidth]{fig11b.eps}} \end{tabular} \caption{Sensitivity of RZF to the parameter $\varepsilon$ for EEG application ($\rho_j := 0.5$, SNR $-2$ dB, SIR $0$ dB).} \label{fig: epsilon_MSE} \end{figure} We now consider the adaptive implementations: RZF implemented by DDAA, and MVDR and ZF implemented by CNLMS \cite{apolinario1998constrained}. The step sizes for all online algorithms are set to $0.1$. The parameter of the DDAA is set to $\alpha_k:=0.5$, $\forall k\in{\mathbb N}$ (see the appendix). Figure \ref{fig: Iter_MSE}(a) plots the steady-state MSE of each algorithm for SIR $0$ dB and $\rho_j:=0.5$ under different SNR conditions. One can see that each beamformer is successfully implemented adaptively by each adaptive algorithm. Figure \ref{fig: Iter_MSE}(b) plots the learning curves for the specific case of SNR $0$ dB, where each point is computed by averaging the squared errors over 300 independent trials. (For visual clarity, the MSE values are further averaged over the previous 30 iterations.) It can be seen that the MSEs of the adaptive algorithms for the RZF and ZF beamformers converge reasonably fast to those of the analytical solutions, respectively. In contrast, MVDR implemented by CNLMS converges slowly due to no use of the channel information of the interfering activities. \begin{figure}[t!] \centering \begin{tabular}{cc} \hspace*{-1.5em} \subfigure[steady-state performance]{ \includegraphics[width = 0.52\textwidth]{fig12a.eps}} & \hspace*{-2em} \subfigure[learning curves under SNR $0$ dB]{ \includegraphics[width =0.52\textwidth]{fig12b.eps}} \end{tabular} \caption{Performances of adaptive implementations for EEG application under low correlation $\rho_j := 0.5$ (SIR $0$ dB). RZF implemented with DDAA, and MVDR and ZF implemented both with CNLMS.} \label{fig: Iter_MSE} \end{figure} We remark finally that the RZF beamformer may be also used when surface Laplacian-processed signals are considered instead of the raw EEG signal to enhance spatial resolution \cite{murzin13,kayser15}. In such a case, the channel matrix is replaced by the surface Laplacian matrix and the covariance matrix $\signal{R}$ is replaced by the covariance matrix of the Laplacian-treated signal. \subsection{Discussions and Remarks} \label{subsec:discussions} \begin{figure}[t!] \centering \psfrag{g}[Bc][Bl][0.9]{$\gamma$} \psfrag{i}[Bc][Bl][0.9]{Interfering source} \centerline{\includegraphics[width =0.52\textwidth]{fig13.eps}} \caption{An example of the $\gamma$ value for each interfering source in the EEG application under low correlation $\rho_j := 0.5$ (SNR $0$ dB, SIR $0$ dB).} \label{fig:gamma_values} \end{figure} Figure \ref{fig:gamma_values} plots the $\gamma$ values for different sources in the setting corresponding to Figure \ref{fig: SIR_MSE} with SIR 0 dB. It is seen that only 9 (out of 28) sources have the $\gamma$ values within the range $(0,1)$; see \eqref{eq:mse_rzf_real} in Theorem \ref{theorem:real_mse}. To see whether those interfering sources which have $\gamma$ outside the range $(0,1)$ cause the MSE gaps between RZF and MMSE-DR, we removed all such interfering sources and evaluated the MSE performances only with the remaining sources having $\gamma\in(0,1)$ under $\rho_j:=0.5$, SNR $-5$ dB, and SIR $0$ dB. The gap then droped, from $3.4$ dB, down to $1.5$ dB approximately. We also tested with the same number of {\it randomly picked} sources removed. In this case, the gap was no less than $2.8$ dB. This indicates that those sources having $\gamma\not\in(0,1)$ would be a main cause of the MSE gaps. In the simulation results presented in Section \ref{subsec:communication}, there are some visible gaps between the MSEs of RZF and MMSE-DR in Figure \ref{fig:change_rhoj}(b). In the case of complex signals, Theorem \ref{theorem:complex_mse} suggests the existence of another factor $\left(1-\abs{\delta_1/\delta_2}^2\right) \sigma_n^4\tan^2\tau/(\sigma_1^2\cos^2\tau+\sigma_n^2)$ that may cause the MSE gap. Indeed, $\gamma$ is a function of $\delta_1$, as well as the others. Referring to \eqref{eq:delta1}, the sign of $\delta_1$ depends on the phase $\phi_c$ of the {\it temporal} correlation $c_1$. This implies that the MSE of RZF may change significantly due to the phase (or the sign in particular) of $c_1$. Nevertheless, the plots for RZF are nearly symmetric for the positive and negative values of $\rho_j(:=c_j/(\sigma_0\sigma_j))$. In addition, we actually tested different values of $\phi_j$s, which yielded no visible differences in MSE. This would be because the phase $\phi_{z_j}$ of the {\it spatial} correlation $z_j:=\innerprod{\signal{h}_0}{\signal{h}_j}$ is quite random among different sources. \section{Conclusion} We studied the RZF beamformer, which minimizes the output variance under the constraints of bounded interference leakage and undistorted desired signal, in the presence of temporally correlated interference. The (quadratic) {\it relaxed zero-forcing} constraint alleviates the gap between the output variance (available) and MSE (unavailable) without amplifying the noise. An adaptive implementation of the RZF beamformer based on the dual-domain adaptive algorithm was also presented. We analyzed the MSE of RZF for the single-interference case and derived the formula of MSE in terms of the spatio-temporal correlations between the desired and interfering signals as well as the variances of noise and interference, clarifying that RZF achieves the minimum MSE under the conditions. The presented analysis gave useful insights into the multiple-interference case, as discussed in the experimental section. Numerical examples showed the remarkable advantages of RZF over the MVDR and ZF beamformers. The RZF beamformer also achieved near-optimal performance in some cases. We conclude the present study by stating that the RZF beamformer will be useful particularly for the EEG brain activity reconstruction because (i) it enjoys superior performance by mitigating the interfering sources efficiently, (ii) it includes the MVDR and ZF beamformers as special cases, and (iii) it can be implemented efficiently by DDAA.
{'timestamp': '2021-09-14T02:15:42', 'yymm': '2109', 'arxiv_id': '2109.05342', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05342'}
arxiv
\section{Introduction} Multiple recent papers have attempted to pinpoint precisely what components of multilingual language models enable cross-lingual transfer. \citet{pires_HowMultilingual_2019} show that although wordpiece overlap tends to improve cross-lingual transfer performance, even languages with different scripts (and no shared subwords) may enable zero-shot transfer.~\citet{wu_betobentz_2019} report similar results on a wider range of tasks. \citet{artetxe_CrosslingualTransferability_2020} show that neither a shared vocabulary nor joint multilingual pre-training are necessary to train successful multilingual models. \citet{k_CrossLingualAbility_2020} find that model depth is a contributor to transfer performance, but that reducing the number of self-attention heads does not have much of an effect. Our starting point is~\citet{dufterIdentifyingNecessaryElements2021}, who claim that a) multilingual compression is caused by forced parameter sharing across languages, and that b) positional encodings play a significant role in the creation of a multilingual space, even in the absence of shared subwords and shared special tokens, like delimiters. \begin{table}[] \scriptsize \centering \begin{tabular}{lll} \toprule {\bf Sinusoidal}&See \S2&\citet{vaswani_attention_2017} \\ {\bf Absolute}&$((w_i+p_i)W^{Q,1})$&\citet{devlin_bertpretraining_2019}\\ &$((w_j+p_j)W^{K,1})^{\top}$&\\ {\bf TUPE}&$(x_i^lW^{Q,l})(x_j^lW^{K,l})^{\top} +$&\citet{keRethinkingPositionalEncoding2020}\\&$ (p_iU^Q)(p_jU^K)^{\top}$\\ {\bf TUPE}(r)&\ldots $+b_{j-i}$ & \\ {\bf Relative}(k)&$(x_iW^Q)(x_jW^K + a_{ij})^{\top}$&\citet{shawSelfAttentionRelativePosition2018}\\ {\bf Relative}(k/q)&$(x_iW^Q + a_{ij})$&\citet{huangImproveTransformerModels2020}\\&$(x_jW^K + a_{ij})^{\top}$&\\ \bottomrule \end{tabular} \caption{We compare six positional encodings and their impact on cross-lingual generalization in multilingual language models} \label{tab:embeds} \end{table} \paragraph{Contributions} We build on \citet{dufterIdentifyingNecessaryElements2021} and demonstrate, through a series of experiments on synthetic and real data, that the choice of positional encoding mechanism has a significant effect on cross-lingual model performance: While many positional encodings have been proposed in monolingual settings as improvements over sinusoidal or absolute positional encodings, originally proposed in \citet{vaswani_attention_2017} and \citet{devlin_bertpretraining_2019}, including untied positional encodings (TUPE; \citet{keRethinkingPositionalEncoding2020}) and relative positional encodings \cite{shawSelfAttentionRelativePosition2018,huangImproveTransformerModels2020}, none of these better facilitate cross-lingual compression or sharing. In fact, multilingual language models trained with untied or relative positional encodings exhibit {\em much worse} cross-lingual performance. We show that this is because sinusoidal embeddings facilitate compositionality, which we argue is particularly important for cross-lingual compression. We present a method for quantifying the compositionality of positional encodings, and find additional evidence for this hypothesis in word-position correlations and ablation studies. We are, to the best of our knowledge, the first to show this asymmetry between monolingual and multilingual language model training. Our experiments rely on the protocols in \citet{dufterIdentifyingNecessaryElements2021}, but in addition to simple experiments with their Bible data, we also replicate all our experiments on Wikipedia data. Rather than relying on deterministic perturbations of data, as in \citet{dufterIdentifyingNecessaryElements2021} and \citet{sinha_maskedlanguage_2021}, we make novel use of Galactic Dependencies \cite{wang_galacticdependencies_2016} in our experiments. Based on our experiments, we recommend caution when adopting methods developed for monolingual language models when training multilingual models, as well as that future work on positional encoding mechanisms also provides evaluations in multilingual settings. \section{Positional encodings} \label{sec:pos} \label{ssec:pos_bg} Positional encodings have been a mainstay of non-autoregressive transformer-based models right since~\citet{vaswani_attention_2017} first proposed the transformer architecture. The motivation being that given that transformers\footnote{Note that we use "transformers" as shorthand for transformer encoders used for masked language modelling.} are order-invariant (as opposed recurrent or convolutional networks), there must be some injection of word order into the encoder. Rather than using conventional "embeddings", \citet{vaswani_attention_2017} use fixed {\bf sinusoidal} position encodings, where each dimension characterises a sinusoidal waveform of a fixed frequency. Specifically, each encoding $p$ is given as: \begin{align*} p_{(pos,2i)} &= sin(pos/10000^{2i/d_{\mathrm{model}}})\\ p_{(pos,2i+1)} &= cos(pos/10000^{2i/d_{\mathrm{model}}}) \end{align*} where $pos$ is the position and $i$ is the dimension. They add these encodings to token representations before passing the sum to the first layer of the self-attention mechanism. Several alternatives to sinusoidal encodings have been proposed since \citet{vaswani_attention_2017}. Most multilingual models tend to use BERT-style~\citep{devlin_bertpretraining_2019} learnt {\bf absolute} positional encodings, where a unique vector is learned and assigned to each position; these vectors are then added to word representations before being passed to the self-attention mechanism. As an alternative to such position representations, where every position is represented by a unique vector, \textbf{relative} positional encodings have been proposed~\citep{shawSelfAttentionRelativePosition2018,huangImproveTransformerModels2020}. Rather than assigning representations to tokens based on their position, relative positional encoding involves assigning representations to position-position pairs; typically, these encodings are calculated separately and added to the attention matrix. We evaluate both the encodings proposed in \citet{shawSelfAttentionRelativePosition2018} and the encodings proposed in \cite{huangImproveTransformerModels2020} in our experiments below. \citet{he_debertadecodingenhanced_2021} propose eliminating position-position correlations, and using separate parameters for word and position representations; \citet{wang_selfattentionstructural_2019a} propose using dependency trees instead of raw sequential positions. \citet{keRethinkingPositionalEncoding2020} recommend eliminating the addition operation in BERT-style representations; they argue that word-position correlations are effectively nil, and that the addition introduces unnecessary noise. We evaluate two {\bf untied} positional encodings proposed in \citet{keRethinkingPositionalEncoding2020} (TUPE). TUPE modifies absolute representations by a) untying word-position correlations; b) using a separate set of parameters for positional attention and c) untying \texttt{[CLS]} tokens from positions. We refer to recent surveys~\citep{dufterPositionInformationTransformers2021,wangPOSITIONEMBEDDINGSBERT2021} for a more detailed treatment of position encoding methods. We provide a summary of our methods in Table~\ref{tab:embeds}. $W^{Q,l}$ and $W^{K,l}$ represent the query/key weights for the attention mechanism at some layer $l$, and $a_{ij}$ or $b_{j-i}$ are learnt vectors corresponding to the offset $j - i$. Note that the untied position-position term $(p_iU^Q)(p_jU^K)^\top{}$ is added at every layer. The above positional encodings have been introduced in the context of monolingual pretrained language models, and there has been only a limited amount of work addressing the effect of positional encodings on multilingual models. \citet{liu_improvingzeroshot_2020} find that positional information tends to hurt machine translation, as the encoder learns a word-order bias towards the source languages.\footnote{The results in \citet{liu_improvingzeroshot_2020} apply to zero-shot generalization of fine-tuned, task-specific models and not to how multilingual language models are pretrained. In their experiments, they rely on a pretrained language model with absolute positional encodings. In fact, what they show is that freezing these during fine-tuning helps cross-lingual zero-shot generalization.} \citet{artetxe_CrosslingualTransferability_2020} find that language-specific positional representations help in an adapter-based training scenario. \citet{ding_selfattentioncrosslingual_2020} attempt to account for structural differences between languages by using bracketing transduction grammar trees to reorder position labels (and find that it helps). \citet{liu_importanceword_2020} find that models that are relatively agnostic to word-order tend to perform better in cross-lingual settings; they hypothesise that large multilingual encoders, being trained on languages with drastic differences in word orders, tend to have order-agnostic positional encodings, and thus discourage fine-tuning positional encodings downstream. Contemporaneous with this work,~\citet{sinha_maskedlanguage_2021} show that positional information is important for monolingual models even given unnatural, randomly shuffled word ordering. \citet{dufterIdentifyingNecessaryElements2021} present a set of experiments training smaller language models on bilingual corpora, consisting of the same corpus in English and "fake-English", which is English with a shifted BPE vocabulary. They evaluate retrieval and translation scores at different layers; gold alignments are easy to derive given that the corpora are effectively parallel corpora, and that the vocabularies for both halves are effectively the same. As we build on these experiments, we adopt slightly simplified notation, and denote vocabulary-shifted corpora with square brackets, eg. \textsc{[en]}{}. \begin{figure*}[h] \centering \includegraphics[width=\textwidth]{fig/macro} \caption{{\bf Main results:} While untied and relative positional encodings are superior to sinusoidal and absolute positional encodings in the monolingual setting, they are clearly worse in the multilingual setting, especially for structurally different languages. The multilingual (ML) scores are computed as in \citet{dufterIdentifyingNecessaryElements2021}. Note also that results are averages across seven different word orders (see \S3).} \label{fig:macro} \end{figure*} \section{Experiments} \label{sec:exp} \paragraph{Galactic Dependencies \label{ssec:exp_struct} A drawback of the multilingual experiments presented in~\citet{dufterIdentifyingNecessaryElements2021} is that \textsc{en}{} and \textsc{[en]}{} effectively have the same structure. While the authors attempt to control for this in additional experiment where word order in \textsc{[en]}{} is completely reversed, this does not resemble realistic differences across languages. Using true multilingual corpora is, however, difficult: our retrieval and translation tasks are easy to bootstrap precisely because we have faux-parallel corpora, with effectively pre-aligned vocabulary. To induce structural diversity in our corpora, therefore, we reorder our corpora using Galactic Dependencies (GD) models~\citep{wang_galacticdependencies_2016}. Briefly, GD models sample ordering statistics based on dependency relations for the dependants of verbs and/or nouns from some superstrate language~\xx{xx}; when applied to sentences in some substrate language (in the context of our experiments, \textsc{en}{}), the models reorder dependants of \textsc{verb} and/or \textsc{noun} nodes to match the ordering statistics of the substrate language they were trained on. We opt to reorder both nominal and verbal arguments, and follow the authors in denoting the sampling operation with a $\sim$, giving us for eg.~\enxx{xx} for an English language corpus, with dependent order statistics adapted from some language \xx{xx}. Table~\ref{tab:gd} contains an example sentence and some of its reorderings. Note that GD reordering only works for projective sentences, and rather than retain un-reordered non-projective sentences, we exclude them from all our corpora. \begin{table}[h] \centering \resizebox{0.5\textwidth}{!}{\begin{tabular}{cc} \midrule \xx{en} & So there were fourteen generations from Abraham to David .\\ \enxx{ar} & . there were So generations fourteen from Abraham to David\\ \enxx{de} & there were So from Abraham to David fourteen generations .\\ \enxx{eu} & there were So David to Abraham from generations fourteen .\\ \enxx{fi} & Abraham from David to fourteen generations there were So .\\ \enxx{fr} & fourteen generations from Abraham to David were there So .\\ \enxx{hi} & there So David to Abraham from fourteen generations were .\\ \enxx{sv} & there were So generations from Abraham to David fourteen .\\ \bottomrule \end{tabular}} \caption{An example sentence from the easy-to-read Bible with its GD reorderings.} \label{tab:gd} \end{table} This approach, while simple and useful, does have several limitations. Predominantly, because our reordering is fundamentally syntactic/structural, our fake languages still maintain both the morphology of the source language (English in our case), and the same vocabulary distribution. Thus, although scrambling ought to affect context and neighbourhoods, an English token and its corresponding fake token have exactly the same unigram distribution. \paragraph{Training} \label{ssec:exp_training} Our model of choice is an underparameterised BERT, as in \citet{dufterIdentifyingNecessaryElements2021}. We train multiple such underparameterised BERT models, each with a different encoding mechanism from Section~\ref{ssec:pos_bg}, on two bilingual corpora: \begin{description} \item[\en{} + \fakeen{}{}] - a bilingual corpus comprised of English, and a fake vocab-shifted English. \item[\biling{xx}] - a bilingual corpus comprised of English, and a fake English that has had its constituents reordered to match the distribution of some language \xx{xx}. \end{description} We reorder our English starting point according to seven different faux-languages (just "languages" for brevity): Arabic, German, Basque, Finnish, French, Hindi and Swedish. Note that given that our starting point was English, there was no way for us to control for morphological differences; as such, languages with freer word order (like Basque) are likelier to make our English corpora ambiguous. We use two corpora in this work: the first is the Bible splits from~\citet{dufterIdentifyingNecessaryElements2021}, with the English easy-to-read Bible as the training split, and the KJV Bible as validation. The second corpus uses the English Wikipedia as the training split, and Common Crawl as validation. We present corpus statistics in Table~\ref{tab:corpus}. For each corpus, we learn and apply a BPE vocabulary of size 2048. \begin{table}[h] \centering \begin{tabular}{ccc} & Train & Validation \\ \midrule Bible & 30602 & 9080 \\ Wikipedia & 50000 & 20000 \\ \bottomrule \end{tabular} \caption{Corpus sizes in sentences (two languages per corpus)} \label{tab:corpus} \end{table} Following \citet{dufterIdentifyingNecessaryElements2021}, our BERT models all have a single head and 12 layers. We reduce the dimensionality of the encoder layers to 64, and the feed-forward layers to 256. Each model is trained for 100 epochs with three different random seeds (0, 42 and 100), giving us a total of 7 languages x 6 encoding methods x 3 seeds x 2 corpora = 252 models. We implement our code\footnote{\url{github.uio.no/vinitr/multilingual-position}} in the transformers library~\citep{wolf-etal-2020-transformers}. For learned absolute and the two relative encoding models, we use the default implementations, that scale attention operations by a scaling factor of $\frac{1}{\sqrt{d}}$. For our untied models, we adjust our scaling factor to $\frac{1}{\sqrt{2d}}$ as in the original paper~\citep{keRethinkingPositionalEncoding2020}. For sinusoidal representations, while \citet{vaswani_attention_2017} multiply token embeddings by $\sqrt{d}$ to avoid drowning them out with the $[-1, 1]$ sinusoidal encoding range, we find that our default embedding size is too small for this to have an effect, and instead scale up token embeddings by $2\sqrt{d}$ before adding positional encodings. For all parameterised encoding models except TUPE (relative), we use a maximum of $k = 512$ positions; the concrete transformers implementation of the relative methods means that this gives us 1023 total offsets. \footnote{In line with~\citet{shawSelfAttentionRelativePosition2018}, we also attempted to use $k = 16$ for the relative key model, but saw no difference in results.} For TUPE (relative), we use a maximum of $k = 128$ positions, divided into 32 bins with logarithmically increasing bin sizes; this is taken from the original implementation in~\citet{keRethinkingPositionalEncoding2020}. \section{Evaluation} We adopt~\citepos{dufterIdentifyingNecessaryElements2021} evaluation pipeline, evaluating each of our models at layers 0 and 8; we also describe a multilingual score, which is defined as the average accuracy for the retrieval and translation tasks, at layers 0 and 8. We also measure perplexity, both on the monolingual first half of the corpus, and on both halves combined. Note that true perplexities for masked language models are intractable~\citep{wang2019bert, Salazar_2020}. We use a trivial approximation and calculate perplexity based on the prediction loss for each masked token; note that while these suffice for comparison purposes, they are not true perplexities and should not be taken as such outside the context of these experiments. \begin{table*} \centering \resizebox{\textwidth}{!}{\begin{tabular}{c|ccccccc|ccccccc} &\multicolumn{7}{c|}{Wiki/CC} & \multicolumn{7}{c}{Bible} \\ \multirow{2}{*}{Embedding} & \multicolumn{2}{c}{Perplexity} & \multicolumn{2}{c}{Retrieval} & \multicolumn{2}{c}{Translation} & \multirow{2}{*}{ML score} & \multicolumn{2}{c}{Perplexity} & \multicolumn{2}{c}{Retrieval} & \multicolumn{2}{c}{Translation} & \multirow{2}{*}{ML score} \\ & Full & L1 & 0 & 8 & 0 & 8 & & Full & L1 & 0 & 8 & 0 & 8\\ \midrule Sinusoidal &66.73 &63.96 &37.43 &\textbf{97.29} &\textbf{77.03} &\textbf{64.07} &\textbf{68.95} &215.77 &186.53 &4.82 &\textbf{54.09} &47.09 &\textbf{27.62} &\textbf{33.4} \\ Absolute &66.35 &63.44 &\textbf{52.35} &96.53 &76.05 &53.62 &68.59 &229.28 &201.88 &\textbf{9.62} &52.51 &\textbf{47.6} &19.36 &32.27 \\ TUPE (absolute) &61.4 &58.77 &9.61 &84.72 &65.89 &36.57 &48.07 &239.48 &210.16 &1.65 &28.86 &28.85 &8.12 &16.87 \\ TUPE (relative) &59.81 &56.96 &16.25 &88.5 &71.7 &40.54 &53.89 &221.04 &194.58 &2.54 &41.34 &40.39 &13.92 &24.55 \\ Relative (key) &55.98 &52.5 &20.2 &87.36 &73.09 &31.38 &53.09 &193.49 &166.75 &2.18 &28.46 &30.43 &10.25 &17.83 \\ Relative (key/query) &\textbf{55.28} &\textbf{51.83} &21.24 &88.04 &73.58 &34.42 &54.64 &\textbf{191.23} &\textbf{164.41} &2.4 &31.6 &34.26 &13.03 &20.32 \\ \end{tabular}} \caption{Detailed results, averaged across our faux-languages. Best results per metric in bold.} \end{table*} We present our results (averaged out over faux-languages) in Figure~\ref{fig:macro}, with full results in Appendix~\ref{sec:app_full}. As expected, the more recent positional encodings are superior to sinusoidal or absolute positional encodings in the monolingual setting; but somewhat surprisingly, sinusoidal and absolute positional encodings are clearly outperforming the more recent approaches in the multilingual setting. We also note that the gap in multilingual performance only grows larger when a different word order is imposed on the target language; see the bottom row of Figure~\ref{fig:macro}. Interestingly, switching to structurally different L2s can sometimes reduce the language modelling perplexity of the L1: this could be due to regularisation induced by structural differences. \paragraph{Typological differences} \begin{figure}[t] \centering \includegraphics[width=0.5\textwidth]{fig/xling.png} \caption{(Full) perplexity and ML score across languages.} \label{fig:xling} \end{figure} We discuss "typology" with a caveat: our experiments with GD only alter word order, which means that all our altered-structure experiments still have English morphology. As such, it is impossible to talk about non-English languages; only about non-English word-order tendencies, when induced in English. Having said that, when we measure performance variation across languages (Figure~\ref{fig:xling}), our results are more or less what one would expect: performance is decent for relatively rigid word-order languages, and poorer for languages that have complex morphology. Interestingly, SVO languages consistently tend to perform better than our three non-SVO languages (Basque, Hindi and Arabic); this could be due to VSO/SOV languages requiring morphology to disambiguate between adjacent nominals~\citep{levshina_tokenbasedtypology_2019}. Another justification could also be that these are languages with a very different "default" word order to English; this would further motivate~\citepos{ding_selfattentioncrosslingual_2020} use of cross-lingually reordered position markers. \begin{figure}[t] \centering \includegraphics[width=0.5\textwidth]{fig/xnli.png} \caption{Real-world results on XNLI. Models were pretrained on a large text corpus and finetuned on English MultiNLI.} \label{fig:my_label} \end{figure} \paragraph{Real-world results} While we conduct most of our analyses on our toy models, we also ran a series of experiments to verify that our results would hold with larger models. As such, we pre-trained full size BERT models (base, not large) for two epochs, on a corpus consisting of 8.5\textsc{m}, 9.3\textsc{m} and 800k sentences in English, German and Hindi respectively. We then fine-tuned these models for three epochs on (English) MultiNLI~\citep{williams_broadcoveragechallenge_2018}, and evaluated on held-out XNLI test sets for our three languages~\citep{conneau_xnlievaluating_2018}; the process took approximately 4 days per model, on a single V100 GPU. We trained two models (seeds 0 and 42) per method, for three different positional encoding methods: a) absolute positional encodings, as these are used in the original BERT, b) sinusoidal encodings, as these were the original transformer encodings, and c) TUPE (absolute), as the most recent innovation. Our real-world results appear to validate our toy experiments: performance on English, the language the model was fine-tuned on, is highest with TUPE, while cross-lingual transfer suffers, both on German and to a lesser extent on Hindi. \section{Analyses} In an attempt to explain the significantly improved cross-lingual performance of absolute positional encodings, we tried to examine precisely what sort of encoding was being learnt. Part of the original motivation behind sinusoidal encodings was that they would allow for {\bf compositionality}; for any fixed offset $k$, there exists a linear transformation from $p_{pos}$ to $p_{pos+k}$, making it easier to learn to attend to relative offsets; the proof of this is in Appendix~\ref{sec:app_proof}.\footnote{\citet{vaswani_attention_2017} do not explicitly mention compositionality, but only generalization across positions for fixed offsets. Positional disentanglement is the flipside of compositionality, however \cite{chaabouni-etal-2020-compositionality}.} \begin{figure}[t] \centering \includegraphics[width=0.5\textwidth]{fig/abs_sin.png} \caption{Dimensions 0, 4, 8 and 16 of learnt absolute and TUPE positional encodings over 32 positions for \enxx{fi}, seed 0.} \label{fig:abs_sin} \end{figure} We examined our absolute positional encodings to see whether or not they were being induced to learn some specific function. Figure~\ref{fig:abs_sin} plots 4 dimensions of absolute and TUPE(a) positional encoding, for the \biling{fi} model; each line represents a specific dimension of the encoding vectors generated for positions 0 to 31. Interestingly, it appears that absolute representations converge to waveforms that represent sinusoids somewhat, while neither of the untied experiments do so (cf. Appendix~\ref{sec:app_plots}). We hypothesize that absolute representations converge to waveforms because of increased pressure for compositionality, being trained on structurally different languages. To test this, we quantify the extent to which the absolute, relative and untied encodings are compositional in the sense that there is a linear transformation from $p_{pos}$ to $p_{pos + k}$ for different $k$. \begin{figure}[t] \centering \includegraphics[width=0.5\textwidth]{fig/procrustes.png} \caption{Procrustes loss for \textcolor{ForestGreen}{absolute} encodings and \textcolor{Orange}{TUPE} (seed 0); differences are statistically significant with $p < 0.001$ (Wilcoxon). The \textcolor{Violet}{sinusoidal} loss is $\approx$ 0.} \label{fig:procrustes} \end{figure} To this end, we use Procrustes analysis \cite{Stegmann:2002} to learn a linear transformation for each $k$, based on the representations of $p_{pos}$ and $p_{pos+k}$. Specifically, we apply \emph{orthogonal} Procrustes analyses~\citep{schonemann1966generalized}, which avoid scaling and translation. First, we minimise $\arg\min_\mathrm{T}||p_{pos}-\mathrm{T}p_{pos+k}||^2$. Next, we apply $\mathrm{T}$ to a different randomly selected $\mathit{pos'}$, i.e. we calculate $\mathcal{L} = ||p_{pos'}-\mathrm{T}p_{pos'+k}||^2$. The higher the final loss $\mathcal{L}$, the less our encodings facilitate compositionality. In order to make learning $\mathrm{T}$ simpler, rather than selecting representations for single positions $pos$ and $pos'$, we select chunks of arbitrary size $C$, and stack their positions into a matrix. Note that for sinusoidal representations, the loss is close to zero regardless of span. The losses are plotted over a range of offsets for both absolute representations and for TUPE(a), in Figure~\ref{fig:procrustes}; we include a control model trained on a monolingual corpus. Losses are averaged over 125 runs per offset, with random values of $\mathit{pos}$, $\mathit{pos'}$ and $C$. While both forms of representation appear to be similar (and relatively non-sinusoidal) when trained on the monolingual corpus, introducing bilingualism leads to a clear difference between the two: absolute positional representations tend to be a lot closer to sinusoidal representations than untied ones do. Note, also, that this gap is clearest for the (simpler) \en{} + \fakeen{}{} experiment -- this is unsurprising, as \en{} + \fakeen{}{} is still \emph{perceived} as bilingual due to the shifted vocabulary. The structural similarity between the two, however, makes it easier to build compositional representations by relying on offsets, as the model only needs to learn to represent one language, structurally speaking. We observe a similar gap when comparing pretrained BERT models: \textsf{bert-base-multilingual-cased} exhibits more sinusoidal representations over a range of offsets, when compared to \textsf{bert-base-cased}, although the gap is narrower than with our toy models. \begin{figure}[h] \centering \includegraphics[width=0.5\textwidth]{fig/heatmap.png} \caption{Word-position correlations for our Finnish-reordered model with random seed 0; words on the y- and positions on the x-axis.} \label{fig:heatmap} \end{figure} \paragraph{Correlations in multilingual settings} A key motivation for eliminating word-position correlations, presented in~\citep{keRethinkingPositionalEncoding2020}, is the fact that these correlations are effectively zero, leading to no additional information for the model. Figure~\ref{fig:heatmap} captures word-position correlations from three of our trained models (with an additional model trained on a purely monolingual corpus); note that while these correlations are very close to zero for monolingual corpora, there is a visible "banding" phenomenon in the multilingual corpora, that only grows stronger when a different grammar is sampled. A similar banding phenomenon is visible when we compare multilingual and monolingual pre-trained BERT models (Appendix~\ref{sec:app_plots}), albeit with reduced magnitude. We hypothesize that the pressure for compositionality induces these correlations. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{fig/ablate.png} \caption{Ablation experiments, averaged over languages (for perplexity and ML score). Procrustes losses calculated as in \S5, for the \enxx{fi} model (seed 0).} \label{fig:ablate} \end{figure} \paragraph{Ablation studies} Finally, we ran a series of ablation experiments on absolute positional encodings to support the above analysis. Three of the experiments involved removing position-position correlations, position-word correlations, word-position correlations, and a fourth involved using separate parameters for word and position attention. Results are presented in Figure~\ref{fig:ablate}; we also include the median Procrustes loss. We note that the removal of both position-word correlations and word-position correlations has an effect on both perplexity and ML score. Interestingly, removing word-position correlations ($(p_iW^Q)(w_jW^K)^\top{}$) does not have the same effect as the inverse does: perplexity is lower than with position-word correlations removed, but so is the ML score, indicating a difference between the role played by position as a key, and as a query. \paragraph{On relative representations} Given our previous assumptions about offsets aiding compositionality, why, then, do our relative representations - that explicitly calculate offsets - perform poorly in multilingual settings? We speculate that the reason relative encodings appear to hurt multilingual compression is that offset-specific bias terms sparsify the learning signal for (and thereby hinder the alignment of) disjoint vocabularies. In compensating for this, relative positional encodings sacrifice their compositionality. Relative representations aid compositionality by directly providing a bias term derived from the distance between a word pair. As shown above, absolute representations learn similar biases; however, being actively forced to learn such biases could encourage models to jointly learn alignment and compositionality. Further, offset representations are also effectively "hard", i.e. derived from the hard distance between the two tokens. The interaction between $w_i$ and $w_j$ is not wholly mediated by the distance $i - j$, however, this correlation is forced by the product term $(x_iW^Q)(a_{ij})^\top{}$. The term $(x_iW^Q)(p_jW^K)^\top{}$, on the other hand, could effectively attend to multiple offsets. $p_jW^K$ is fixed for position $j$; given the sinusoidal nature of $p$, the product term could induce a "soft" positional representation with subspaces attending to different offsets\footnote{Indeed, we find that $p_jW^k$ is less invariant to Procrustes transformation than $p_j$ is.}; the relevant offset mix could then be indexed into by $x_iW^Q$. \section{Discussion} The main contribution of our work is practical, namely showing that findings about positional encodings in the context of monolingual language models do not apply straightforwardly to multilingual language models. In answering why sinusoidal embeddings are superior to more recent alternatives in the multilingual setting, we also found the compositionality of positional encodings to be predictive of multilingual compression in such models. While relative positional encodings seem designed for compositionality, they prevent efficient alignment of multilingual vocabularies. \citet{sinha_maskedlanguage_2021} show that word order matters little for monolingual language model pretraining, and that pretrained language models seem to rely mostly on higher-order word co-occurrence statistics. Our work shows that this finding does not generalize to pretraining multilingual language models. In the multilingual setting, word order clearly matters, as also shown in previous work~\citep{keRethinkingPositionalEncoding2020,dufterIdentifyingNecessaryElements2021}, and compositional positional encodings seem to facilitate effective multilingual compression. This aligns with the observation that syntactic reordering à la \citet{ding_selfattentioncrosslingual_2020} is in some cases an effective way to encourage compositional cross-lingual representations In general, our results illustrate how methods developed for monolingual language models should not be blindly adopted when training multilingual models, which potentially require different architectures. Conversely, we would encourage future work on new positional encoding mechanisms for non-autoregressive models to also evaluate these mechanisms in multilingual settings. \section{Conclusion} Through a series of synthetic and real experiments with training multilingual language models, we showed that a) sinusoidal positional encodings perform better in multilingual settings than more recent alternatives (that have been shown to perform better in monolingual settings); b) this is likely because of an increased pressure for compositionality. We devised a method for quantifying the compositionality of positional encodings, and strengthened our results by also considering word-position correlations and ablation studies.
{'timestamp': '2021-09-14T02:17:49', 'yymm': '2109', 'arxiv_id': '2109.05388', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05388'}
arxiv
\section{Introduction}\label{sec:introduction} Recent advances in Artificial Intelligence (AI) are enabling computer science and engineering to create machines that can learn from rough data, hence automating tasks previously thought to be accessible only by biological intelligence. But these advances and results seem to come at a cost in terms of explainability, so that the most effective machine learning techniques are, so far, not easily interpretable in symbolic terms \cite{chakraborty2017interpretability,rudin2019stop}. The paradigms that address this explainability problem usually fall into the so-called \ac{XAI} field, which is broadly recognized as a crucial feature for the practical implementation of artificial intelligence models \cite{arrieta2020explainable}. In fact, we are recently assisting to an increasing demand for explainability in AI applications, motivated by the growing awareness that transparency is pivotal for fairness and lawfulness. More precisely, in the European Union (EU) we now have several laws in force, which establish obligations of explainability based on who uses AI (e.g. public authorities, private companies) and the degree of automation of the decision-making process (e.g., fully or partially automated) \cite{bibal2021legal}. As a result, the EU is indirectly posing an interesting challenge to the \acf{XAI} community by calling for more transparent, user-centred and accountable \textit{automated decision-making systems} to ensure the explainability of their workings. In a recent attempt to capture the \quotes{legal requirements on explainability in machine learning}, \citeauthor{bibal2021legal} \cite{bibal2021legal} have identified four main explainability requisites for Business-to-Consumer and Business-to-Business. In particular, \citeauthor{bibal2021legal} assert that, for Business-to-Consumer and Business-to-Business, explanations about a solely-automated decision making system should at least provide information about: \begin{itemize} \item the main features used in a decision taken by the AI; \item all features processed by the AI; \item the specific decision taken by the AI; \item the underlying logical model followed by the AI. \end{itemize} Therefore, with the present letter we want to further expand the work of \citeauthor{bibal2021legal}, trying to understand whether it is possible to objectively quantify how much of the information required by law is explained by an AI. In this paper, we propose a new model-agnostic approach and metric to \textit{objectively} evaluate explainability in a manner that is mainly inspired by Ordinary Language Philosophy instead of Cognitive Science. Our approach is based on a specific theoretical model of explanation, called the \textit{Achinstein’s theory of explanations}, where explanations are the result of an \textit{illocutionary} (i.e., broad yet pertinent and deliberate) act of pragmatically answering to a question. Accordingly, explanations are actually answers to many different basic questions (\textit{archetypes}) each of which sheds a different light over the concepts being explained. As consequence, the more (archetypal) answers an \textit{automated decision-making system} is able to give about the important aspects of its explanandum\footnote{The word \textit{explanandum} means \quotes{what is to be explained}, in Latin.}, the more it is explainable. Therefore, we assert that it is possible to quantify the degree of explainability of a set of texts by applying the Achinstein-based definition of explanation proposed in \cite{sovrano2022generating}. Thus, drawing also from Carnap’s criteria of adequacy of an explication \cite{novaes2017carnapian}, we frame the \ac{DoX} as the average \textit{explanatory illocution} of information on a set of \textit{explanandum aspects}\footnote{Carnap uses the term \textit{explicandum} where we employ \textit{explanandum}, but, by and large, we assume the two words can be used interchangeably. They both mean \quotes{what needs to be explained} in Latin.}. More precisely, we hereby present an algorithm for measuring \ac{DoX} by means of pre-trained \textit{deep language models} for general-purpose answer retrieval (e.g., \cite{karpukhin2020dense,bowman2015large}) applied to a special graph of triplets automatically extracted from text to facilitate this type of information retrieval. Hence, we made the following hypothesis. \begin{hypothesis} \label{hyp:main} \textbf{\ac{DoX} scores measure explainability}: a \ac{DoX} score can describe \textit{explainability}, so that, given the same explanandum, a higher \ac{DoX} implies greater \textit{explainability} and a lower \ac{DoX} implies smaller \textit{explainability}. \end{hypothesis} To verify this hypothesis, we devised and implemented a pipeline of algorithms, called DoXpy, able to compute \textit{DoX} scores. We also performed a few experiments and user-studies involving more than 160 participants, with the objective of showing that \textit{explainability} changes in accordance with varying \ac{DoX} scores. Importantly, the results of all our experiments and user-studies clearly and undoubtedly showed that, in fact, our hypothesis \ref{hyp:main} holds. This paper is structured as follows. In section \ref{sec:background} we give the necessary background information to properly introduce the theoretical models discussed subsequently (i.e., Achinstein's theory), while in section \ref{sec:related_work} we discuss existing literature, comparing it to our proposed solution. In section \ref{sec:proposed_solution} we show how a metric for quantifying the degree of explainability is possible by defining \textit{explaining} as an illocutionary act of question-answering and by verifying Carnap’s criteria by means of deep language models. In section \ref{sec:experiments} we describe our experiments, we then present the findings in section \ref{sec:results}, and discuss them in section \ref{sec:discussion}. Finally, in section \ref{sec:limitations} we discuss some possible limitations of \ac{DoX}, pointing to future work and conclusions in section \ref{sec:conclusions}. For guaranteeing the reproducibility of the experiments, we publish the source code\footnote{\url{https://github.com/Francesco-Sovrano/DoXpy}} of the algorithm for computing \ac{DoX} scores, as well as the code of the XAI-based systems, the full details of our user-studies and the full set of data mentioned in this paper. \section{Background} \label{sec:background} In this section we provide some background to justify and support the rest of the paper. Hereby we briefly summarise a number of recent and less recent approaches to the theories of explanation, with a particular due focus on Achinstein's. After that, we discuss how Achinstein's theory of explaining as a question-answering process is compatible with existing \ac{XAI} literature, highlighting how profound is the connection between answering questions and explaining in this field. \subsection{Adequacy of Explainability: Carnap's Criteria} \label{sec:carnap} In philosophy, the most important work about the criteria of adequacy of \textit{explainable information} is likely to be Carnap's \cite{leitgeb2021carnap}. Even though Carnap studies the concept of \textit{explication} rather than that of \textit{explainable information}, we assert that they share a common ground making his criteria fitting in both cases. In fact, \textit{explication} in Carnap’s sense is the replacement of a somewhat unclear and inexact concept, the \textit{explicandum}, by a new, clearer, and more exact concept, the \textit{explicatum}\footnote{i.e., \quotes{what has been explained}, in Latin.}, and this is exactly what information does when made explainable. Carnap’s central criteria of explication adequacy\cite{leitgeb2021carnap} are: \textit{similarity}, \textit{exactness} and \textit{fruitfulness}\footnote{Carnap also discussed another desideratum, \textit{simplicity}, but this criterion is presented as being subordinate to the others (especially exactness).}. \textit{Similarity} means that the explicatum should be \textit{detailed} about the explicandum, in the sense that at least many of the intended uses of the explicandum, brought out in the clarification step, are preserved in the explicatum. On the other hand, \textit{exactness} means that the explication should be embedded in some sufficiently \textit{clear} and exact linguistic framework, while \textit{fruitfulness} implies that the explicatum should be \textit{useful} and usable in a variety of other \textit{good} explanations (the more, the better). Carnap's adequacy criteria seem to be transversal to all the identified definitions of explainability, possessing preliminary characteristics for any piece of information to be considered properly explainable. Interestingly, the property of \textit{truthfulness} (being different from \textit{exactness}) is not explicitly mentioned in Carnap's desiderata. That is to say that explainability and \textit{truthfulness} are complementary, but different, as discussed also by \cite{hilton1996mental}. In fact, an explanation is such regardless of its truth (high-quality but ultimately false explanations exist, especially in science). Vice versa, highly correct information can be very poor at explaining. \subsection{Definitions of Explainability} \label{sec:contemporary_theories_of_explanation} Considering the definition of \quotes{explainability} as \quotes{the potential of information to be used for explaining}, we envisage that a proper understanding of how to measure explainability must pass through a thorough definition of what constitutes an explanation and of the act of explaining. In 1948 Hempel and Oppenheim published their \quotes{Studies in the Logic of Explanation} \cite{hempel1948studies}, giving birth to what is considered the first theory of explanations: the deductive-nomological model. After that work, many amended, extended or replaced this model, which came to be considered fatally flawed \cite{bromberger1966questions,salmon1984scientific}. Several more modern and competing theories of explanations were the result of this criticism. \begin{table*}[!htb] \caption{\textbf{Definitions of Explainability}: In this table we summarise the definitions of \textit{explanation} and \textit{explainable information} for each one of the identified theories of explanations.} \label{tab:definitions} \makebox[\linewidth]{ \begin{tabular}{|p{0.20\linewidth}|p{0.50\linewidth}|p{0.3\linewidth}|} \hline \rowcolor[HTML]{C0C0C0} \textbf{Theory} & \textbf{Explanations} & \textbf{Explainable Information} \\ \hline Causal Realism \cite{salmon1984scientific} & Descriptions of causality, expressed as chains of causes and effects. & What can fully describe causality. \\ \hline Constructive Empiricism \cite{van1980scientific} & Contrastive information that answers \textit{why} questions, allowing one to calculate the probability of a particular event relative to a set of (possibly subjective) background assumptions. & What provides answers to contrastive \textit{why} questions. \\ \hline Ordinary Language \linebreak Philosophy \cite{achinstein1983nature} & Pragmatically answering multiple types of questions (not just \texttt{why} ones), with the explicit intent of producing understanding in someone. & What can be used to pertinently answer questions about relevant aspects, in an illocutionary way. \\ \hline Cognitive Science \cite{holland1986induction} & A process triggered as response to predictive failures and meant to provide information to fix failures in someone's mental model. & What can fix failures in mental models. \\ \hline Naturalism and Scientific Realism \cite{sellars1963philosophy} & An iterative process of confirmation of truths aimed at improving understanding. Explanations increase someone's understanding not simply by being the correct answer to a particular question, but by increasing the coherence of her/his entire belief system. & What can be used to increase understanding, i.e., by answering to particular questions. \\ \hline \end{tabular} } \end{table*} Summarising our full analysis \cite{sovrano2022metrics}, the five most important theories of explanation in contemporary philosophy are: \begin{inparadesc} \item Causal Realism, \item Constructive Empiricism, \item Ordinary Language Philosophy, \item Cognitive Science, \item Naturalism and Scientific Realism. \end{inparadesc} As consequence, there are at least five different definitions of \quotes{explanation}, one per theory. A summary of these definitions is shown in Table \ref{tab:definitions}, highlighting that there is no full agreement between them on the nature of explanations. Importantly, we notice that whenever explaining is considered to be an act that has to satisfy someone's needs, then explainability differs from explaining. In fact, in this context, pragmatically satisfying someone (i.e., user-centrality) is achieved when explanations are tailored to a specific person, so that the same explainable information can be presented and re-elaborated differently across different individuals. It follows that, in each philosophical tradition except Causal Realism \cite{salmon1984scientific}, we have a definition of \quotes{explainable information} that slightly differs from that of \quotes{explanation}, as described in \cite{sovrano2022metrics}. For example, in Ordinary Language Philosophy \textit{explainable information} can be understood as \quotes{what can be used to pertinently answer questions about relevant aspects, in an illocutionary way}. \subsection{Explainability According to Ordinary Language Philosophy} \label{sec:archetypal_questions} According to Achinstein's theory, explanations are the result of an \textit{illocutionary} act of pragmatically answering to a question. In particular, it means that there is a subtle and important difference between simply \quotes{answering to questions} and \quotes{explaining}, and this difference is \textit{illocution}. It appears that an \textit{illocutionary} act results from a clear intent of achieving the goal of such act, as a promise being \quotes{what it is} just because of the intent of maintaining it. So that \textit{illocution} in explaining makes an explanation as such just because it is the result of an underlying and proper intent of explaining. Despite this definition, \textit{illocution} seems to be too abstract to be implementable inside a real software application. Nonetheless, recent efforts towards the automated generation of explanations \cite{sovrano2021philosophy,sovrano2022generating}, have shown that it may be possible to define \textit{illocution} in a more \quotes{computer-friendly} way. Indeed, as stated in \cite{sovrano2021philosophy}, illocution in explaining involves informed and \textit{pertinent} answers not just to the main question, but also to other questions of various kinds, even unrelated to causality, that are relevant to the explanations. These questions can be understood as instances of archetypes such as \texttt{why}, \texttt{why not}, \texttt{how}, \texttt{what for}, \texttt{what if}, \texttt{what}, \texttt{who}, \texttt{when}, \texttt{where}, \texttt{how much}, etc. \begin{definition}[Archetypal Question] \label{def:archetypal_question} An archetypal question is an archetype applied on a specific aspect of the explanandum. Examples of archetypes are the interrogative particles (e.g., \texttt{why}, \texttt{how}, \texttt{what}, \texttt{who}, \texttt{when}, \texttt{where}), or their derivatives (e.g., \texttt{why not}, \texttt{what for}, \texttt{what if}, \texttt{how much}), or also more complex interrogative formulas (e.g., \texttt{what reason}, \texttt{what cause}, \texttt{what effect}). Accordingly, the same archetypal question may be rewritten in several different ways, as \quotes{why} can be rewritten in \quotes{what is the reason} or \quotes{what is the cause}. In other terms, archetypal questions identify generic explanations about a specific aspect to explain (e.g., a topic, an argument, a concept), in a given informative context. \end{definition} Thus, archetypal questions provide generic explanations on a specific aspect of the explanandum, in a given informative context which can precisely link the content to the informative goal of the person asking the question. For example, if the explanandum were \quotes{heart diseases}, there would be many aspects involved including \quotes{heart}, \quotes{stroke}, \quotes{vessels}, \quotes{diseases}, \quotes{angina}, \quotes{symptoms}, etc. Some archetypal questions in this case might be \quotes{What is an angina?} or \quotes{Why a stroke?}. \subsection{Explainable AI and Question Answering} \label{sec:xai_as_qa} If we assume that the interpretation of Achinstein’s theory of explanations given by \cite{sovrano2021philosophy} is correct, then data or processes are said to be \textit{explainable} when their informative content can adequately answer \textit{archetypal questions}. The idea of answering questions as explaining is not new to the field of \ac{XAI} \cite{liao2020questioning} and it is also quite compatible with our intuition of what constitutes an explanation. In fact, it is common to many works in the field \cite{ribera2019can,lim2009and,miller2018explanation,gilpin2018explaining,dhurandhar2018explanations, wachter2017counterfactual,rebanal2021xalgo,jansen2016s,madumal2019grounded} the use of generic (e.g., \texttt{why}, \texttt{who}, \texttt{how}, \texttt{when}) or more punctual questions to clearly define and describe the characteristics of explainability \cite{liao2020questioning}. For example, \citeauthor{lundberg2020local} \cite{lundberg2020local} assert that the local explanations produced by their TreeSHAP (an \textit{additive feature attribution} method for feature importance) may \quotes{help human experts understand \textit{why} the model made a specific recommendation for high-risk decisions}. On the other hand, \citeauthor{dhurandhar2018explanations} \cite{dhurandhar2018explanations} clearly state that they designed CEM (a method for the generation of counterfactuals and other contrastive explanations) to answer the question \quotes{why is input \textit{x} classified in class \textit{y}?}. Furthermore, \citeauthor{rebanal2021xalgo} \cite{rebanal2021xalgo} propose and studies an interactive approach where explaining is defined in terms of answering \texttt{why}, \texttt{what} and \texttt{how} questions. These are just some examples, among many, of how Achinstein's theory of explanations is already implicit in existing \ac{XAI} literature, and they highlight how deep is in this field the connection between answering questions and explaining. Nonetheless, despite the compatibility, practically none of the works in \ac{XAI} explicitly mentions any theory from Ordinary Language Philosophy, preferring to refer to Cognitive Science \cite{miller2018explanation,hoffman2018metrics} instead. This is probably because Achinstein’s illocutionary theory of explanations is seemingly difficult to be implemented into software, by being utterly pragmatic. In fact, \emph{user-orientedness} is challenging and sometimes not obviously connected to the main goal of \ac{XAI}: \quotes{opening the black-box} (e.g., understanding how and why an opaque AI model works). \section{Related Work} \label{sec:related_work} \begin{table*}[!htb] \centering \caption[Comparison of Different Explainability Metrics]{ \textbf{Comparison of Different Explainability Metrics}\footnotemark: The column \quotes{Sources} points to referenced papers, while column \quotes{Metrics} points to the names of the metrics. Elements in bold are column-by-column better than the rest. } \label{tab:literature_comparison} \makebox[\linewidth]{ \begin{tabular}{|p{.11\linewidth}|p{.13\linewidth}|p{.2\linewidth}|p{.07\linewidth}|p{.12\linewidth}|p{.25\linewidth}|} \hline \rowcolor[rgb]{0.753,0.753,0.753} \textbf{Source} & \textbf{Model \& Information Format} & \textbf{Closest Supporting Theory} & \textbf{Subject - based} & \textbf{Measured Carnap's Criteria} & \textbf{Metrics} \\ \hline \cite{rosenfeld2021better} & Rule-based & Causal Realism & \textbf{No} & \begin{tabular}[c]{@{}l@{}}Exactness,\\Fruitfulness\end{tabular} & \begin{tabular}[c]{@{}l@{}}Performance Difference, \\Number of Rules,\\Number of Features, Stability\end{tabular} \\ \hline \cite{villone2020comparative} & Rule-based & Causal Realism & \textbf{No} & \begin{tabular}[c]{@{}l@{}}Similarity,\\Fruitfulness\end{tabular} & \begin{tabular}[c]{@{}l@{}}Fidelity, \\ Completeness\end{tabular} \\ \hline \cite{nguyen2020quantitative} & Feature Attribution & Causal Realism & \textbf{No} & \begin{tabular}[c]{@{}l@{}}Exactness,\\Fruitfulness\end{tabular} & \begin{tabular}[c]{@{}l@{}}Monotonicity, Non-sensitivity, \\ Effective Complexity\end{tabular} \\ \hline \cite{lakkaraju2017interpretable} & Rule-based & Causal Realism & \textbf{No} & \begin{tabular}[c]{@{}l@{}}\textbf{Similarity,}\\\textbf{Exactness,}\\\textbf{Fruitfulness}\end{tabular} & \begin{tabular}[c]{@{}l@{}}Fidelity, Unambiguity, \\ Interpretability, Interactivity\end{tabular} \\ \hline \cite{holzinger2020measuring} & \textbf{Any} & \begin{tabular}[c]{@{}l@{}}Causal Realism, \\ Cognitive Science, \\ Naturalism \& Co.\end{tabular} & Yes & \begin{tabular}[c]{@{}l@{}}Exactness,\\Fruitfulness\end{tabular} & System Causability Scale \\ \hline \cite{hoffman2018metrics} & \textbf{Any} & \begin{tabular}[c]{@{}l@{}}Cognitive Science, \\ Naturalism \& Co.\end{tabular} & Yes & \begin{tabular}[c]{@{}l@{}}Exactness,\\Fruitfulness\end{tabular} & \begin{tabular}[c]{@{}l@{}}Satisfaction, Trust, \\ Mental Models, \\ Curiosity, Performance\end{tabular} \\ \hline \cite{dieber2022novel,sovrano2021philosophy,mohseni2021quantitative,wang2021explanations,szymanski2021visual,buccinca2020proxy,poursabzi2018manipulating} & \textbf{Any} & \begin{tabular}[c]{@{}l@{}}Cognitive Science, \\ Naturalism \& Co.\end{tabular} & Yes & \begin{tabular}[c]{@{}l@{}}Exactness,\\Fruitfulness\end{tabular} & \begin{tabular}[c]{@{}l@{}}Usability: Effectiveness, \\Efficiency, Satisfaction\end{tabular} \\ \hline \cite{arras2022clevr} & Heatmap & Constructive Empiricism & \textbf{No} & \begin{tabular}[c]{@{}l@{}}Similarity, \\Exactness\end{tabular} & \begin{tabular}[c]{@{}l@{}}Relevance Mass Accuracy, \\Relevance Rank Accuracy\end{tabular} \\ \hline \cite{keane2021if} & Prototype-based & Constructive Empiricism & \textbf{No} & Exactness & \begin{tabular}[c]{@{}l@{}}Proximity, Sparsity, \\ Adequacy (Coverage)\end{tabular} \\ \hline \cite{nguyen2020quantitative} & Prototype-based & Constructive Empiricism & \textbf{No} & \begin{tabular}[c]{@{}l@{}}Similarity,\\Fruitfulness\end{tabular} & \begin{tabular}[c]{@{}l@{}}Non-Representativeness, \\ Diversity\end{tabular} \\ \hline This Paper & \textbf{Any} (Natural Language Text) & \begin{tabular}[c]{@{}l@{}}Ordinary Language \\Philosophy\end{tabular} & \textbf{No} & \begin{tabular}[c]{@{}l@{}}\textbf{Similarity,}\\\textbf{Exactness,}\\\textbf{Fruitfulness}\end{tabular} & Degree of Explainability \\ \hline \end{tabular} } \end{table*} \footnotetext{This table extends a similar one in \cite{sovrano2022metrics}.} Being able to measure the quality of explanations and \ac{XAI} tools is pivotal for claiming technological advancements, understanding existing limitations, developing better solutions and delivering \ac{XAI} that can go into production. Not surprisingly, every good paper proposing a new \ac{XAI} algorithm comes with evidences and experiments backing up their own claims and none other, usually relying on \textit{ad hoc} or subjective mechanisms for measuring the quality of their explainability. This makes it very hard to perform meaningful comparisons. In other words, as suggested also by literature reviews (e.g., \cite{vilone2021notions}, and especially \cite{sovrano2022metrics}, which reports in table \ref{tab:literature_comparison} its main results), it is common to encounter explainability metrics that work only with a specific \ac{XAI} model or prove their usefulness by collecting human-generated opinions/results after interacting with the studied system and no other. For example, the metrics proposed in \cite{arras2022clevr,rosenfeld2021better,villone2020comparative,nguyen2020quantitative,lakkaraju2017interpretable,keane2021if} can only be used with specific types of \ac{XAI} approaches (e.g., prototype selection or feature attribution), while the metrics proposed in \cite{hoffman2018metrics,holzinger2020measuring,dieber2022novel} rely on user-studies, as many other works \cite{sovrano2021philosophy,mohseni2021quantitative,wang2021explanations,szymanski2021visual,buccinca2020proxy,poursabzi2018manipulating}, based on classical usability metrics (i.e., effectiveness, efficiency, satisfaction). Only one work among those examined, \citeauthor{hoffman2018metrics} \cite{hoffman2018metrics}, claims that its proposed metric is model-agnostic, and thus generic enough to be compatible with any \ac{XAI}. In particular, this is possible because the work measures explainability \textit{indirectly}, by estimating the effects of explanations on human subjects. More precisely, \cite{hoffman2018metrics} is mainly inspired by the interpretation of explanations given by Cognitive Science, requiring to measure: \begin{inparaenum}[i)] \item the subjective goodness of explanations; \item whether users are satisfied by explanations; \item how well users understand the AI systems; \item how curiosity motivates the search for explanations; \item whether the user's trust and reliance on the AI are appropriate; \item how the human-\ac{XAI} work system performs. \end{inparaenum} Indeed, the metric presented in \cite{hoffman2018metrics} is non-deterministic and heavily relying on subjective measurements, despite being model-agnostic. The metric we propose here, \ac{DoX}, is objective, deterministic and model-agnostic\footnote{\ac{DoX} is model-agnostic only under the assumption that any explanation or bit of explainable information can be represented or described in natural language, e.g., English.} and it can be used to evaluate the explainability of any textual information and to understand whether the amount of explainability is objectively poor, even if the resulting explanations are perceived as satisfactory and good by the explainees. Furthermore, only \ac{DoX} and \cite{lakkaraju2017interpretable} appear to measure all the three main Carnap's desiderata. More specifically, \citeauthor{lakkaraju2017interpretable} \cite{lakkaraju2017interpretable} evaluate Carnap's criteria separately, while with \ac{DoX} we propose a single metric that combines all of them. Finally, as suggested in \cite{sovrano2022metrics}, all existing explainability metrics can be aligned to different interpretations of explainability coming from complementary theories of explanations. As shown in table \ref{tab:literature_comparison}, the vast majority of these metrics seems to be aligned to Causal Realism and Cognitive Science, while \ac{DoX} is the very first metric based on Ordinary Language Philosophy. \section{Degrees of Explanation (DoX)} \label{sec:proposed_solution} In section \ref{sec:related_work} we discussed how existing metrics for measuring (properties of) explainability are frequently either model-specific or subjective, raising the question of whether it is possible to objectively measure the degree of explainability with a fully automated software. With this paper we try to answer this question, by leveraging on an extension of Achinstein's theory of explanations as proposed in \cite{sovrano2021philosophy} and summarized in section \ref{sec:archetypal_questions}. We do it by asserting that any algorithm for measuring the degree of explainability must pass through a thorough definition of what constitutes \textit{explainability} and \textit{explanation}. In fact, considering that \textit{explainability} is fundamentally the \textit{ability to explain}, it is clear that a proper definition of it requires a precise understanding of what is \textit{explaining}. In this section we discuss both the theory behind \ac{DoX} and a concrete implementation to measure \ac{DoX} in practice. \subsection{Quantifying the Degree of Explainability} \label{sec:proposed_solution:theory} As discussed in section \ref{sec:xai_as_qa}, the informative contents of state-of-the-art \ac{XAI} is clearly polarised towards answering \texttt{why}, \texttt{what if} or \texttt{how} questions. Considering that \texttt{why}, \texttt{what if} and \texttt{how} are different questions pointing to different types of information, which type is the best one? We assert that the correct answer to this question is: \quotes{none}. In fact, depending on the needs of the explainee, its background knowledge, the context, and potentially many other factors, each archetype may be equally important. In other words, depending on the characteristics of the explainee (e.g., background knowledge, objectives, context, etc.), a combination of different \ac{XAI} mechanisms may be necessary to obtain a minimum \textit{understanding of the internal logic of a black-box AI}. Therefore, knowing the types of explainability covered by an XAI-based system can be of the utmost importance in understanding how explainable it is. Hence, following this intuition, we started to study how to measure explainability in terms of (generic) questions. Among the different approaches mentioned in section \ref{sec:contemporary_theories_of_explanation}, the closest one to our intuition of explainability is probably Achinstein's theory, coming from Ordinary Language Philosophy. Achinstein defines the act of explaining as an act of illocutionary question answering, stating that \textit{explaining} is more than \textit{answering a question} because it requires some form of illocution. Nonetheless, without a precise and computer-friendly definition of illocution, it is hard to go further than a philosophical and abstract understanding of such concept. For this reason, as discussed in section \ref{sec:archetypal_questions}, in \cite{sovrano2021philosophy} we suggested that illocution (or, better, \textit{explanatory illocution}) is in fact the process of answering multiple generic and primitive questions (e.g., \texttt{why}, \texttt{how}, \texttt{what}, etc.) called \textit{archetypal questions}. For example, if someone would be asking \quotes{How are you doing?}, an answer like \quotes{I am good} would not be considered an explanation. Differently, the answer \quotes{I am happy because I just got a paper accepted at this important venue, and [...]} would instead be normally considered an explanation, because it answers other \textit{archetypal questions} together with the main question. We are convinced that, under these premises, we can concretely measure the degree of explainability of information in a quantitative way. More precisely, we propose that the degree of explainability of the information depends on the number of \textit{archetypal questions} to which it can adequately answer. In other words, we propose to estimate the degree of explainability of a piece of information by measuring the relevance with which it can answer a (pre-defined) set of archetypal questions. Hence, our theoretical contribution, unfolded in the following sub-sections, consists in the precise and formal definition of: \begin{inparadesc} \item \textit{cumulative pertinence}, \item \textit{explanatory illocution}, \item \textit{\acf{DoX}}, \item and \textit{Average \ac{DoX}} \end{inparadesc} \subsubsection{Cumulative Pertinence, Explanatory Illocution and DoX} Assuming the correctness of a given piece of information, \textit{explainability} is a property of that information and it can be measured in terms of \textit{explanatory illocution}. In order to understand what \textit{explanatory illocution} is, we have to define the concept of \textit{cumulative pertinence} first. \begin{definition}[Cumulative Pertinence] \label{def:cumulative_pertinence} The \textit{cumulative pertinence} is an estimate of how \textit{pertinently} and how in \textit{detail} a given piece of information $\Phi$ can answer a question about an aspect $a$ of an explanandum $\Delta$. Let $A$ be the set of relevant aspects to be explained about $\Delta$. Let $D_a$ be the subset of all the details (e.g., sentences, grammatical clauses, paragraphs, etc.) in $\Phi$ that are about an aspect $a \in A$. Let $q_a$ be a question about an aspect $a \in A$. Let $p\left(d,q_a\right) \in [0,1]$ be the pertinence of a detail $d \in D_a$ to $q_a$. Let also $t$ be a pertinence threshold in the $[0,1]$ range. Then, the \textit{cumulative pertinence} of $D_a$ to $q_a$ is $P_{D_a,q_a} = \sum_{d \in D_a, p\left(d,q_a\right) \geq t}{p\left(d,q_a\right)}$. \end{definition} \begin{definition}[Explanatory Illocution] \label{def:explanatory_illocution} The \textit{explanatory illocution} is a set of \textit{cumulative pertinences} for a pre-defined set of \textit{archetypal questions}. Let $Q$ be a set of archetypes $q$ and $q_a$ be the question obtained by applying the archetype $q$ to an aspect $a \in A$. Then the \textit{explanatory illocution} of $\Phi$ to an aspect $a \in A$ is the set of tuples $\{\forall q \in Q | <q, P_{D_a,q_a}> \}$\footnote{The operator $<x, y>$ is used here to represent tuples.}. \end{definition} Consequently, we define \ac{DoX} as follows. \begin{definition}[Degree of Explainability] \label{def:DoX} \ac{DoX} is the average \textit{explanatory illocution} per archetype, on the whole set $A$ of relevant aspects to be explained. In other terms, let $R_{D,q,A} = \frac{\sum_{a \in A}{P_{D_a,q_a}}}{|A|}$ be the average \textit{cumulative pertinence} of $D$ to $q$ and $A$, where $D = \{\forall a \in A, \forall d \in D_a | d \}$, then the \ac{DoX} is the set $\{\forall q \in Q | <q, R_{D,q,A}> \}$. \end{definition} \subsubsection{Interpreting DoX in Terms of Carnap's Criteria} Given definition \ref{def:DoX}, we can say that \ac{DoX} is an estimate of the \textit{fruitfulness} of $D$ that combines in one single score the \textit{similarity} of $D$ to $A$ and the \textit{exactness} of $D$ with respect to $Q$. For these reasons, \ac{DoX} is akin to Carnap’s \textit{central} criteria of adequacy of explanation (introduced in section \ref{sec:carnap}). Although, differently from Carnap, our understanding of \textit{exactness} is not that of adherence to standards of formal concept formation\footnote{Actually, Carnap did not specify what he means by \quotes{exactness}. Regardless, in this context \quotes{exactness} is often viewed as either lack of vagueness or adherence to standards of formal concept formation.} \cite{brun2016explication}, but rather that of being precise or pertinent enough as an answer to a given question. In fact, the number of relevant aspects $A$ covered by a given piece of information, and the number of details $D$ that are pertinent about it, roughly say how much \textit{similar} that information is to the explanandum. More precisely, the formula used for computing the cumulative pertinences $P_{D_a,q_a}$ sums the contribution of each single detail according to its pertinence to the aspects $a \in A$, telling us how much $D_a$ is similar to $a$. Thus that if \textit{pertinence} $p\left(d,q_a\right)$ is close to zero for all archetypes $q \in Q$, then a detail $d$ has nothing to do with an aspect $a$. Furthermore, the average cumulative pertinence $R_{D,q,A}$ contains information about the \textit{exactness} of multiple archetypal explanations, being an aggregation of pertinence scores. As result, by measuring $R_{D,q,A}$ for all the $q \in Q$ we obtain also an estimate of how $D$ is \textit{fruitful} for the formulation of many other different explanations intended as the result of an illocutionary act of answering questions. For example, suppose the set of relevant aspects $A = \left\{\text{heart}, \text{stroke}, \text{vessel}, \text{disease}, \text{angina}, \text{symptom}\right\}$ and the sentence \quotes{I am happy that my article has been accepted in this prestigious journal} as $\Phi$. In this case $D = \emptyset$ because nothing in $\Phi$ is related to $A$. Hence, the average cumulative pertinence would be equal to $0$ for every archetype $q \in Q$, forcing the \ac{DoX} score to be equal to $0$, as expected. In fact, no detail of $\Phi$ is explaining anything about $A$, therefore the explainability of $\Phi$ with respect to $A$ is $0$. On the other hand, we would not have a null \ac{DoX} for $A$ with the sentence \quotes{Angina happens when some part of your heart doesn't get enough oxygen} as $\Phi$. In fact, this new $\Phi$ contains details about at least two relevant aspects $a \in A$ (i.e., \quotes{angina}, \quotes{heart}). In particular, such details would probably score an higher average cumulative pertinence $R_{D,q,A}$ for $q$ equal to \texttt{why}, because they are about causality. For instance, with the DoXpy algorithm presented in section \ref{sec:proposed_solution:practice}, when using the FB pertinence estimator described in section \ref{sec:experiments:pertinence}, the archetypes with the best score are those related to causality (i.e., \texttt{what effect} scores $0.59$, \texttt{in what case}, \texttt{why} and \texttt{how} score $0.57$), while most of the others have a null score (i.e., \texttt{who}, \texttt{when}, etc.), and the Average \ac{DoX} is $0.29$. This construction of \ac{DoX} in terms of Carnap's central criteria of adequacy is the central theoretical contribution of this paper, because it allows us to move to the next step: implementing (in section \ref{sec:proposed_solution:practice}) an algorithm to experimentally verify hypothesis \ref{hyp:main}. \subsubsection{The Average DoX} Despite all its good properties, \ac{DoX} cannot help in judging whether some collections of information have higher degrees of explainability than others. This is due to the multidimensional nature of the estimated relevance of different archetypes. This multidimensionality makes it hard to tell if a \ac{DoX} score is greater than another. To overcome this issue, a mechanism is required for combining the set of pertinence scores composing \ac{DoX} into a single score representing \textit{explainability}. We do so by simply averaging pertinence scores. Hence, the resulting Average \ac{DoX} can act as a metric to judge whether the \textit{explainability} of a system is greater than, equal to, or lower than another. \begin{definition}[Average Degree of Explainability] \label{def:AveDoX} The Average \ac{DoX} is the average of the pertinences of each archetype composing the \ac{DoX}. In other terms, the Average \ac{DoX} is $\frac{\sum_{q \in Q}{R_{D,q,A}}}{|Q|}$. \end{definition} The Average \ac{DoX} represents a naive approach to quantify explainability with a single score, as it implies that all the archetypal questions and aspects have the same weight, although this may not be necessarily true. In fact, as suggested in section \ref{sec:xai_as_qa} and in \cite{liao2020questioning}, it seems that there is a shared understanding that \texttt{why} explanations are the most important in \ac{XAI}, sometimes followed by \texttt{how}, \texttt{what for}, \texttt{what if} and, possibly, \texttt{what}. In other words, the relevance of an explanation can be estimated by the ability to effectively answer the most relevant (archetypal) questions for the objectives of the stakeholders. Nonetheless, defining which (archetypal) question is the most relevant is clearly a challenging task and rather prone to subjectivity, therefore we believe that Average \ac{DoX} is probably the only objective solution to this dispute. \subsection{The \textit{DoXpy} algorithm} \label{sec:proposed_solution:practice} Given definition \ref{def:DoX}, we argue that it is possible to write an algorithm that can approximate a quantification of the \acl{DoX} of information representable with \textit{natural language} (e.g., English). Suppose we want to measure the \ac{DoX} of a set of texts $\Phi$ called \textit{explanandum support material}, containing correct content-giving textual information about an explanandum. For example, if the \textit{explanandum} were \quotes{heart diseases}, there would be many aspects involved including \quotes{heart}, \quotes{stroke}, \quotes{vessel}, \quotes{diseases}, \quotes{angina}, \quotes{symptoms}, etc. Hence a reasonable \textit{support material} for it would probably be a book describing all these aspects, or a set of web-pages (i.e., those published by the \textit{U.S. Centers for Disease Control and Prevention}\footnote{\url{https://www.cdc.gov}}), or any other kind of related corpus written in natural language. As per definition \ref{def:explanatory_illocution}, in order to implement an algorithm capable of computing the (average) \ac{DoX} of $\Phi$, we need to: \begin{itemize} \item define a set $A$ of \textit{explanandum aspects}; \item identify the set of all possible archetypes $Q$ and the set $D$ of details contained in $\Phi$; \item define a mechanism to identify $D$; \item define the function $p$ to compute the pertinence of an individual detail $d$ to an archetypal question $q_a$. \end{itemize} In particular, while the set of aspects $A$ is task-dependent and needs to be defined for every explanandum (i.e., by manually listing all the aspects, or by automatically extracting with a tokenizer the list of aspects from a textual description of the explanandum), the set of archetypes $Q$, the pertinence function $p$ and the mechanism for extracting $D$ and $D_a$ out of $\Phi$ \textit{can be always the same} for all the explananda. \begin{figure}[!tb] \centering \includegraphics[width=.99\columnwidth]{figures/pipeline} \caption{\textbf{DoXpy Pipeline}: The pipeline starts with the extraction of a graph from the \textit{explanandum support material} $\Phi$ that is then converted into a set of details $D$. The set of details is then used in combination with the explanandum $A$ and the set of archetypes $Q$ to compute the \ac{DoX}. To do so, we use some deep language models for answer retrieval.} \label{fig:pipeline} \end{figure} Indeed, by leveraging on existing pre-trained deep language models \cite{reimers2019sentence,yang2019multilingual} capable of converting snippets of text (e.g., questions and answers) into numerical representations, in the following sections we show how to concretely implement DoXpy, an algorithm capable of estimating the \ac{DoX} of any arbitrary piece of textual information with the pipeline shown in Figure \ref{fig:pipeline}. More precisely, this pipeline relies on a mechanism for the automatic extraction of a (knowledge) graph from any $\Phi$, in order to identify the details needed to generate a score, as per definition \ref{def:DoX}. For reproducibility purposes, we publish the DoXpy source code at: \url{https://github.com/Francesco-Sovrano/DoXpy}. \subsubsection{Details Extraction and Pertinence Estimation} Definition \ref{def:DoX} requires a mechanism to identify the set $D$ of details contained in the \textit{explanandum support material} $\Phi$, as well as a mechanism to identify the sub-sets $D_a \subseteq D$ for every $a \in A$. In particular, the set $A$ of \textit{explanandum aspects} is a collection of lemmatised words/syntagms. On the other hand, a detail $d$ is a snippet of text with some specific characteristics. In fact, a detail $d$ is an \textit{information unit}, i.e., a relatively small sequence of words about one or more aspects (i.e., a sub-set of $A$) that is usually extracted from a more complex information bundle (i.e., a paragraph, a sentence) comprising several \textit{information units}. In other terms, these details should carry enough information to describe different parts of an aspect $a$ (possibly connected to many other aspects), so that we can use them to answer some (archetypal) questions about $a$ and to correctly estimate a \textit{level of detail}, as required by definition \ref{def:DoX}. Considering the aforementioned characteristics of $D$ and $A$, the most natural representation of them seems to be a (knowledge) graph. In fact, a graph is a set of nodes (i.e., $A$) connected by a set of edges (i.e., $D$). Therefore, we believe that the easiest way to identify the set of details $D$ (and possibly also $A$) might pass through some mechanism for the extraction of a graph of \textit{information units} from $\Phi$. Thus, an approach like the one used in \cite{sovrano2021philosophy,sovrano2020legal} for archetypal question answering, might be suitable to our ends, allowing for the identification of meaningful \textit{information units} and suggesting also a mechanism for the estimation of \textit{pertinence}. In particular, the algorithm proposed by \cite{sovrano2021philosophy,sovrano2020legal} consists in a pipeline of AI tools for the extraction from $\Phi$ of a graph of $D$ and $A$ designed for answer retrieval. More specifically, this graph is extracted by detecting, with a dependency parser, all the phrases and sub-phrases within the \textit{explanandum support material} that stand as an edge of the graph. In practice, these phrases are represented as special triplets of subjects, templates and objects called template-triplets. More specifically, the templates are composed by the ordered sequence of tokens connecting together a subject and an object. On the other hand, the subject and the object are represented in these templates by the placeholders \textit{\quotes{\{subj\}}} and \textit{\quotes{\{obj\}}}. An example of template-triple is: \begin{itemize} \item Subject: \textit{\quotes{angina pectoris}} \item Template: \textit{\quotes{In particular, \{subj\} happens when some part of your heart doesn't get enough \{obj\}.}} \item Object: \textit{\quotes{oxygen}} \end{itemize} Hence, the resulting template-triplets are a sort of function, where the predicate is the body and the object and subject are the parameters. Obtaining a natural language representation (i.e., a detail $d \in D$) of these template-triplets is straightforward by design, by replacing the instances of the parameters in the body. This natural representation is then used as possible answer for retrieval by measuring the (cosine) similarity (or pertinence $p$) between its embedding (obtained through deep language models such as \cite{guo2020multireqa,karpukhin2020dense}) and the embedding of a question $q$. Importantly, as \textit{information units}, \citeauthor{sovrano2021philosophy} \cite{sovrano2021philosophy,sovrano2020legal} use meaningful decompositions of grammatical dependency trees, to guarantee that the units represent the smallest granularity of information. As a consequence, using this type of \textit{information units} for \ac{DoX} guarantees: \begin{itemize} \item a disentanglement of complex information bundles into the most simple units, to correctly estimate the \textit{level of detail} covered by the information pieces, as per definition \ref{def:DoX}; \item a better identification of duplicated units scattered throughout the information pieces, so to avoid an over-estimation of the \textit{level of detail}; \item an easy way to understand whether an answer is invalid when it is totally contained in the question, hence forcing its \textit{pertinence} to be zero. \end{itemize} All these properties meet the requirements that a good detail $d \in D$ should possess for the generation of a \ac{DoX} score. Therefore, this motivates our decision to use inside our pipeline the algorithm for answer retrieval from \cite{sovrano2021philosophy,sovrano2020legal}. In these papers you can also find additional technical details about how this algorithm works. \subsubsection{Selection of Archetypes} \label{sec:proposed_solution:practice:archetype_selection} According to definition \ref{def:archetypal_question}, an archetypal question is a generic question characterised by one or more interrogative formulas. Literature is full of different examples of such archetypal questions, and many of them are used to classify semantic relations (see for instance \cite{he2015question,fitzgerald2018large,michael2017crowdsourcing,pyatkin2020qadiscourse}, etc.). Interestingly, it is possible to identify a sort of hierarchy or taxonomy of these archetypes, ordered by their intrinsic level of specificity. For example, the simplest interrogative formulas (made only of an interrogative particle: \texttt{what}, \texttt{why}, \texttt{when}, \texttt{who}, etc.) can be seen as the most generic archetypes. While the more complex and composite is the formula (e.g., \texttt{what for}, \texttt{what cause}), the more specific is the question. Hence, we decided to consider as set $Q$ of main \textit{archetypes} the most generic interrogative formulas used by literature \cite{he2015question,fitzgerald2018large,michael2017crowdsourcing,pyatkin2020qadiscourse} to classify semantic relations within discourse. In particular, the main \textit{archetypes} coming from Abstract Meaning Representation theory \cite{michael2017crowdsourcing} are: \begin{inparadesc} \item \texttt{what}, \item \texttt{who}, \item \texttt{how}, \item \texttt{where}, \item \texttt{when}, \item \texttt{which}, \item \texttt{whose}, \item \texttt{why}. \end{inparadesc} We refer to these archetypes as the \textit{primary} ones because they consist only of interrogative particles. On the other hand, the main \textit{archetypes} coming from PDTB-style discourse theory \cite{pyatkin2020qadiscourse} (also called \textit{secondary archetypes} because they make use of the \textit{primary archetypes}) are: \begin{inparadesc} \item \texttt{in what manner}, \item \texttt{what is the reason}, \item \texttt{what is the result}, \item \texttt{what is an example}, \item \texttt{after what}, \item \texttt{while what}, \item \texttt{in what case}, \item \texttt{despite what}, \item \texttt{what is contrasted with}, \item \texttt{before what}, \item \texttt{since when}, \item \texttt{what is similar}, \item \texttt{until when}, \item \texttt{instead of what}, \item \texttt{what is an alternative}, \item \texttt{except when}, \item \texttt{unless what}. \end{inparadesc} In addition to the fact that many more archetypes could be devised (e.g., \texttt{where to} or \texttt{who by}), we believe that the list of questions we provided earlier is already rich enough to be generally representative for any other question\footnote{For concrete examples of how all these questions (especially the primary ones) are related to XAI algorithms, we point the reader to this recent survey by \textit{IBM Research} \cite{liao2020questioning} or to section \ref{sec:xai_as_qa} of this paper.}, whereas more specific questions can be always framed by using the interrogative particles we considered (e.g., \texttt{why}, \texttt{what}). In fact, \textit{primary archetypes} can be used to represent any fact and abstract meaning \cite{bos2016expressive}, while the \textit{secondary archetypes} can cover all the discourse relations between them (at least according to the PDTB theory). \section{Experiments} \label{sec:experiments} In section \ref{sec:proposed_solution:theory} we argued that the degree of explainability of any collection of text (e.g., the output of a XAI-based system) can be measured in terms of \ac{DoX} on a set of chosen \textit{explanandum aspects}. In order to verify this assertion and hypothesis \ref{hyp:main}, we have to show that there is a strong correlation between our \ac{DoX} and the perceived amount of \textit{explainability}. To this end, we devised two experiments using some XAI-based systems: \begin{itemize} \item a Heart Disease Predictor based on XGBoost \cite{chen2016xgboost} and TreeSHAP \cite{lundberg2020local}; \item a Credit Approval System based on a simple Artificial Neural Network and on CEM \cite{dhurandhar2018explanations}. \end{itemize} In particular, with the first experiment we measure explainability \textit{directly}, while with the second we perform \textit{indirect} measurements obtained through user-studies with human subjects. Measuring explainability \textit{directly} is not possible without a metric like the one we propose (\ac{DoX}), except for a few naive cases. One of these cases is surely when a simple XAI-based system is considered. In fact, in a standard XAI-based system, the amount of \textit{explainability} is (by design) clearly and explicitly dependent on the output of the underlying \ac{XAI}, for the black-box not being explainable by nature. Thus, by masking the output of the \ac{XAI} the overall system can be forced to be not explainable enough. This characteristic can be used to partially verify hypothesis \ref{hyp:main}, but not in a generic way, because this type of verification is based on a comparison with a total lack of explainability and not with different degrees of it. This is the reason we decided to measure explainability also \textit{indirectly} with a second experiment, to understand whether \ac{DoX} correlates with the expected effects of explainability on human subjects. In other terms, we have to compare \ac{DoX} to existing metrics for explainability based on Cognitive Science (e.g., usability, effectiveness) as shown in table \ref{tab:literature_comparison}. In fact, if hypothesis \ref{hyp:main} is correct, the lower is the \ac{DoX} score, the fewer explanations can be extracted, the less effective (as per ISO 9241-210) an explainee is likely to be in achieving explanatory goals that are not covered by the explanations. More specifically, effectiveness here is defined as \quotes{accuracy and completeness with which users achieve specified goals}, and in our case it is measured through multiple-choice domain-specific quizzes. Hence, once all the components that may affect effectiveness were fixed, including the explanandum and the presentation logic (i.e., the mechanism for re-elaborating explainable information into explanations), we expecte that an increase in \ac{DoX} always corresponds to an increase in effectiveness, at least on those tasks covered by the information provided by the increment of \ac{DoX}. To show this, we borrowed and extended the results of two independent user-studies \cite{sovrano2021philosophy,sovrano2022generating}, observing how \ac{DoX} correlates with the effectiveness scores measured by these studies. Therefore, in the following sub-sections we present: \begin{itemize} \item the two XAI-based systems object of these experiments; \item the pertinence functions $p$ and threshold $t$ that we considered for computing the \ac{DoX} scores and why; \item the sets $A$ of \textit{explanandum aspects} that were identified in each experiment. \end{itemize} \subsection{XAI-Based Systems} \label{sec:experiments:xai_based_systems} The XAI-based systems we considered for the two experiments of this paper are a Credit Approval System and a Heart Disease Predictor, respectively on finance and healthcare topics. Both these systems are an example of normal \textit{XAI-based explainer}, a one-size-fits-all explanatory mechanism providing the bare output of the \ac{XAI} as fixed explanation for all users, together with the output of the wrapped AI, a few extra details to ensure the readability of the results, and a minimum of context. \subsubsection{Finance: Credit Approval System} The Credit Approval System is the same used also by \cite{sovrano2021philosophy,sovrano2022generating} and it has been designed by IBM to showcase AIX360\footnote{\url{https://aix360.mybluemix.net/explanation_cust}}. In particular, the explanandum of the Credit Approval System is about finance and the system is used by a bank. The bank deploys an Artificial Neural Network to decide whether to approve a loan request, and it uses CEM \cite{dhurandhar2018explanations} to create post-hoc contrastive explanatory information. This information is meant to help the customers, showing them which minimal set of factors is to be manipulated for changing the outcome of the system from denial to approval (or vice versa). The Artificial Neural Network behind the Credit Approval System was trained on the \quotes{FICO HELOC} dataset\footnote{\url{https://fico.force.com/FICOCommunity/s/explainable-machine-learning-challenge?tabset-3158a=a4c37}}, containing anonymized information about loan applications made by real homeowners. Importantly, the Artificial Neural Network is trained to answer the following question: \quotes{What is the decision on the loan request of applicant X?}. Given the specific characteristics of the Credit Approval System, it is possible to assume that the main goal of its users is to understand what are the causes behind a loan rejection and what to do for getting a loan accepted. This is why CEM is deployed to answer the following questions: \begin{itemize} \item What are the easiest factors to consider in order to change the result of the application of applicant X? \item How factor F should be modified in order to change the result of the application of applicant X? \item What is the relative importance of factor F in changing the result of the application of applicant X? \end{itemize} Nonetheless, many other relevant questions might be to answer before a user of the system can be satisfied, reaching its goals. These questions include: \quotes{How to perform those minimal actions?}, \quotes{Why are these actions so important?}, etc. Finally, to summarise, the output of the Credit Approval System is composed by: \begin{itemize} \item Context: a titled heading section kindly introducing Mary (the user) to the system. \item AI Output: the decision of the Artificial Neural Network for the loan application. This decision normally can be \quotes{denied} or \quotes{accepted}. For Mary it is: \quotes{denied}. \item \ac{XAI} Output: a section showing the output of CEM. This output consists in a minimal ordered list of factors that are the most important to change for the outcome of the AI to switch. \end{itemize} A screenshot of this Credit Approval System is shown in figure \ref{fig:nxe_ca}. \begin{figure}[!htb] \centering \includegraphics[width=.99\columnwidth]{figures/nxe_ca} \caption{\textbf{Screenshot of the Credit Approval System}} \label{fig:nxe_ca} \end{figure} \subsubsection{Health: Heart Disease Predictor} Similarly to the Credit Approval System, also the Heart Disease Predictor comes from \cite{sovrano2022generating}. In particular, the explanandum of the Heart Disease Predictor is about health and the system is used by a first level responder of a help-desk for heart disease prevention. More specifically, a first level responder is responsible for handling the requests for assistance of a patient, forwarding them to the right physician in the eventuality of a reasonable risk of heart disease. First level responders get basic questions from callers, they are not doctors but they have to decide on the fly whether the caller should speak to a real doctor or not. So, they quickly use the Heart Disease Predictor to figure out what to answer to the callers and what are the next actions to suggest. In other words, this system is used directly by the responder, and indirectly by the caller through the responder. These two types of users have different but overlapping goals and objectives. It is reasonable to assume that the goal of the responders is to answer in the most efficient and effective way the questions of a caller. The Heart Disease Predictor uses XGBoost \cite{chen2016xgboost} to predict the likelihood of a patient having a heart disease given its demographics (gender and age), health (diastolic blood pressure, maximum heart rate, serum cholesterol, presence of chest-pain, etc.) and the electrocardiographic (ECG) results. This likelihood is classified into 3 different risk areas: low (probability $p$ of heart disease below 0.25), medium ($0.25 < p < 0.75$) or high. Therefore, XGBoost is used to answer the following questions: \begin{itemize} \item How is likely that patient X has a heart disease? \item What is the risk of heart disease for patient X? \item What is the recommended action, for patient X to cure or prevent a heart disease? \end{itemize} More specifically, the dataset used to train XGBoost is the \quotes{UCI Heart Disease Data} \cite{detrano1989international,alizadehsani2019database}. On top of XGBoost, the Heart Disease Predictor uses TreeSHAP \cite{lundberg2020local}, a famous \ac{XAI} algorithm specialised on tree ensemble models (i.e., XGBoost) for post-hoc explanations. In particular, TreeSHAP is used to understand what is the contribution of each feature to the output of XGBoost. Therefore, TreeSHAP is used to answer the following questions: \begin{itemize} \item What would happen if patient X would have factor Y (e.g., chest-pain) equal to A instead of B? \item What are the most important factors contributing to the predicted likelihood of heart disease, for patient X? \item How factor Y contributes to the predicted likelihood of heart disease, for patient X? \end{itemize} Nonetheless, many other important questions should probably be answered, including: \quotes{What is the easiest thing that the patient could actually do to change his heart disease risk from medium to low?}, \quotes{How could the patient avoid raising one of the factors, preventing his heart disease risk to raise?}, etc. Finally, to summarise, the output of the Heart Disease Predictor is composed by: \begin{itemize} \item Context: a titled heading section kindly introducing the responder (the user) to the system. \item AI Inputs: a panel for inserting the patient's parameters. \item AI Outputs: a section displaying the likelihood of heart disease estimated by XGBoost and a few generic suggestions about the next actions to suggest. \item \ac{XAI} Outputs: a section showing the contribution (positive or negative) of each parameter to the likelihood of heart disease, generated by TreeSHAP. \end{itemize} A screenshot of this Heart Disease Predictor is presented in figure \ref{fig:nxe_hd}. \begin{figure}[!htb] \centering \includegraphics[width=.99\columnwidth]{figures/nxe_hd} \caption{\textbf{Screenshot of the Heart Disease Predictor}} \label{fig:nxe_hd} \end{figure} \subsection{Pertinence Functions and Thresholds} \label{sec:experiments:pertinence} In order to compute \ac{DoX}, according to definition \ref{def:DoX}, we need to define a pertinence function $p$ and pick a threshold $t$. As discussed in section \ref{sec:proposed_solution:practice}, we are interested in using as pertinence function $p$ a deep language model for answer retrieval. Though, the point is that many different deep language models exist for this task, i.e. \cite{guo2020multireqa,sovrano2020legal,karpukhin2020dense}, and each one of them has different characteristics producing different pertinence scores. So, which model is the right one for computing the \ac{DoX}? Can we use any model? To answer these questions, during our experiments we decided to study the behaviour of more than one deep language model as pertinence function $p$. Hence the models we considered are: \begin{itemize} \item FB: published by \cite{karpukhin2020dense} and \cite{reimers2019sentence}. FB has been trained on the combination of the following datasets: Natural Questions \cite{kwiatkowski2019natural}, TriviaQA \cite{joshi2017triviaqa}, WebQuestions \cite{berant2013semantic}, and CuratedTREC \cite{baudivs2015modeling}. \item TF: or Multilingual Universal Sentence Encoder \cite{yang2019multilingual}. TF has been trained on the Stanford Natural Language Inference corpus \cite{bowman2015large}. \end{itemize} Furthermore, we found that different pertinence thresholds $t$ had to be considered for TF and FB. In particular, on the two XAI-based systems presented in section \ref{sec:experiments:xai_based_systems}, a good pertinence threshold for FB is $t=0.55$, while for TF is $t=0.15$. \subsection{1st Experiment: Direct Evaluation on XAI-generated Explanations} \label{sec:experiments:exp1} The 1st experiment is meant to shed more light on how a few changes to the explainability of a system affect the estimated \ac{DoX}. Specifically, \ac{XAI}-based systems are considered for this experiment, instead of other AI-based systems, because their amount of \textit{explainability} is by design, clearly and explicitly dependent on the output of the underlying \ac{XAI}. So that, by masking the output of the \ac{XAI}, the overall system can be forced to be less explainable. Hence, this characteristic can be exploited to (at least partially) verify hypothesis \ref{hyp:main}, in a very simple but effective way. In other words, a \ac{XAI}-based system is composed by a black-box AI-system wrapped by a \ac{XAI}. So, with this experiment we compare the \ac{DoX} of a normal \ac{XAI}-based explainer with that of the same system without the \ac{XAI}, also called normal \textit{AI-based explainer}. As result, we expect the (average) \ac{DoX} of the \ac{XAI}-based explainer to be clearly higher than that of its wrapped AI-based system. For this experiment, we used the XAI-based systems defined in section \ref{sec:experiments:xai_based_systems}. Therefore, by simply removing the output of the \ac{XAI} (respectively CEM and TreeSHAP) from these systems we obtain the \textit{AI-based explainers} we need. In order to compute the (average) \ac{DoX} of these systems, we take as set of \textit{explanandum aspects} those targeted by the Credit Approval System and the Heart Disease Predictor. More precisely, the main \textit{explanandum aspects} $A$ targeted by XGBoost \cite{chen2016xgboost} and TreeSHAP \cite{lundberg2020local} in the Heart Disease Predictor are 5: \begin{itemize} \item The recommended action for patient X \item The most important factors that contribute to predict the likelihood of heart disease \item The likelihood of heart disease \item The risk R of having a heart disease \item The contribution of Y to predict the likelihood of heart disease for patient X \end{itemize} While the main \textit{explanandum aspects} $A$ targeted by the Artificial Neural Network and CEM \cite{dhurandhar2018explanations} in the Credit Approval System are 4: \begin{itemize} \item The easiest factors to consider for changing the result \item The relative importance of factor F in changing the result of applicant X's application \item Applicant X's risk performance \item The result of applicant X's application \end{itemize} After properly converting the images produced by the \textit{XAI-based explainers} to textual explanations, the resulting \textit{explanandum aspects coverage}\footnote{The \textit{explanandum aspects coverage} is the percentage of \textit{explanandum aspects} that are covered by explanations.} of both the Heart Disease Predictor and the Credit Approval System is 100\%, while that of their \textit{AI-based explainers} is respectively 60\% and 50\%. In particular, for estimating the \ac{DoX} we used the pipeline described in section \ref{sec:proposed_solution:practice}, extracting different sets of details $D$ from the textual representations of both the XAI-based and \textit{AI-based explainers}. Thus, we were able to compute the \ac{DoX} scores in accordance with definition \ref{def:DoX} by using: \begin{itemize} \item the set of archetypes $Q$ described in section \ref{sec:proposed_solution:practice:archetype_selection}, \item the pertinence functions $p$ and the thresholds $t$ presented in section \ref{sec:experiments:pertinence}, \item the aforementioned set of details $D$ and \textit{explanandum aspects} $A$. \end{itemize} Results are presented and discussed in section \ref{sec:results}. \subsection{2nd Experiment: Explainability vs Effectiveness} \label{sec:experiments:exp2} Unlike the first, this second experiment aims to understand if there is a correlation between \ac{DoX} and the effects of explainability on the explainees. In fact, we have that more explainability implies a greater ability to explain, therefore more explanations. In short, the lower the \ac{DoX}, the less explanations can be produced, the less effective is likely to be an explainee on the tasks related to the explanandum. So, if hypothesis \ref{hyp:main} would be correct, an increase in the \ac{DoX} of the (explanatory) system should always correspond to a proportional increase of its effectiveness, at least on those tasks covered by the information provided by the increment of \ac{DoX}. Therefore, to verify this point we borrowed and extended the user-studies published by \cite{sovrano2021philosophy,sovrano2022generating} and involving more than 160 human subjects. Importantly, these user-studies consider the same XAI-based systems used during the first experiment and described throughout section \ref{sec:experiments:xai_based_systems}. In particular, each user-study analyses the effectiveness of the explanations given by the XAI-systems, when changing the \textit{explanandum support material} and the way it is presented to the explainee. In the following sub-sections we will present the aforementioned user-studies more in detail. \subsubsection{1st User-Study: Finance} \label{sec:experiments:exp2:1st_study} \begin{figure*}[!htb] \begin{subfigure}{0.49\linewidth} \centering \includegraphics[width=1\linewidth]{figures/overview_modal_hd} \end{subfigure}% ~ \begin{subfigure}{0.49\linewidth} \centering \includegraphics[width=1\linewidth]{figures/overview_modal_hd2} \end{subfigure} \caption{ \textbf{Example of Overview}: this figure shows an example of interactive \textit{overview} displaying relevant information about important concepts for the Heart Disease Predictor. Clicking on any underlined word would open a new \textit{overview} in a new tab, as shown. Furthermore, every given answer is linked to its source document. } \label{fig:overview_modal_hd} \end{figure*} The first user-study comes from \cite{sovrano2021philosophy}. \cite{sovrano2021philosophy} present a novel mechanism, that we call \textit{overview-based explainer}, to explain large collections of heterogeneous documents (i.e., more than 50 web-pages) about the Credit Approval System, in a user-centred and interactive way. This is done by organising knowledge as a graph of abstract aspects whose related explanations are ordered by relevance and simplicity, according to a set of pre-defined archetypal questions (i.e., \texttt{what}, \texttt{how}, \texttt{when}, \texttt{why}, etc.). In particular, \textit{overviewing} can be performed iteratively from an initial explanation by clicking on annotated words for which an explanation (in the form of a cluster of questions and answers) is needed. An example of \textit{overview} is shown in figure \ref{fig:overview_modal_hd}. \begin{table}[!htb] \centering \caption{ \textbf{Quiz - Credit Approval System}: in this table are shown the questions used for the quiz on the Credit Approval System and their archetypes. The \quotes{Archetype} column indicates which interrogative particle is representative of the question. \textit{Steps} is the minimum number of steps (in terms of links to click, overviews to open and/or questions to pose) required by each explanatory tool. \quotes{NXE} stands for the normal \textit{XAI-based explainer}, while \quotes{Others} stands for the \textit{overview-based explainer} or its extensions described in section \ref{sec:experiments:exp2:2nd_study}. Negative \textit{steps} mean that the correct answer cannot be found, while 0 \textit{steps} means that the answer is immediately available without clicking on any link. } \label{tab:ca_quiz} \resizebox{\linewidth}{!}{ \arrayrulecolor{black} \begin{tabular}{|p{0.6\linewidth}|l|l|l|l|l|} \hline \rowcolor[rgb]{0.937,0.937,0.937} {\cellcolor[rgb]{0.937,0.937,0.937}} & {\cellcolor[rgb]{0.937,0.937,0.937}} & \multicolumn{2}{l|}{\textbf{Steps}} \\ \hhline{|>{\arrayrulecolor[rgb]{0.937,0.937,0.937}}-->{\arrayrulecolor{black}}--|} \rowcolor[rgb]{0.937,0.937,0.937} \multirow{-2}{*}{{\cellcolor[rgb]{0.937,0.937,0.937}}\textbf{Question}} & \multirow{-2}{*}{{\cellcolor[rgb]{0.937,0.937,0.937}}\textbf{Archetype}} & \textbf{NXE} & \textbf{\textbf{Others}} \\ \hline What did the Credit Approval System decide for Mary's application? & \texttt{what}, \texttt{how} & 0 & 0 \\ \hline What is an inquiry (in this context)? & \texttt{what} & -1 & 1 \\ \hline What type of inquiries can affect Mary's score, the hard or the soft ones? & \texttt{what}, \texttt{how} & -1 & 1 \\ \hline What is an example of hard inquiry? & \texttt{what} & -1 & 1 \\ \hline How can an account become delinquent? & \texttt{how}, \texttt{why} & -1 & 1 \\ \hline Which specific process was used by the Bank to automatically decide whether to assign the loan? & \texttt{what}, \texttt{how} & 0 & 0 \\ \hline What are the known issues of the specific technology used by the Bank (to automatically predict Mary's risk performance and to suggest avenues for improvement)? & \texttt{what}, \texttt{why} & -1 & 1 \\ \hline \end{tabular} } \end{table} To show that the \textit{overview-based explainer} generates more effective explanations, the authors compare the effectiveness scores of the Credit Approval System with a version of it enhanced by the \textit{overview-based explainer}. In particular, the effectiveness scores are generated by the users interacting with the system and answering a quiz (shown in table \ref{tab:ca_quiz}) on the Credit Approval System comprising 7 different questions. For this user-study 103 different participants were recruited (57 males, 44 females, 2 unknowns; ages 18-55) on the online platform Prolific \cite{palan2018prolific}. All the participants were recruited among those who: \begin{inparaenum} \item are resident in UK, US or Ireland; \item have a Prolific acceptance rate greater or equal to 75\%\footnote{Mainly because they are unlikely to answer poorly/randomly to questions.}. \end{inparaenum} Participants were randomly allocated to use either the Credit Approval System or its \textit{overview-based explainer}, in a between-subjects test. In the end, 51 participants evaluated the normal \textit{XAI-based explainer} and 52 evaluated the \textit{overview-based explainer}\footnote{For more details about the evaluation, please read \cite{sovrano2021philosophy}.}. \begin{figure}[!htb] \centering \includegraphics[width=.75\columnwidth]{figures/user_studies/1st_user_study_uncovered} \caption{\textbf{2nd Experiment - 1st User-Study}: Comparison of the median effectiveness scores obtained on the Credit Approval System (CA) with the normal \textit{XAI-based explainer} (NXE; the blue one) and the \textit{overview-based explainer} (OBE; the orange one) on those questions whose answer is not contained in the \textit{explanandum support material} of NXE. Results are shown in the form of box plots (25th, 50th, 75th percentile, and whiskers covering all data and outliers). The numerical value of medians is shown inside pink boxes. Differently from \cite{sovrano2021philosophy}, here effectiveness scores are normalised in $[0,100]$. } \label{fig:1st_user_study_uncovered} \end{figure} Importantly, the results of the user-study showed that the \textit{overview-based explainer} produces significantly better effectiveness statistics than its counterpart, especially on those questions (questions number 2, 3, 4, 5 and 7 in table \ref{tab:ca_quiz}) not covered by the \textit{explanandum support material} of the normal \textit{XAI-based explainer}, as shown in figure \ref{fig:1st_user_study_uncovered}. Indeed, the difference between a normal \textit{XAI-based explainer} and an \textit{overview-based explainer} is twofold. First of all, the explanations produce by the \textit{overview-based explainer} are interactive and more user-centred, while those of the normal XAI-based system are not. Secondly, the normal \textit{XAI-based explainer} considers a smaller amount of explainable information. In fact, the \textit{overview-based explainer} builds its explanations using more than 50 extra web-pages that its counterpart does not see. This last difference is exactly what allowed us to exploit the user-study, to verify hypothesis \ref{hyp:main}. In fact, the amount of information handled by the normal \textit{XAI-based explainer} is roughly $\frac{1}{100}$ of its \textit{overview-based explainer} and this is enough to say that its explainability is not none and it is probably the lowest amongst the two explainers. In order to use this first user-study, to show that an increment in \ac{DoX} causes a consequent increment in the effectiveness of the explanations, we have to compute the \ac{DoX} scores of a normal \textit{XAI-based explainer} and its \textit{overview-based explainer} as in the 1st experiment. To do so, we identified the set of \textit{explanandum aspects} $A$ from the quiz used to generate the effectiveness scores, applying on it the same technique for extracting the set of details $D$ mentioned in section \ref{sec:proposed_solution:practice}. In fact, the quiz defines exactly what the users should know in order to be effective, indirectly defining also what is important for the system to explain: the \textit{explanandum aspects}. The resulting \ac{DoX} scores are given in section \ref{sec:results}. \subsubsection{2nd User-Study: Health} \label{sec:experiments:exp2:2nd_study} The second user-study comes from \cite{sovrano2022generating}. Unlike the first though, this user-study is on the Heart Disease Predictor and it analyses an extension of the \textit{overview-based explainer} called YAI4Hu, together with other two explainers: a \textit{two-layered explainer} and a \textit{how-why explainer}. The \textit{two-layered explainer} is static, as the normal \textit{XAI-based explainer}, in fact it is made of the output a normal \textit{XAI-based explainer} directly connected to a 2nd (non-expandable) layer of information consisting in an exhaustive and verbose set of autonomous static explanatory resources. The \textit{two-layered explainer} is organized therefore as a very long text document (more than 50 pages per system, when printed), structured in titled sections and prefixed with a table of content with hypertext links. On the other hand, the \textit{how-why explainer} is like the \textit{overview-based explainer} but, differently from that, it uses only the archetypes \texttt{why} and \texttt{how} for generating explanations. Furthermore, also YAI4Hu is an extension the \textit{overview-based explainer} that instead adds a mechanism (called \textit{open questioning}) for users to ask their own questions to the system. More specifically, \textit{open questioning} can be performed asking questions in English through a search box that uses the same graph-based answer retrieval mechanism described in section \ref{sec:proposed_solution:practice}. Importantly, YAI4Hu, the \textit{how-why explainer} and the \textit{two-layered explainer} share the same explanandum support material of the \textit{overview-based explainer} (see section \ref{sec:experiments:exp2:1st_study} for more details). For the user-study, \cite{sovrano2022generating} recruited 64 different participants amongst the university students of the following courses of study\footnote{All the courses of study were of an Italian university, and only the master degrees were international, i.e., with English teachings and students from countries other than Italy.}: \begin{inparadesc} \item bachelor degree in computer science; \item bachelor degree in management for informatics; \item master degree in digital humanities; \item master degree in artificial intelligence. \end{inparadesc} The 64 participants were randomly allocated to test only one of the three types of explainers. In other words, similarly to the first user-study, also this second user-study followed a between-subjects design. In the end, there were approximatively 20 participants per explainer. \begin{table}[!htb] \centering \caption{ \textbf{Quiz - Heart Disease Predictor}: in this table are shown the questions used for the quiz on the Heart Disease Predictor and their archetypes. NXE stands for the normal \textit{XAI-based explainer}, HWN for the \textit{how-why explainer}, and 2EC for the \textit{two-layered explainer}. Furthermore, \quotes{no OQ} means that \textit{open questioning} cannot be used for correctly answering the question. For more details about how to read this table, see the caption of table \ref{tab:ca_quiz}. } \label{tab:hd_quiz} \resizebox{\linewidth}{!}{ \arrayrulecolor{black} \begin{tabular}{|p{0.6\linewidth}|l|l|l|l|l|} \hline \rowcolor[rgb]{0.937,0.937,0.937} {\cellcolor[rgb]{0.937,0.937,0.937}} & {\cellcolor[rgb]{0.937,0.937,0.937}} & \multicolumn{4}{l|}{\textbf{Steps}} \\ \hhline{|>{\arrayrulecolor[rgb]{0.937,0.937,0.937}}-->{\arrayrulecolor{black}}----|} \rowcolor[rgb]{0.937,0.937,0.937} \multirow{-2}{*}{{\cellcolor[rgb]{0.937,0.937,0.937}}\textbf{Question}} & \multirow{-2}{*}{{\cellcolor[rgb]{0.937,0.937,0.937}}\textbf{Archetype}} & \textbf{NXE} & \textbf{\textbf{2EC}} & \textbf{\textbf{HWN}} & \textbf{\textbf{YAI4Hu}} \\ \hline What are the most important factors leading that patient to a medium risk of heart disease? & \texttt{what}, \texttt{why} & 0 & 0 & 0 & 0 (no OQ) \\ \hline What is the easiest thing that the patient could actually do to change his heart disease risk from medium to low? & \texttt{what}, \texttt{how} & 0 & 0 & 0 & 0 (no OQ) \\ \hline According to the predictor, what level of serum cholesterol is needed to shift the heart disease risk from medium to high? & \texttt{what}, \texttt{how} & 0 & 0 & 0 & 0 (no OQ) \\ \hline How could the patient avoid raising bad cholesterol, preventing his heart disease risk to shift from medium to high? & \texttt{how} & -1 & 1 & 2 & 2 \\ \hline What kind of tests can be done to measure bad cholesterol levels in the blood? & \texttt{what}, \texttt{how} & -1 & 1 & -1 & 1 \\ \hline What are the risks of high cholesterol? & \texttt{what}, \texttt{why not} & -1 & 1 & 2 & 1 \\ \hline What is LDL? & \texttt{what} & -1 & 1 & 2 & 1 \\ \hline What is Serum Cholestrol? & \texttt{what} & -1 & 1 & 1 & 1 \\ \hline What types of chest pain are typical of heart disease? & \texttt{what}, \texttt{how} & -1 & 1 & 1 & 1 \\ \hline What is the most common type of heart disease in the USA? & \texttt{what} & -1 & 1 & 1 & 1 \\ \hline What are the causes of angina? & \texttt{what}, \texttt{why} & -1 & 1 & 2 & 1 \\ \hline What kind of chest pain do you feel with angina? & \texttt{what}, \texttt{how} & -1 & 1 & 1 & 1 \\ \hline What are the effects of high blood pressure? & \texttt{what}, \texttt{why not} & -1 & 1 & 1 & 1 \\ \hline What are the symptoms of high blood pressure? & \texttt{what}, \texttt{why}, \texttt{how} & -1 & 1 & 1 & 1 \\ \hline What are the effects of smoking to the cardiovascular system? & \texttt{what}, \texttt{why not} & -1 & 1 & 3 & 1 \\ \hline How can the patient increase his heart rate? & \texttt{how} & -1 & 1 & 3 & 1 \\ \hline How can the patient try to prevent a stroke? & \texttt{how} & -1 & 1 & 3 & 2 \\ \hline What is a Thallium stress test? & \texttt{what}, \texttt{why} & -1 & 1 & 3 & 1 \\ \hline \end{tabular} } \end{table} Each participant evaluated the effectiveness of the XAI-based system by answering a quiz shown in table \ref{tab:hd_quiz}. For more details about the evaluation, please read \cite{sovrano2022generating}. The results of the user-study published by \cite{sovrano2022generating} show that YAI4Hu produces significantly greater effectiveness scores than the \textit{how-why explainer}, and that the \textit{how-why explainer} is better than the \textit{two-layered explainer} as well. Though, considering that YAI4Hu, the \textit{how-why explainer} and the \textit{two-layered explainer} share the same \textit{explanandum support material} (of the \textit{overview-based explainer}), these results tell us only that changing the explainer might change the quality of the explanations. In other words, differently from the first user-study, these results do not show any improvement in effectiveness due to changes in the explainability of the \textit{explanandum support material}. Considering that, we decided to extend the user-study recruiting 19 more participants\footnote{We made sure that none of our 19 extra participants was involved in the user-study published by \cite{sovrano2022generating}.} from the same pool of users, asking them to answer the same quiz but with a normal \textit{XAI-based explainer}. Indeed, the normal \textit{XAI-based explainer} has a smaller \textit{explanandum support material} than the others. After this modification, also the second user-study can be used to check whether there is a correlation between the \ac{DoX} scores and the perceived effectiveness score. That is because we can compare the scores of the normal \textit{XAI-based explainer} against the others, in a situation where it is possible to study the effects on effectiveness of different \textit{explanandum support materials}. Hence, to do this comparison, similarly to the first user-study, we extracted the set of \textit{explanandum aspects} $A$ needed for computing the \ac{DoX} scores from the evaluation quizzes. As result we were able to identify $82$ \textit{explanandum aspects} for the Heart Disease Predictor. \section{Results} \label{sec:results} In this section we present and discuss the results of the experiments defined in section \ref{sec:experiments}. \subsection{1st Experiment} \label{sec:results:1st_experiment} \begin{table}[!htb] \caption[1st Experiment - Degree of Explainability]{ \textbf{1st Experiment - Degree of Explainability}\footnotemark: in this table \ac{DoX} and Average \ac{DoX} are shown for the Credit Approval System (CA) and the Heart Disease Predictor (HD). As columns we have the different explanatory mechanisms used for experiment 1: the normal \textit{AI-based explainer} (NAE) and the normal \textit{XAI-based explainer} (NXE). As rows we have different explainability estimates using different deep language models for computing pertinence: FB and TF. For simplicity, with \ac{DoX} we show only the \textit{primary archetypes}. } \label{tab:exp1_dox} \centering \resizebox{\linewidth}{!}{ \arrayrulecolor{black} \begin{tabular}{|l|l|l|l||l|l|} \hhline{~~----|} \multicolumn{2}{l|}{\multirow{2}{*}{}} & \multicolumn{2}{l||}{{\cellcolor[rgb]{0.937,0.937,0.937}}CA} & \multicolumn{2}{l|}{{\cellcolor[rgb]{0.937,0.937,0.937}}HD} \\ \hhline{~~----|} \multicolumn{2}{l|}{} & {\cellcolor[rgb]{0.937,0.937,0.937}}NAE & {\cellcolor[rgb]{0.937,0.937,0.937}}NXE & {\cellcolor[rgb]{0.937,0.937,0.937}}NAE & {\cellcolor[rgb]{0.937,0.937,0.937}}NXE \\ \hline {\cellcolor[rgb]{0.937,0.937,0.937}} & {\cellcolor[rgb]{0.937,0.937,0.937}}FB & 0.607 & 0.659 & 0.596 & 0.609 \\ \hhline{|>{\arrayrulecolor[rgb]{0.937,0.937,0.937}}->{\arrayrulecolor{black}}-----|} \multirow{-2}{*}{{\cellcolor[rgb]{0.937,0.937,0.937}}Avg DoX} & {\cellcolor[rgb]{0.937,0.937,0.937}}TF & 0.264 & 0.344 & 0.214 & 0.227 \\ \hline {\cellcolor[rgb]{0.937,0.937,0.937}} & {\cellcolor[rgb]{0.937,0.937,0.937}}FB & \begin{tabular}[c]{@{}l@{}}which: 0.63\\whose: 0.63\\how: 0.6\\when: 0.6\\what: 0.6\\why: 0.6\\where: 0.59\\who: 0.58\end{tabular} & \begin{tabular}[c]{@{}l@{}}which: 0.66\\whose: 0.66\\how: 0.66\\where: 0.66\\what: 0.66\\who: 0.66\\when: 0.65\\why: 0.65\end{tabular} & \begin{tabular}[c]{@{}l@{}}which: 0.6\\what: 0.6\\whose: 0.59\\why: 0.59\\how: 0.59\\where: 0.58\\who: 0.57\\when: 0.56\end{tabular} & \begin{tabular}[c]{@{}l@{}}which: 0.63\\what: 0.62\\whose: 0.62\\how: 0.62\\why: 0.61\\where: 0.61\\when: 0.59\\who: 0.58\end{tabular} \\ \hhline{|>{\arrayrulecolor[rgb]{0.937,0.937,0.937}}->{\arrayrulecolor{black}}-----|} \multirow{-2}{*}{{\cellcolor[rgb]{0.937,0.937,0.937}}DoX} & {\cellcolor[rgb]{0.937,0.937,0.937}}TF & \begin{tabular}[c]{@{}l@{}}what: 0.33\\when: 0.31\\which: 0.26\\why: 0.25\\whose: 0.24\\where: 0.23\\who: 0.23\\how: 0.2\end{tabular} & \begin{tabular}[c]{@{}l@{}}what: 0.4\\which: 0.37\\where: 0.37\\how: 0.36\\why: 0.36\\when: 0.35\\who: 0.33\\whose: 0.31\end{tabular} & \begin{tabular}[c]{@{}l@{}}why: 0.31\\what: 0.28\\when: 0.24\\whose: 0.22\\how: 0.21\\who: 0.21\\where: 0.2\\which: 0.2\end{tabular} & \begin{tabular}[c]{@{}l@{}}what: 0.28\\why: 0.28\\which: 0.25\\when: 0.24\\how: 0.22\\who: 0.21\\whose: 0.21\\where: 0.2\end{tabular} \\ \hline \end{tabular} } \end{table} \footnotetext{This table is different from that shown in \cite{sovrano2022how} because we used DoXpy v2.1 instead of DoXpy v1.0.} Computing the \ac{DoX} scores for the first experiment (described in section \ref{sec:experiments:exp1}), we got the results displayed in table \ref{tab:exp1_dox}. As expected, on both the XAI-based systems, the results of the first experiment neatly show that the (average) \ac{DoX} achieved by the normal \textit{XAI-based explainer} is way greater than its \textit{AI-based explainer}, regardless the adopted \textit{deep language model}. Although, as discussed in section \ref{sec:discussion}, we can see that TF and FB (the two adopted \textit{language models}) produce numerically different \ac{DoX} scores, suggesting that the choice of the pertinence function $p$ can sensibly impact on the value of \ac{DoX}. Considering that in the 1st experiment we arbitrarily picked a simple set of \textit{explanandum aspects}, what would happen if we would consider different and more complex explicanda and explanatory contents? Furthermore, the result of the 1st experiment is based on the comparison of the \ac{DoX} of a non-explainable system (i.e, the \textit{AI-based explainers}) with an explainable system, and this is a very peculiar and naive case to consider. Therefore, in order to fully verify hypothesis \ref{hyp:main} we need to understand whether \ac{DoX} is behaving properly also when explainability is present in different, non-zero, amounts. To do so, we envisage that explainability can be measured \textit{indirectly}, by studying the effectiveness of the resulting explanations on humans, as shown in section \ref{sec:results:2nd_experiment}. \subsection{2nd Experiment} \label{sec:results:2nd_experiment} With the second experiment we studied if there is a correlation between the effectiveness of the explainers described in section \ref{sec:experiments:exp2} and their \ac{DoX} scores. We do it by considering two different user-studies and by comparing the effectiveness scores of different explainers . The 1st user-study comes from \cite{sovrano2021philosophy}, while the 2nd is an extension to the user-study presented by \cite{sovrano2022generating}. The approach we followed to extend this latter study is described in section \ref{sec:experiments:exp2:2nd_study}. In particular, the results of the 1st user-study (summarised in figure \ref{fig:1st_user_study_uncovered}) show that the \textit{overview-based explainer} is statistically more effective than the normal \textit{XAI-based explainer}, on the Credit Approval System. In fact, according to a one-sided Mann-Whitney U-Test (a non-parametric version of the t-test for independent samples) there is enough statistical evidence\footnote{A $P < 0.05$ is normally considered to be a significant statistical evidence.} to claim that the \textit{overview-based explainer} is better ($U=849.5$, $P=0.007$) than the \textit{XAI-based explainer} on the questions covered by the increment in \ac{DoX} of the \textit{overview-based explainer} (questions number 2, 3, 4, 5 and 7 in table \ref{tab:ca_quiz}). This is true at least on the considered pool of subjects. For more details about these results, please read \cite{sovrano2021philosophy}. \begin{figure}[!htb] \centering \includegraphics[width=.75\columnwidth]{figures/user_studies/2nd_user_study_uncovered} \caption{\textbf{2nd Experiment - 2nd User-Study - Effectiveness Scores on Questions \textit{not covered} by the XAI-based explainer}: Comparison of the results achieved on the Heart Disease Predictor (HD) with the normal \textit{XAI-based explainers} (NXE) and the other explainers, only on those questions whose aspects are \textit{not covered} by the information presented by NXE. In particular, the other explainers are: the \textit{two-layered explainer} (2EC), the \textit{how-why explainer} (HWN) and YAI4Hu. Effectiveness scores are normalised in $[0,100]$. } \label{fig:2nd_user_study_uncovered} \end{figure} On the other hand, the results we got by extending the 2nd user-study are summarised in the box-plots of figure \ref{fig:2nd_user_study_uncovered}. In particular, these box-plots show the effectiveness score of the considered explainers on the questions that the normal \textit{XAI-based explainer} cannot answer (i.e., the questions with negative steps in the NXE column of table \ref{tab:hd_quiz}). As expected, also in this case we see the median effectiveness score of the normal \textit{XAI-based explainers} being significantly lower than the other explainer. More precisely, according to a one-sided Mann-Whitney U-Test ($U=40.0$, $P=0.0002$) there is enough statistical evidence to claim that YAI4Hu is better than the \textit{XAI-based explainer} on the questions covered by the increment in \ac{DoX} of the \textit{overview-based explainer}. Furthermore, there is also enough statistical evidence to claim that the \textit{two-layered explainer} ($U=48.0$, $P=0.003$) and the \textit{how-why explainer} ($U=65.5$, $P=0.02$) are significantly more effective than the normal XAI-based explainer. Now, if hypothesis \ref{hyp:main} is true, we would expect that the higher is \ac{DoX}, the higher is the effectiveness of an explainer. Importantly, the opposite is not necessarily true, in fact, two explainers (with different presentation logics; e.g., the \textit{two-layered explainer} and YAI4Hu) might have different effectiveness scores despite having the same \ac{DoX}. \begin{table}[!htb] \centering \caption{ \textbf{2nd Experiment - Degree of Explainability}: these scores are different from those of experiment 1 (table \ref{tab:exp1_dox}) because a different explanandum is considered for experiment 2. As columns we have the different explanatory mechanisms used for experiment 2: the normal \textit{XAI-based explainer} (NXE) and the \quotes{others}. For more details about how to read this table, refer to the caption of table \ref{tab:exp1_dox}. } \label{tab:exp2_dox} \resizebox{\linewidth}{!}{ \arrayrulecolor{black} \begin{tabular}{|l|l|l|l||l|l|} \hhline{~~----|} \multicolumn{2}{l|}{\multirow{2}{*}{}} & \multicolumn{2}{l||}{{\cellcolor[rgb]{0.937,0.937,0.937}}CA} & \multicolumn{2}{l|}{{\cellcolor[rgb]{0.937,0.937,0.937}}HD} \\ \hhline{~~----|} \multicolumn{2}{l|}{} & {\cellcolor[rgb]{0.937,0.937,0.937}}NXE & {\cellcolor[rgb]{0.937,0.937,0.937}}Others & {\cellcolor[rgb]{0.937,0.937,0.937}}NXE & {\cellcolor[rgb]{0.937,0.937,0.937}}Others \\ \hline {\cellcolor[rgb]{0.937,0.937,0.937}} & {\cellcolor[rgb]{0.937,0.937,0.937}}FB & 0.43 & 2.066 & 0.936 & 2.465 \\ \hhline{|>{\arrayrulecolor[rgb]{0.937,0.937,0.937}}->{\arrayrulecolor{black}}-----|} \multirow{-2}{*}{{\cellcolor[rgb]{0.937,0.937,0.937}}Avg DoX} & {\cellcolor[rgb]{0.937,0.937,0.937}}TF & 0.163 & 0.636 & 0.504 & 1.708 \\ \hline {\cellcolor[rgb]{0.937,0.937,0.937}} & {\cellcolor[rgb]{0.937,0.937,0.937}}FB & \begin{tabular}[c]{@{}l@{}} \texttt{how}: 0.58\\ \texttt{why}: 0.58\\ \texttt{what}: 0.57\\ \texttt{whose}: 0.56\\ \texttt{which}: 0.29\\ \texttt{where}: 0.28\\ \texttt{when}: 0.27\\ \texttt{who}: 0.27\end{tabular} & \begin{tabular}[c]{@{}l@{}} \texttt{which}: 2.42\\ \texttt{whose}: 2.37\\ \texttt{how}: 2.36\\ \texttt{why}: 2.35\\ \texttt{what}: 2.34\\ \texttt{where}: 2.24\\ \texttt{when}: 1.71\\ \texttt{who}: 1.71\end{tabular} & \begin{tabular}[c]{@{}l@{}} \texttt{which}: 1.18\\ \texttt{how}: 1.17\\ \texttt{what}: 1.16\\ \texttt{whose}: 1.15\\ \texttt{why}: 0.9\\ \texttt{when}: 0.89\\ \texttt{where}: 0.89\\ \texttt{who}: 0.88\end{tabular} & \begin{tabular}[c]{@{}l@{}} \texttt{what}: 3.95\\ \texttt{how}: 3.42\\ \texttt{which}: 2.95\\ \texttt{why}: 2.52\\ \texttt{whose}: 2.26\\ \texttt{when}: 2.23\\ \texttt{who}: 1.95\\ \texttt{where}: 1.91\end{tabular} \\ \hhline{|>{\arrayrulecolor[rgb]{0.937,0.937,0.937}}->{\arrayrulecolor{black}}-----|} \multirow{-2}{*}{{\cellcolor[rgb]{0.937,0.937,0.937}}DoX} & {\cellcolor[rgb]{0.937,0.937,0.937}}TF & \begin{tabular}[c]{@{}l@{}} \texttt{what}: 0.29\\ \texttt{why}: 0.23\\ \texttt{when}: 0.22\\ \texttt{who}: 0.21\\ \texttt{whose}: 0.2\\ \texttt{how}: 0.18\\ \texttt{which}: 0.13\\ \texttt{where}: 0.09\end{tabular} & \begin{tabular}[c]{@{}l@{}} \texttt{when}: 1.04\\ \texttt{what}: 1.02\\ \texttt{why}: 0.97\\ \texttt{which}: 0.93\\ \texttt{how}: 0.72\\ \texttt{who}: 0.65\\ \texttt{whose}: 0.65\\ \texttt{where}: 0.62\end{tabular} & \begin{tabular}[c]{@{}l@{}} \texttt{why}: 0.57\\ \texttt{what}: 0.56\\ \texttt{which}: 0.49\\ \texttt{how}: 0.48\\ \texttt{when}: 0.48\\ \texttt{where}: 0.48\\ \texttt{who}: 0.48\\ \texttt{whose}: 0.47\end{tabular} & \begin{tabular}[c]{@{}l@{}} \texttt{what}: 2.19\\ \texttt{how}: 1.77\\ \texttt{why}: 1.76\\ \texttt{when}: 1.76\\ \texttt{which}: 1.62\\ \texttt{whose}: 1.59\\ \texttt{who}: 1.58\\ \texttt{where}: 1.25\end{tabular} \\ \hline \end{tabular} } \end{table} Computing the \ac{DoX} scores for the second experiment we got the results shown in Table \ref{tab:exp2_dox}. These results confirm our expectations for them. In fact, they show that the \textit{two-layered explainer}, the \textit{overview-based explainer}, the \textit{how-why explainer} and YAI4Hu have higher \ac{DoX} scores than the normal \textit{XAI-based explainer}. \section{Discussion} \label{sec:discussion} The results presented in section \ref{sec:results} clearly show that \ac{DoX} behaves as expected, roughly confirming hypothesis \ref{hyp:main}. Indeed, we see that \ac{DoX} grows whenever a black-box AI is wrapped within a \ac{XAI} (as it should be) and that an increment of \ac{DoX} corresponds to a statistically meaningful increase in the effectiveness of the explanatory system. In particular, the results of the 1st experiment tell us that whenever new information about different aspects to be explained is added to the \textit{explanandum support material}, the \ac{DoX} scores increase, and this is also true when changing the set of \textit{explanandum aspects}, as we did with the 2nd experiment. Furthermore, the results of the 2nd experiment tell us that whenever the \ac{DoX} scores increase, the overall effectiveness of the explanations generated from the \textit{explanandum support material} increases as well. This is true even for the \textit{two-layered explainer}, despite the fact that it is not interactive and it does not re-organise information to make it simpler and easier to access, dumping on the user hundreds of pages of content. Our user-studies involved more than 160 participants and were consistent across two fairly different and broad user pools, producing statistically significant results (hence with $P$ values lower than $0.05$). Therefore, considering that \textit{explainability} is fundamentally the \textit{ability to explain}, the two experiments combined together tell us that our (average) \ac{DoX} can quantitatively approximate the degree of explainability of information. In other words, we conclude from our experiments that \ac{DoX} \textit{can} be used as proxy for measuring the explainability of an explanatory system, as long as a set of \textit{explanandum aspects} can be defined. In fact, \ac{DoX} is deterministic and fully objective, and it could be used as a cheaper alternative to expensive non-deterministic user-studies. We are convinced that \ac{DoX} may have a role on all applications where it is important to objectively evaluate explainability. Indeed, the main benefit of \ac{DoX} is the fact that it works with any set of \textit{explanandum aspects} $A$, and therefore it can be used to quantify how the explanations given by an AI are aligned with any of the Business-to-Business and Business-to-Consumer requirements as identified in \cite{bibal2021legal}. In particular, for each Business-to-Business and Business-to-Consumer requirement we may have the following set of \textit{explanandum aspects} $A$: \begin{itemize} \item \textit{Providing the main features used in a decision by the AI}: $A$ can simply be the set of main feature labels used for a decision. This list can be generated with a XAI like CEM, TreeSHAP or others. \item \textit{Providing all features processed by the AI}: in this case $A$ is the set of all the feature labels considered by the AI. \item \textit{Providing a comprehensive explanation of a specific decision taken by the AI}: $A$ can be the set of aspects deemed relevant to the decision of the AI, i.e. what is the AI, what are the known issues of the AI, or all the other aspects discussed in \cite{sovrano2020modelling}. \item \textit{Providing the underlying logical model followed by the AI}: in this case $A$ can be the set of all the nouns or noun/verbal phrases used in the textual description of the logical model of the AI. \end{itemize} In this sense, the benefits of using \ac{DoX} over a normal user-study are manifold, in fact: \begin{itemize} \item it reduces testing costs normally sustained during subject-based evaluations; \item it allows to directly measure the degree of explainability of any piece of information that has a meaningful textual representation written in a natural language (i.e., English); \item it disentangles the evaluation of the \textit{explanandum support material} from that of the explainer (or presentation logic) and of the interface. \end{itemize} In other terms, \ac{DoX} is a fully objective metric that could be used to understand whether a piece of information is sufficient to explain something regardless of whether the resulting explanations have happened to be perceived as satisfactory and good by the explainees. We deem this characteristic of \ac{DoX} to be very important: a poor degree of explainability objectively implies poor explanations, no matter how good the adopted explanatory process is (or how it is perceived): \quotes{Users also do not necessarily perform better with systems that they prefer and trust more. To draw correct conclusions from empirical studies, explainable AI researchers should be wary of evaluation pitfalls, such as proxy tasks and subjective measures} \cite{buccinca2020proxy}. \section{Limitations and Future Work} \label{sec:limitations} Despite all the good properties supported by both theory and empirical results, we found that \ac{DoX} may have limitations that we plan to address in future works. First of all, the results of the 2nd experiment show that explanatory systems with the same \ac{DoX} could be usable and effective in different ways. Indeed, this points to the fact that \ac{DoX} should not be considered as a total replacement to user studies, but rather as a cheaper alternative to consider while developing complex explanatory systems. In other words, \ac{DoX} cannot fully replace subjective metrics (i.e., usability) if one wants to evaluate the user-centrality of an explanatory system or interface. On the other hand, \ac{DoX} is probably better than subjective metrics if one wants to objectively evaluate the contents of an explanatory system, so as to understand how many questions can be properly answered: the higher \ac{DoX}, the greater the chances to properly explain to a variety of users. Secondly, the numerical differences between the \ac{DoX} estimates shown in table \ref{tab:exp1_dox} and \ref{tab:exp2_dox} suggest that our algorithm for computing \ac{DoX} scores may be sensitive to the choice of deep language model for pertinence estimation (see section \ref{sec:experiments:pertinence}). In fact, on the one hand we see that the difference in terms of \ac{DoX} between the normal \textit{XAI-based explainers} and the other explainer tend to differ from TF to FB. Nonetheless, we also see that in all the considered experiments the \ac{DoX} scores increase as expected, with both TF and FB, suggesting that the alignment of \ac{DoX} to \textit{explainability} is independent from the chosen deep language model. This intuition is supported by the fact that both TF and FB, in average, perform reasonably well on existing benchmarks for evaluating answer retrieval algorithms. In other words, if the Average \ac{DoX} aggregates enough archetypes, aspects and details, then different pertinence functions performing in similar ways on standard benchmarks may produce proportionally similar Average \ac{DoX} scores. This does not exclude the fact that there might be deep language models that are better than others for computing the \ac{DoX} score, or that multiple standardised deep language models should be adopted for a thorough estimate of the \ac{DoX}. We leave this analysis for future work. Another possible limitation of \ac{DoX} is that its scores cannot be easily normalised in a $[0,1]$ range. In fact, according to definition \ref{def:DoX}, \ac{DoX} is computed by performing a sum (called \textit{cumulative pertinence}) over the set of details $D$ extracted from an \textit{explanandum support material}, so that \ac{DoX} is able to measure the similarity of the \textit{explanandum support material} to the explanandum. Unfortunately, it is not possible to know in advance the total number of details of any possible \textit{explanandum support material} and therefore it is not possible to normalize the score by dividing the \textit{cumulative pertinence} by such number. It is worth noting that such sum is necessary. Indeed, if the \textit{cumulative pertinence} were a mean instead of a sum, then the resulting score for an \textit{explanandum support material} could not be compared to that of any larger (in terms of number of details) \textit{explanandum support material}, making pointless the use of \ac{DoX} in the first place. Furthermore, it is important to mention that \ac{DoX}, alone, is not sufficient for a thorough quantification of how much of the information is explained by an AI. In fact, our definition of \ac{DoX} does not take into consideration the correctness of information of the \textit{explanandum support material}, assuming that truth is given and that it is a different thing from explainability. In other terms, \ac{DoX} should always be used in combination with other metrics that describe how correct the available information is. Finally, as discussed in section \ref{sec:discussion}, although \ac{DoX} can be used to verify many of the requirements defined by \cite{bibal2021legal}, it is still unclear how to apply \ac{DoX} to verify also Government-to-Citizen legal requirements. In fact, being able to select a reasonable threshold of \ac{DoX} scores for law-compliance is certainly one of the next challenges we envisage for a proper standardisation of \textit{explainability} in the industrial context. We also leave these analyses for future work. \section{Conclusions} \label{sec:conclusions} In this paper, we proposed a new metric for explainability called \ac{DoX} that could be used to objectively quantify how much of the information is explained by an AI. For instance, \ac{DoX} can be used to verify the satisfaction of Business-to-Business and Business-to-Consumer requirements as defined by \citeauthor{bibal2021legal} \cite{bibal2021legal}. \ac{DoX} is based on the intuition coming from Achinstein’s theory of explanations that explaining is an act of illocutionary question answering. Specifically, \ac{DoX} frames explanations as answers to many simple questions (\textit{archetypes}) shedding light over the concepts being explained, so that the more (archetypal) answers a corpus is able to give about important aspects of an explanandum, the more that corpus is explainable. Thus \ac{DoX} is the first explainability metric based on Ordinary Language Philosophy and it is a model-agnostic and deterministic approach that can work with any corpus of explainable information represented in natural language (i.e., English). In particular, \ac{DoX} quantifies the three main criteria of explainability adequacy defined by Carnap: similarity, exactness, and fruitfulness. In this sense, our contribution is a mechanism for quantifying Carnap's criteria and aggregating them together in one single score called Average \ac{DoX}, used to compare the degree of explainability of different explanatory systems. \ac{DoX} can quantify the degree of explainability of a corpus of information by estimating how adequately that corpus could answer an arbitrary set of archetypal questions about the concepts of an explanandum. Throughout the paper we also presented a concrete implementation of \ac{DoX} called DoXpy. In order to understand whether the \ac{DoX} is actually behaving as expected, we designed a few experiments on two realistic AI-based systems for heart disease prediction and credit approval, involving state of the art AI technologies such as as Artificial Neural Networks, TreeSHAP \cite{lundberg2020local}, XGBoost \cite{chen2016xgboost} and CEM \cite{dhurandhar2018explanations}. The results we obtained show that the \ac{DoX} is aligned with our expectations, and that it can be used to quantify \textit{explainability} in natural language information corpora. Although \ac{DoX} cannot be used directly on a black-box model to understand how much of it can be explained, it can be used on the output of an ensemble of \acp{XAI} or any other explainable information (i.e., documentation, papers, books, etc.) to understand how that information can be used to explain. In this sense, \ac{DoX} is the most useful when used to evaluate large collections of explainable information (i.e., the output of an ensemble of \acp{XAI}). Another context of application of \ac{DoX} could be education. Not surprisingly, many would argue that explanations are one of the main artefacts through which humans understand reality and learn to solve complex problems \cite{berland2009making}. Therefore, \textit{explaining} is not only central to \ac{XAI} but also to education, and these are two contexts where our technology and our understanding of explanations could be of utmost importance. \bibliographystyle{cas-model2-names}
{'timestamp': '2022-09-01T02:13:34', 'yymm': '2109', 'arxiv_id': '2109.05327', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05327'}
arxiv
\section{Introduction} \label{Introduction} Accurate localization of anatomical landmarks is a fundamental step for numerous medical imaging applications such as image registration and shape analysis \cite{regression-forest,Deep-Anatomical-Cephalometric,regression-voting,Two-StageTask-Oriented,deep-landmark-medical}. It also has the potential to advance the early recognition of those affected by prenatal alcohol exposure \cite{FAS}, \cite{DSNT}. Prenatal alcohol exposure (PAE) damages the developing central nervous system, resulting in a continuum of effects \cite{PAE}. Conditions that result from PAE are collectively known as fetal alcohol spectrum disorders (FASDs). Fetal alcohol syndrome (FAS) is the most severe outcome in this spectrum, characterized by restricted growth, neurobehavioral deficits, and facial dysmorphism \cite{FASD}. The diagnosis of FAS requires at least 2 of 3 cardinal facial features; a smooth philtrum, a thin upper lip, and a reduced palpebral fissure length (PFL)\cite{PAE,FASD}. Conventional clinical approaches \cite{PFL,three-facial} for facial assessment rely on manual examination, using a ruler for PFL measurement, and a Likert-scale comparison chart for the lip and philtrum, as depicted in Fig. \ref{fas_illustration}. Clinical examination is necessarily subjective, with accuracy heavily reliant on the skill and experience of the clinician. Consequently, there is poor inter-rater reliability, and underdiagnosis and misdiagnosis of FASDs are a common occurrence \cite{three-facial}. Therefore, automatically localizing anatomical landmarks, as shown in Fig. \ref{landmark_illustration}, is seen as a crucial part of the clinical workflow to provide objective measurements for recognition of FASD. \begin{figure}[t] \centering \setlength{\belowcaptionskip}{-0.5cm} \includegraphics[width=0.85\linewidth]{fas_illustration.pdf} \caption{Conventional clinical approaches for extracting diagnostic facial features of fetal alcohol syndrome (FAS). (Image credit: \cite{PFL}, \cite{youtube})} \label{fas_illustration} \end{figure} \begin{figure}[t] \centering \setlength{\belowcaptionskip}{-0.5cm} \includegraphics[width=0.9\linewidth]{landmark_markup.pdf} \caption{Illustration of anatomical landmarks used in this study.} \label{landmark_illustration} \end{figure} With the rapid development of deep learning, recent years have witnessed important advances in automation of various medical imaging tasks \cite{Unet}. Included in this, recent approaches for anatomical landmark detection \cite{Deep-Anatomical-Cephalometric,regression-voting,Two-StageTask-Oriented, deep-landmark-medical, DSNT}, have often leveraged the power of deep neural networks, due to the ability to capture hierarchical representations from raw data, and have achieved promising performance. However, anatomical landmark detection in our imaging application remains a challenge due to the large appearance variation of faces, different age groups and ethnic background, as exemplified in Fig. \ref{dataset_illustration}. One feasible solution to mitigate the challenge is to utilize backbone CNN architectures (e.g. VGG16 \cite{vgg16} or ResNet50 \cite{resnet}) trained on a large-scale and diverse image dataset, such as VGGFace2 \cite{VGGFACE2}, which can be fine-tuned or specialized with additional task-specific layers to promote the optimization of facial anatomical landmark detection \cite{self-supervised,mobileFAN}. Finetuning, as a common paradigm in transfer learning \cite{transfer-learning}, aims to benefit the target task by providing a good initialization, but it can require exhaustive tuning or a set of ad-hoc hyper-parameters to achieve good performance \cite{Inductive-TL,DELTA}. Furthermore, limited availability of labeled data, which often occurs in the medical domain, can result in overfitting in transfer learning, leading to poor accuracy for the desired task\cite{Two-StageTask-Oriented}. \begin{figure}[t] \centering \setlength{\belowcaptionskip}{-0.5cm} \includegraphics[width=0.85\linewidth]{dataset_illustration.pdf} \caption{Examples of facial phenotypes in our challenging dataset.} \label{dataset_illustration} \end{figure} To address this, $L^{2}$ regularization, also known as weight decay, has been frequently suggested to reduce the effect of overfitting by regularizing the parameter search space \cite{Inductive-TL}. However, such a regularizer may not perform well in transfer learning, especially, and as in our case, when transferring knowledge across different tasks (classification $\rightarrow$ regression). We illustrate this in Fig. \ref{justification_results} (b) which shows that standard fine-tuning with weight decay ignores useful facial semantics or patterns (see Fig. \ref{justification_results} (a)) which are related to the target task of landmark detection, but instead can pay attention to irrelevant regions. To this end, we argue that the target (fine-tuned) model should not only focus on adjusting the pre-trained weights, but also learn how to ``behave" as a source model does \cite{DELTA}, so that facial semantics can be explicitly reused to improve learning of the landmark detector, as shown in Fig. \ref{justification_results} (c). Therefore, we propose to retain feature responses of a source classification model given the target task data to regularize landmark detection optimization, as shown in Section \ref{Regularized Transfer Learning for Anatomical Landmark Detection}. Inspired by knowledge distillation for model compression \cite{knowledge-distillation,hint-learning,attention-transfer}, we develop four regularization strategies during fine tuning, including constraining the feature outputs from classification and intermediate layers, as well as matching activation attention maps in both spatial and channel levels which are shown to provide more comprehensive representations, as depicted in Fig. \ref{justification_results} (d). Extensive experimental evaluations reported in Section \ref{Experiments}, demonstrate that the proposed framework generalizes well in anatomical landmark detection with limited training samples and favorably outperforms other solutions from the literature. This paper considerably extends our preliminary work in \cite{CTRL}, developing a unified regularized transfer learning framework for localizing anatomical landmarks in fetal alcohol syndrome. The new contributions of this paper relative to \cite{CTRL} are, 1) we present a more detailed justification of the proposed framework as well as its importance with additional illustrations. 2) we propose two additional regularization constraints based on spatial and channel attention maps which improve localization accuracy relative to results reported in \cite{CTRL}. The technical details of each solution in the proposed framework are explained. 3) Experimentally, we provide an in-depth analysis of different proposed regularization strategies, analyze the effectiveness of different pre-trained source models for the proposed framework, study the impact of different parameter selection and include detailed comparisons with further related methods both quantitatively and qualitatively. 4) we provide a detailed discussion to discuss the strengths and the limitations of our approaches and suggest their translational potentials. \begin{figure}[t] \centering \setlength{\belowcaptionskip}{-0.3cm} \includegraphics[width=0.95\linewidth]{justification.pdf} \caption{Illustration of top-level activation attention maps for different approaches given an image in the target dataset, where (a) represents the original source model, (b) is the fine-tuned model with weight decay, (c) denotes the proposed regularization constraint on intermediate layer outputs, and (d) demonstrates the proposed regularization constraint on spatial attention maps.} \label{justification_results} \end{figure} The rest of the paper is structured as following: Section \ref{Related-Work} discusses the most closely related work to the proposed approach. Section \ref{Method} formulates the problem considered and details the proposed solution via regularized transfer learning. In Section \ref{Experiments}, we perform extensive experimental evaluations. Finally, following the Discussion in Section \ref{Discussion}, Section \ref{Conclusions} draws conclusions and suggests some future directions of research. \section{Related Work} \label{Related-Work} \subsection{Anatomical Landmark Detection} In the literature, there has been significant progress on automatic landmark (keypoint) detection of natural images, which has in turn advanced human pose estimation, and facial alignment. Existing methods for this task include random forest \cite{regression-forest,geometric-configuration} and cascaded shape regression \cite{explicit-regression,cascaded-pose}. Convolutional neural networks (CNN) based regression has become a recently popular approach for keypoint localization \cite{stacked-hourglass,mobileFAN,wing-loss,high-resolution}. Two CNN-based architecture designs have emerged: direct coordinate regression \cite{facial-attribute,wing-loss} and heatmap regression \cite{stacked-hourglass,simple-baseline}, where the latter usually outperforms the former, due to the advantage of preserving higher spatial resolution for accurate localization. Methods based on U-Net \cite{Unet}, a stacked hourglass \cite{stacked-hourglass}, and simple-baseline \cite{simple-baseline} CNN architectures have achieved good performance on the challenging keypoint detection benchmarks (e.g. MPII benchmark \cite{mpii}). Different from generic keypoint localization in natural images, anatomical landmark detection in medical imaging is often constrained by the scarcity of labeled data, as annotating abundant landmarks in the medical domain is expensive. To accommodate this, some existing methods have considered cascaded CNNs following a coarse-to-fine strategy \cite{deep-landmark-medical,Two-Stage-Task-Oriented,spatial-configuration}. Although cascaded designs can give good results, they require additional computational efforts, where repeatedly extracting similar low-level features may not be necessary \cite{Attention-UNet}. On the other hand, attention mechanisms which were originally proposed for machine translations \cite{attention-need}, have been exploited to enhance the CNN-based anatomical landmark detection \cite{attention-guided-landmark,regression-voting,Misshapen-Pelvis-Landmark}. Specifically, Zhong et al. \cite{attention-guided-landmark} developed a two-stage U-Net with attention guidance to localize anatomical landmarks. Chen et al. \cite{regression-voting} and Liu et al. \cite{Misshapen-Pelvis-Landmark} exploited self-attention modules \cite{attention-need},\cite{non-local} for pelvis and cephalometric landmark detection respectively. More recently, Huang et al. \cite{DSNT} added a differentiable spatial to numerical transform layer to an encoder-decoder network. Vlontzos et al. \cite{regression-DQN} introduced multi-agent reinforcement learning for multiple landmark detection by designing a collaborative Deep Q-Network. Unlike the aforementioned methods, the proposed learning approach focuses on internally enriching the feature representations via regularized transfer learning for anatomical landmark detection, requiring neither attention mechanisms nor cascaded processing. \subsection{Knowledge Transfer} Fine-tuning \cite{simple-baseline} is a standard practice in transfer learning for refining a pre-trained model to be suitable for a new target task. Typically a small learning rate is applied and some model parameters may need to be frozen to reduce overfitting. However, empirically modifying existing model parameters is not a direct method to reuse the representational features from a source task model, which may limit good generalization to a small new task training dataset \cite{LWF}. In contrast, knowledge distillation, originally proposed for model compression \cite{knowledge-distillation}, can be considered as a more direct way to retain the learning experiences from a source task model by encouraging predictions of a student model to be close to those of a teacher model. This technique has been extended and applied to various applications, including hint learning \cite{hint-learning}, incremental learning \cite{LWF,LWM,Incremental-ultrasound}, privileged learning \cite{privileged-info}, domain adaptation \cite{cross-modality} and human expert knowledge distillation \cite{gaze-distillation}. Distillation methods focus on producing a compact model by operating the knowledge transfer across common tasks \cite{knowledge-distillation,gaze-distillation,hint-learning}. Different from the aforementioned methods, the proposed learning approach in this paper regularizes the transfer learning across different tasks. In other words, the proposed regularized knowledge transfer can be interpreted as cross-task representation learning, where ``cross-task" means that the learning process is made between the source and target tasks corresponding to a different label space. To boost the performance of the target task, joint training of the source and the target tasks, termed multi-task learning \cite{facial-attribute} has been proposed, where model parameters for both tasks are jointly optimized to learn a shared representation to benefit the target task. However that method requires data and labels of both tasks to be available during training, which can be difficult to satisfy for modelling tasks from clinical data. For our proposed design, we do not require access to the data from the source domain. \begin{figure*}[t] \centering \setlength{\abovecaptionskip}{-3pt} \setlength{\belowcaptionskip}{-5pt} \includegraphics[width=0.85\linewidth]{plot_overall_block.pdf} \caption{Illustration of proposed regularized transfer learning for the anatomical landmark detection. Face recognition is considered as the source task to provide rich facial semantics. For the target task, (a)-(d) illustrate four regularization constraints on the classification output ($L_{CO}$), the encoder output ($L_{EO}$), the spatial attention map ($L_{SAM}$) and the channel attention map ($L_{CAM}$), respectively.} \label{overall-system} \end{figure*} \section{Method} \label{Method} In this section, we first introduce the task of anatomical landmark detection, then describe the proposed regularized transfer learning solution for this task. \subsection{Problem Formulation} \label{problem-formulation} Consider a supervised anatomical landmark detection task, where we are given a training dataset with $N$ pairs of training samples, denoted as $\mathcal{D}= \{\mathbf{I}_{i}, \mathbf{p}_{i}\}_{i=1}^{N}$, where $\mathbf{I}_{i}\in \mathbb{R}^{H \times W \times 3}$ represents a 2D facial image with height $H$ and width $W$, and $\mathbf{p}_{i} = [(x_{1}, y_{1}), (x_{2}, y_{2}),...,(x_{K}, y_{K})] \in \mathbb{R}^{2\times K}$ denotes $K$ numbered labeled landmark coordinates in each of the N images ($i=1 \rightarrow N$). Inspired by its recent success in keypoint localization \cite{stacked-hourglass,simple-baseline}, we use a heatmap to regress the keypoints. To do this, we need to transform these landmark coordinates into heatmaps. Specifically, labeled coordinates are downscaled to $1/4$ of the input size ($\mathbf{p}_{i} \leftarrow \mathbf{p}_{i}/4$), and then are transformed to a set of heatmaps $\mathbf{G}_{i} \in \mathbb{R}^{(H/4) \times (W/4) \times K}$. Each heatmap $\mathbf{g}_{i, k} \in \mathbb{R}^{(H/4) \times (W/4)}, k\in \{1,...,K\}$ is defined as a 2D Gaussian kernel centered on the $k$-th landmark coordinate $(x_{i, k},y_{i, k})$, which is given as, \begin{equation}\label{heatmap} \mathbf{g}_{i, k}(a,b)=\exp \left(-\frac{(a-x_{i, k})^{2}+(b-y_{i, k})^{2}}{2 \sigma^{2}}\right) \end{equation} where $a$ and $b$ denotes the entry of matrix $\mathbf{g}_{i, k}$ in the $a$-th row and $b$-th column, and $\sigma$ is Gaussian kernel scale parameter. Given the dataset $\mathcal{D}= \{\mathbf{I}_{i}, \mathbf{G}_{i}\}_{i=1}^{N}$, the goal is then to learn a non-linear mapping function between an input image and a set of heatmaps. We follow \cite{simple-baseline,mobileFAN}, and design a CNN-based encoder-decoder network $\mathcal{T}_{\theta_{e},\theta_{d}}: \mathbb{R}^{H \times W \times 3}\rightarrow \mathbb{R}^{(H/4) \times (W/4) \times K}$ with learnable parameters $\theta_{e}$ and $\theta_{d}$, to achieve the goal. To mitigate against facial variability in our dataset, we consider a ResNet-50 model \cite{resnet} pre-trained on a large-scale and diverse VGGFace2 \cite{VGGFACE2} dataset as a backbone for feature extraction (encoder) $f_{\theta_{e}}: \mathbb{R}^{H \times W \times 3}\rightarrow \mathbb{R}^{m}$, with the classification branch $g_{\theta_{c}}: \mathbb{R}^{m} \rightarrow \mathbb{R}^{C} $ being disabled, where $m$ denotes the dimensionality of the encoder output, and $C$ represents the number of classes in the source classification task. For the decoder, three deconvolutional layers are employed to recover the spatial resolution, each of which is with the dimension of 256, a $4 \times4$ kernel and a stride of $2$, and is followed by a batch normalization and a rectified linear unit (ReLU) \cite{relu} activation function. Then, a $1 \times 1$ convolutional layer with linear activation is applied to obtain the predicted heatmaps $h_{\theta_{d}}: \mathbb{R}^{m}\rightarrow \mathbb{R}^{(H/4) \times (W/4) \times K}$. Consequently, the network $\mathcal{T}_{\theta_{e},\theta_{d}} := h_{\theta_{d}}(f_{\theta_{e}}(\mathbf{I}))$ can be learned by minimizing the following loss between the predicted heatmaps and the corresponding ground truth, \begin{equation}\label{regression-loss} L_{R}= \frac{1}{N}\sum_{i=1}^{N} \left\|\mathbf{G}_{i}-h_{\theta_{d}}(f_{\theta_{e}}(\mathbf{I}_{i}))\right\|^{2}_{F} \end{equation} where $F$ denotes the Frobenius norm. The above underpins our primary learning objective for the task of anatomical landmark detection. Standard training strategies for such a transfer learning approach usually rely on fine-tuning, where the entire network or only the decoder is trained on the target data. Considering the limited available labelled data in our case, an L2 penalty (weight decay) is usually utilized in the fine-tuning to reduce parameter over-fitting. However, merely penalizing the model weights may not capture the original knowledge embedded in the source network. In our case this may lead to a loss of useful facial descriptions and the distraction from other irrelevant regions, as illustrated in Fig. \ref{justification_results}. We present proposed solutions to address this problem in the next subsection. \subsection{Regularized Transfer Learning for Anatomical Landmark Detection} \label{Regularized Transfer Learning for Anatomical Landmark Detection} In order to reuse knowledge from the source network in the landmark detector model, we introduce a new regularized transfer learning (RTL) approach which aligns the network features (behaviors) of the source and the target models during target model training. To this end, we compute predictions of the source network on the target dataset $\mathcal{D}^{t}$, which are matched with those from the target network through a regularization loss $L_{\gamma}$. Hence, the total loss is updated as, \begin{equation}\label{total-loss} L=L_{R}+ \lambda L_{\gamma} \end{equation} where $\lambda>0 $ is a weighting parameter. If $\lambda = 0$, Eq. (\ref{total-loss}) reduces to standard fine-tuning. Fig. \ref{overall-system} shows the overall architecture of proposed regularized transfer learning for anatomical landmark detection. Face recognition is considered as the source task to provide rich facial semantics. For the target task, as shown in Fig. \ref{overall-system} (a)-(d), there are four different regularization constraints that are developed and explored for the proposed learning approach. \subsubsection{Constraint on Classifier Output (RTL-CO)} Motivated by \cite{knowledge-distillation} \cite{LWF}, this variant constrains the distance between the classification outputs for the design of $L_{\gamma}$, as shown in Fig. \ref{overall-system} (a). To do this, the previously abandoned classification branch $g_{\theta_{c}}: \mathbb{R}^{m} \rightarrow \mathbb{R}^{C} $ in Section \ref{problem-formulation} is re-enabled for training. Similar to the distillation loss \cite{knowledge-distillation}, we use a temperature parameter $\mu$ with $softmax$ function denoted as $\sigma$ to smooth the predictions. While the original cross-entropy function is replaced by the following term, \begin{equation}\label{output-loss} L_{CO}= \frac{1}{N}\sum_{i=1}^{N}\left\|\sigma\left( \frac{g_{\theta_{c}}^{s}(f_{\theta_{e}}^{s}(\mathbf{I}_{i}))}{\mu}\right)-\sigma\left( \frac{g_{\theta_{c}}^{t}(f_{\theta_{e}}^{t}(\mathbf{I}_{i}))}{\mu}\right)\right\|^{2}_{2} \end{equation} The main reason for this replacement is that the task (label space) between the source and target domains is different, and applying cross-entropy function as a strong regularizer could make the optimization lean towards the source task, thereby affecting the target task performance. Moreover, our empirical results showed that using the L2 norm improves the cross-entropy function by 0.45 pixels regarding the mean square errors. Note that the superscripts $s$ and $t$ refer to the source and target (fine-tuned) networks respectively. \subsubsection{Constraint on Encoder Output (RTL-EO)} this variant considers the role of the regularization constraint, as shown in Fig. \ref{overall-system} (b). The goal is to align the features from encoder outputs, similar to hint learning \cite{hint-learning}. Compared to $L_{CO}$, aligning the intermediate feature maps which preserve spatial configuration can be more effective and helpful for the landmark localization \cite{cross-modality}. In this case, we adopt the cosine similarity for feature alignment as described in Eq. (\ref{encoder-loss}) \cite{RKD}, as we conjecture that penalizing higher-order angular differences would benefit matching the relational information between the source and target tasks. \begin{equation}\label{encoder-loss} L_{EO}= 1- \frac{f_{\theta_{e}}^{s}(\mathbf{I}_{i})\cdot f_{\theta_{e}}^{t}(\mathbf{I}_{i})}{\| f_{\theta_{e}}^{s}(\mathbf{I}_{i})\| \times \|f_{\theta_{e}}^{t}(\mathbf{I}_{i})\|} \end{equation} \subsubsection{Constraint on Spatial Attention Map (RTL-SAM)} In addition to purely matching the predicted scores or feature maps between source and target tasks, it is important to understand how retainment of source task facial knowledge is beneficial to the target task. In this regard, we propose to constrain spatial attention maps which indicate where the meaningful features are emphasized given the input data. This is inspired by \cite{attention-transfer}, \cite{block-attention} which demonstrated attention maps can be more interpretative than estimated feature maps. Fig. \ref{justification_results} (c) and Fig. \ref{justification_results} (d) demonstrate the advantage of \textit{RTL-SAM} over that of \textit{RTL-EO }on an example image. We specifically employ activation-based spatial attention maps \cite{attention-transfer} for the proposed \textit{RTL-SAM}, as shown in Fig. \ref{overall-system} (c). Given an activation map $\mathbf{E}_{i} \in \mathbb{R}^{H \times W \times B} = f_{\theta_{e}}(\mathbf{I}_{i})$ for the $i$-th sample of the target dataset, the corresponding spatial attention map $\mathbf{A}_{i} \in \mathbb{R}^{H \times W}$ is computed as \cite{attention-transfer}, \begin{equation}\label{activation-attention} \mathbf{A}_{i} =\sum_{b=1}^{B}\left|\mathbf{E}_{i}(b)\right|^{2} \end{equation} where $B$ denotes the number of feature channels, $|\cdot|$ and $(\cdot)^{2}$ are the element-wise absolute value and power operators, respectively. We then reshape the $\mathbf{A}_{i}\in \mathbb{R}^{H \times W}$ into $\hat{\mathbf{A}}_{i}\in \mathbb{R}^{H W}$ and use it to formulate the following loss function \cite{attention-transfer}, \begin{equation}\label{SAM-loss} L_{SAM}= \frac{1}{N}\sum_{i=1}^{N}\left\| \frac{\hat{\mathbf{A}}_{i}^{s}}{\|\hat{\mathbf{A}}_{i}^{s}\|_{2}}- \frac{\hat{\mathbf{A}}_{i}^{t}}{\|\hat{\mathbf{A}}_{i}^{t}\|_{2}}\right\|^{2}_{2} \end{equation} \subsubsection{Constraint on Channel Attention Map (RTL-CAM)} The final variant considers channel-wise attention maps \cite{block-attention,SE-Net} as a regularization constraint in our proposed framework. See Fig. \ref{overall-system} (d). Here we squeeze the spatial dimension of an activation map $\mathbf{E}_{i} \in \mathbb{R}^{H \times W \times B} $ to achieve a context vector $\mathbf{Q}_{i} \in \mathbb{R}^{B}$ \cite{SE-Net}, as given below, \begin{equation} \mathbf{Q}_{i} = \frac{1}{H \times W}\sum^{H}_{h=1}\sum^{W}_{w=1}|\mathbf{E}_{i}(h,w)| \end{equation} Similar to $L_{SAM}$, we formulate the regularization loss $L_{CAM}$ as below, \begin{equation}\label{CAM-loss} L_{CAM}= \frac{1}{N}\sum_{i=1}^{N}\left\| \frac{\mathbf{Q}_{i}^{s}}{\|\mathbf{Q}_{i}^{s}\|_{2}}- \frac{\mathbf{Q}_{i}^{t}}{\|\mathbf{Q}_{i}^{t}\|_{2}}\right\|^{2}_{2} \end{equation} In practice, the four regularization terms $L_{CO}$, $L_{EO}$, $L_{SAM}$ and $L_{CAM}$ can be combined in the total loss function as described in \ref{total-loss}. The effect on performance of doing this will be assessed in the following section. For the model inference, only the trained target encoder and decoder are utilized to predict heatmaps $\mathbf{H}_{i} = h_{\theta_{d}}^{t}(f_{\theta_{e}}^{t}(\mathbf{I}_{i}))$, and they are further processed via an $argmax$ function to obtain final landmark locations $\hat{\mathbf{p}}_{i}$. Note that other methods such as fitting another radial basis function to obtain subpixel localization can be also utilized in here for kepoint extraction. \section{Experiments} \label{Experiments} \subsection{Dataset} \begin{table*}[t] \caption{Quantitative comparison between proposed and other related existing approaches using MSE$\pm$Std and failure rate on the test set. Best results are marked in bold.} \centering \label{table1} \resizebox{0.75\linewidth}{!}{% \begin{tabular}{c|c|c|c|c|c|c|c} \toprule \multirow{2}{*}{Method} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}MSE$\pm$Std\\ ($\downarrow$)\end{tabular}} & \multicolumn{3}{c|}{Failure Rate ($\downarrow$)} & \multicolumn{3}{c}{AUC ($\uparrow$)} \\ \cline{3-8} & & 1.0 pixel & 1.2 pixel & 1.4 pixel&1.0 pixel&1.2 pixel&1.4 pixel \\ \hline FE \cite{simple-baseline}& 1.82$\pm$0.50 & 99.03\% & 94.52\% &80.00\%&0.01&0.01&0.02 \\ DSNT \cite{DSNT}&1.41$\pm$0.26 & 96.13\%& 74.19\%& 50.65\%&0.01&0.02&0.07\\ FTP \cite{simple-baseline} & 1.16$\pm$0.26 & 73.87\% & 40.32\% &16.77\% &0.04&0.10& 0.19\\ U-Net \cite{Unet}&0.93$\pm$0.39 &30.00\% & 10.00\%& 4.84\%&0.15&0.26&0.36 \\ HG \cite{stacked-hourglass}& 0.88$\pm$ 0.39&24.84\% & 12.58\%&6.77\%&0.20&0.30&0.39 \\ FT \cite{simple-baseline}& 0.86$\pm$0.24 &24.19\% & 10.65\% &3.23\% &0.18&0.29&0.38\\ \hline \emph{RTL-CO} & 0.84$\pm$0.25 & 24.84\% & 5.81\% & 1.61\% &0.20&0.31&0.40\\ \emph{RTL-EO} & 0.83$\pm$0.25 & 21.29\% & 7.74\%& 1.61\% &0.21&0.32&0.41\\ \emph{RTL-SAM} & \textbf{0.78$\pm$0.22} & \textbf{13.55\% }& \textbf{4.84\%}& \textbf{1.61\%} &\textbf{0.24}&\textbf{0.35}&\textbf{0.44}\\ \emph{RTL-CAM} & 0.82$\pm$0.24 & 20.00\% & 5.81\%& 1.61\% &0.21&0.32&0.42\\ \bottomrule \end{tabular}% } \end{table*} \label{Dataset} The data used in the experiments was collected by the Collaborative Initiative on Fetal Alcohol Spectrum Disorders (CIFASD)\footnote{https://cifasd.org/}, a global multi-disciplinary consortium focused on furthering the understanding of FASD. It contains subjects from 4 sites across the USA, aged between 4 and 18 years. Each subject was imaged using a commercially available static 3D photogrammetry system from 3dMD\footnote{http://www.3dmd.com/}. Since directly processing a high spatial resolution 3D mesh is computationally intensive, we utilize the 2D images captured during 3D acquisition, which are used as UV mapped textures for 3D surface reconstruction. We used in total 1549 facial scans for our experiments, and for each scan, there are 14 FAS associated landmarks which had been manually annotated by an expert (see Fig. \ref{landmark_illustration} for details). These scans were randomly split into a training/validation set (70\%/10\%), and a test set (20\%) for the experiments. \subsection{Implementation Details} All the images were cropped and resized to $256 \times 256$ pixels, and intensity normalized with mean and standard deviation (std) values provided by the VGGFace2 \cite{VGGFACE2} for the network training, validation and testing. Data augmentation was performed with randomly horizontal flip (50\%) and scaling ($0.8$). During training, the Adam optimizer \cite{Adam} was used for the optimization ($\beta_{1} = 0.9$, $\beta_{2}=0.999$, and epsilon = $1e^{-8}$) with a mini-batch size of $2$ for $150$ epochs. A polynomial decay learning rate was used with an initial value of $0.001$. Models saved with the best accuracy on the validation set were used for evaluation. For more details of model training, Fig. \ref{tran_val_loss} in Section \ref{Visualization of Training Details} depicts a learning curve of model performance on the train/validation sets. The temperature parameter $\mu$ in Eq. (\ref{output-loss}) was set to $2$. We experimentally set up the weighting parameter $\lambda=0.002$ used in Eq. (\ref{total-loss}) and the kernel scale parameter $\sigma = 1.5$ used in Eq. (\ref{heatmap}), and we used this parameter setting throughout the remaining experiments. The proposed learning algorithm was implemented using TensorFlow 1.6.0 and the model trained using an Nvidia GTX 1060 GPU. \subsection{Evaluation Metrics} We firstly employ the Mean Squared Error (MSE) for evaluation, which is a commonly-used metric to assess landmark detection. It is defined as: \begin{equation}\label{evaluation-metric} \mathrm{MSE}=\frac{1}{N_{e}} \sum_{i=1}^{N_{e}} \frac{1}{K}\left\|\mathbf{p}_{i}-\hat{\mathbf{p}}_{i}\right\|_{2} \end{equation} where $N_{e}$ is the number of images in the test set, and $\mathbf{p}_{i}$ and $\hat{\mathbf{p}}_{i}$ denote the ground truth and prediction landmark, respectively. Note that the original normalization factor estimated by inter-ocular distance (Euclidean distance between outer eye corners) \cite{300W} is not included in this evaluation, as annotations for the other eye are not available, as shown in Fig. \ref{qualitative_results}. In addition, we utilize the Cumulative Errors Distribution (CED) curve with two additional metrics of Area-Under-the-Curve (AUC) and Failure Rate (FR). When the Euclidean distance between the estimated landmark and its ground truth location (point-to-point Euclidean error) is greater than a pre-defined threshold, it is considered as a mis-detection. We consider three thresholds of 1.0 pixels, 1.2 pixels and 1.4 pixels. \begin{figure}[t] \centering \includegraphics[clip, trim=0.4cm 0.01cm 2.cm 3.cm,width=0.8\linewidth]{ced_com.pdf} \caption{Illustration of cumulative error distribution (CED) curve on the test set. Best viewed in colored version.} \label{ced-results} \end{figure} \begin{figure*}[t] \centering \includegraphics[width=0.95\linewidth]{qualitative_results.pdf} \caption{Qualitative evaluation of landmark detection (first and third rows) and heatmap regression (second and fourth rows) on the test set. Best viewed in color version.} \label{qualitative_results} \end{figure*} \subsection{Comparison with Existing Approaches} \label{Comparison with Existing Approaches} In this section, we evaluate the effect of the proposed regularized transfer learning (RTL) methods (\emph{RTL-CO}, \emph{RTL-EO}, \emph{RTL-SAM}, and \emph{RTL-CAM}) and compare these variants with several related approaches from the literature. The related approaches are: a two-stage Hourglass network (HG) \cite{stacked-hourglass}, a modified U-Net for landmark localization \cite{Unet}, and a fully-convolutional network with a differentiable spatial-to-numerical transform (DSNT) \cite{DSNT}. In addition, three variants of transfer learning \cite{simple-baseline} without regularization ($\lambda = 0$) are considered: Feature Extraction (FE) \cite{simple-baseline} with freezing the encoder, Fine Tuning Parts (FTP) \cite{simple-baseline} without freezing the final convolutional layer of the encoder, and Fine Tuning (FT) \cite{simple-baseline} without freezing any layer. For a fair comparison, all the evaluated methods use the same weight decay rate of $10^{-4}$. Table \ref{table1} summarizes the quantitative evaluation on the test set by reporting the MSE, failure rate, and AUC for each compared method. Performance metrics with ($\downarrow$) or ($\uparrow$) indicate that lower is better or higher is better, respectively. From the results, we observe that all the proposed new approaches favorably surpass the previous methods from the literature for most metrics. It is noteworthy that \emph{RTL-SAM} reports the best performance among all the compared approaches. Compared to FT \cite{simple-baseline}, which is closely related to our work, the proposed \emph{RTL-SAM} improves the MSE by 0.08 pixels (9.3\%), and the failure rate by 11.29\%, 5.81\%, and 1.62\% for the three thresholds. This demonstrates that the proposed regularization constraint is beneficial for transfer learning across domain-similar source/target tasks. \begin{table*}[t] \centering \caption{Ablation studies on different proposed regularization constraints. The upper part shows the results for the individual landmark localization using MSE$\pm$ Std (pixel), while the lower part presents the failure rate with the error threshold of 1.2 pixel. Best results are shown in bold.} \label{table2} \resizebox{0.85\linewidth}{!}{ \begin{tabular}{c|ccccccc} \toprule \multirow{2}{*}{Landmark} & \multicolumn{7}{c}{Configurations} \\ \cline{2-8} & \emph{RTL-CO} &\emph{ RTL-EO} & \emph{RTL-SAM} & \emph{RTL-CAM }& \emph{RTL-CO-EO} &\emph{ RTL-CO-SAM}& \emph{RTL-CO-CAM}\\ \hline L1 & 0.64$\pm$0.58 & 0.63$\pm$0.59 &\textbf{0.59$\pm$0.56} &0.65$\pm$0.58 & 0.64$\pm$0.58 &0.61$\pm$0.60 & 0.62$\pm$0.56 \\ L2 & 0.68$\pm$0.54 & 0.74$\pm$0.54 & \textbf{0.67$\pm$0.56} &0.78$\pm$0.55 & 0.79$\pm$0.55 &0.74$\pm$0.58 & 0.77$\pm$0.64\\ L3 & 0.82$\pm$0.63 & 0.89$\pm$0.60 & 0.74$\pm$0.59 &0.77$\pm$0.84 & 0.82$\pm$1.12 &0.75$\pm$0.60 & \textbf{0.73$\pm$0.72} \\ L4 & 0.65$\pm$0.60 &\textbf{0.61$\pm$0.56} &0.66$\pm$0.93 &0.68$\pm$0.55 &0.62$\pm$0.56 &0.63$\pm$0.57 &0.64$\pm$0.58 \\ L5 &0.71$\pm$0.57 & \textbf{0.64$\pm$0.56}&0.67$\pm$0.55 &0.69$\pm$0.56 &0.67$\pm$0.58 &0.66$\pm$0.57 & 0.73$\pm$0.56 \\ L6 & 0.75$\pm$0.58 & 0.74$\pm$0.57 &\textbf{0.68}$\pm$\textbf{0.56} &0.69$\pm$0.56 &0.73$\pm$0.56 &0.78$\pm$0.56 &0.79$\pm$0.58 \\ L7 &1.48$\pm$1.17 & 1.46$\pm$1.13 &\textbf{1.20$\pm$1.02} &1.46$\pm$1.22 &1.44$\pm$1.10 &1.58$\pm$1.29 &1.28$\pm$1.05 \\ L8 &0.74$\pm$1.02 & 0.72$\pm$0.56 &0.73$\pm$0.56 &0.78$\pm$0.56 &0.74$\pm$0.55 &0.74$\pm$0.55 &\textbf{0.68$\pm$0.56} \\ L9 &1.40$\pm$1.05 & 1.39$\pm$1.15 & \textbf{1.17$\pm$1.19} &1.28$\pm$1.17 &1.30$\pm$1.19 &1.50$\pm$1.33 & 1.32$\pm$1.13\\ L10 &0.64$\pm$0.57 & \textbf{0.60$\pm$0.55} &0.63$\pm$0.59 &0.60$\pm$0.58 &0.64$\pm$0.58 &0.63$\pm$0.57 &0.71$\pm$0.57 \\ L11 &0.89$\pm$1.06 & \textbf{0.75$\pm$0.60} &0.80$\pm$0.58 &0.84$\pm$0.60 &0.83$\pm$0.61 &0.83$\pm$0.57 & 0.91$\pm$1.07 \\ L12 &0.89$\pm$0.72 & 0.92$\pm$1.35 &0.85$\pm$0.62 &0.84$\pm$0.66 &\textbf{0.82$\pm$0.64} &0.95$\pm$0.69 &0.94$\pm$0.63 \\ L13 &0.72$\pm$0.60 & 0.70$\pm$0.61 &0.74$\pm$0.60 &\textbf{0.63$\pm$0.59} &0.71$\pm$0.62 &0.69$\pm$0.60 &0.76$\pm$0.60 \\ L14 &0.78$\pm$0.59 & 0.86$\pm$0.72 & 0.78$\pm$0.58 &0.80$\pm$0.63 &0.85$\pm$0.62 &\textbf{0.76$\pm$0.57} &0.86$\pm$0.60 \\ \hline Average &0.84$\pm$0.25 &0.83$\pm$0.24 & \textbf{0.78$\pm$0.22}& 0.82$\pm$0.24 &0.83$\pm$0.25 & 0.85$\pm$0.25 &0.86$\pm$0.33 \\ \bottomrule \end{tabular}% } \end{table*} In Fig. \ref{ced-results}, we show the cumulative distributions of landmark detection errors for the methods considered. This reveals the advantage of the proposed approaches over the compared previous ones, which is consistent with the findings in Table \ref{table1}. From the CED curve, we observe that more than 95\% of the testing images are successfully predicted within the error range of 1.3 pixels, and over 98\% of the test set is well estimated within an error range of 1.4 pixels. Fig. \ref{qualitative_results} presents a qualitative comparison between different approaches. From the figure, we observe that the predicted landmarks and heatmaps from the proposed methods generally align very well with the ground truth, and are less prone to ambiguities when landmarks are in close proximity (for instance, the upper lip). \subsection{Ablation Studies} \label{Ablation Studies} \subsubsection{Impact of Different Regularization Constraints} \label{Impact of Different Regularization Constraints} In this section, we present an ablation study to analyze the effectiveness of each proposed regularization constraint, in which different combined regularization constraints are also added for evaluation. In addition to the original four regularization constraints, we study the effectiveness of combinations of both the classifier and encoder outputs (\emph{RTL-CO-EO}), the classifier output with spatial attention map (\emph{RTL-CO-SAM}), and the classifier output with channel attention map (\emph{RTL-CO-CAM}). \begin{figure}[t] \centering \includegraphics[clip, trim=0.4cm 0.01cm 1.8cm 2.7cm,width=0.85\linewidth]{AUC_CED.pdf} \caption{AUC scores of cumulative error distribution (CED) curve versus point-to-point error threshold for different proposed regularization constraints. Best viewed in color version.} \label{failure-rate} \end{figure}% Table \ref{table2} presents a detailed comparison of the different proposed approaches by listing the performance scores per individual landmark. From the results, we can see that \emph{RTL-EO} and \emph{RTL-SAM} achieve the highest number of best scores $4$ and $5$ landmarks respectively. This indicates that preserving and highlighting the feature outputs with spatial information from intermediate layers can be potentially more beneficial for the localization task. It can be also seen that for all the proposed variants the MSE ranged from 0.59 pixels to 1.58 pixels for different landmarks, where landmarks L1 and L2 corresponding to the exocanthion and endocanthion are well estimated with relatively lower scores than the others. However, similar to the visual findings in Fig. \ref{qualitative_results}, landmarks L7 and L9 marked as the crista philtri on both sides are seen as the most challenging cases. Fig. \ref{failure-rate} compares the effect of modelling with the different proposed regularization constraints using the AUC score calculated from the CED curve. Interestingly, the results indicate that combined approaches which introduce additional computational cost performed similarly or even worse than those of individual ones. \begin{table}[t] \caption{Ablation studies on different pre-trained source tasks. A failure case here is considered if the point-to-point Euclidean error is greater than $1.2$ pixel. Best results are marked in bold.} \centering \label{table3} \resizebox{0.95\linewidth}{!}{ \begin{tabular}{c|c|c|c} \toprule \multirow{2}{*}{Method} & \multirow{2}{*}{MSE $\pm$ Std ($\downarrow$)} & \multirow{2}{*}{FR ($\downarrow$)} & \multirow{2}{*}{AUC ($\uparrow$)} \\ && & \\ \hline FT-ImageNet \cite{simple-baseline}& 0.85$\pm$0.37& 9.68\% & 0.31 \\ FT-YoutubeFaces \cite{simple-baseline}& 0.86$\pm$0.30& 8.06\% & 0.30 \\ FT-VGGFace2 \cite{simple-baseline} & 0.86$\pm$0.24& 10.65\% & 0.29 \\ \textit{RTL-SAM-ImageNet} & 0.82$\pm$0.32 & 8.39\%& 0.33 \\ \textit{RTL-SAM-YoutubeFaces} & 0.84$\pm$0.25 & 8.06\% & 0.31 \\ \textit{RTL-SAM-VGGFace2}& \textbf{0.78}$\pm$\textbf{0.22} & \textbf{4.84\%} & \textbf{0.35} \\ \bottomrule \end{tabular} } \end{table} \subsubsection{Impact of Different Source Tasks} \label{Impact of Different Pre-trained Source Tasks} To investigate the impact of different source tasks on the proposed framework, we re-implement methods FT \cite{simple-baseline} and our proposed \textit{RTL-SAM} using the network ResNet-50 pre-trained on ImageNet \cite{ImageNet} and a sub-dataset of YoutubeFaces \cite{youtube-faces} (facial alignment with 3462 images). We denote the evaluated methods as FT-ImageNet, FT-YoutubeFace, \textit{RTL-SAM-ImageNet} and \textit{RTL-SAM-YoutubeFaces}. We then compare them with those previously obtained using VGGFace2 \cite{VGGFACE2} pre-trained weights. We observe from Table \ref{table3}, that by utilizing ImageNet and YoutubeFaces pre-trained weights, our proposed regularization strategy \textit{RTL-SAM} outperforms FT in most evaluated metrics, which further confirms the effectiveness of our proposed method. Moreover, it is noteworthy that the proposed method with VGGFace2 pre-trained weights (\textit{RTL-SAM-VGGFace2}) achieves the best performance among all compared methods. Interestingly, \textit{RTL-SAM-YoutubeFaces} using the source task which is closely relevant to the target task, did not show advantage over \textit{RTL-SAM-ImageNet} and \textit{RTL-SAM-VGGFace2}. To provide further insight on this finding, we visualize the top activation attention maps for the models derived with the source tasks of ImageNet and VGGFace2, as shown in Fig. \ref{impact-of-imagenet}. We can see that the attention map generated from the source model (ResNet-50 \cite{resnet}) pre-trained on VGGFace2 \cite{VGGFACE2} (ResNet-50-VGGFace2) concentrates more on the desired facial region compared to ResNet-50-ImageNet. After refining the pre-trained models to the target task, the attention map produced from \textit{RTL-SAM-VGGFace2} seems to be more informative than that of \textit{RTL-SAM-ImageNet} for inferring the anatomical landmarks. \begin{figure}[t] \centering \setlength{\belowcaptionskip}{-0.3cm} \setlength{\abovecaptionskip}{-0.2cm} \includegraphics[width=1\linewidth]{impact-of-imagenet.pdf} \caption{Illustration of top activation attention maps for models with different pre-trained source tasks: the source model (ResNet-50) pre-trained on ImageNet (ResNet-50-ImageNet), the source model (ResNet-50) pre-trained on VGGFace2 (ResNet-50-VGGFace2), the proposed regularization constraint on spatial attention maps transferred from ImageNet pre-trained weights (\textit{RTL-SAM-ImageNet}), and the proposed regularization constraint on spatial attention maps transferred from VGGFace2 pre-trained weights (\textit{RTL-SAM-VGGFace2}).} \label{impact-of-imagenet} \end{figure} \subsubsection{Impact of $\lambda$} \label{Impact of Weighting Parameter} \begin{figure}[t] \centering \includegraphics[clip, trim=0.45cm 0.01cm 1.8cm 2.8cm,width=0.8\linewidth]{parameter_analysis.pdf} \caption{Illustration of CED curve on validation set for different values of weighting parameter $\lambda$, where corresponding results using MSE$\pm$Std are shown in the parenthesis.} \label{parameter_analysis} \end{figure}% To study the influence of weighting parameter choice on transfer learning regularization, we test a set of values for the parameter $\lambda$ ranging from $0$ to $2\times 10^{-5}$ on the validation set using the proposed \emph{RTL-EO}, which has the simplest implementation among proposed methods. Note that when $\lambda = 0$, the designed model is evaluated without regularization, which is equivalent to standard fine tuning. Fig. \ref{parameter_analysis} presents the results for varying parameter $\lambda$. This shows that the proposed approach reduces the localization error when adjusting the value of $\lambda$ from $2\times 10^{-5}$ to $2\times 10^{-3}$. We also observe that the setting of $\lambda = 2\times 10 ^{-3}$, denoted as the red solid line, achieves the best performance considering both the CED curve and MSE. However, a larger value of $\lambda = 2\times 10^{-2}$, regarded as a strong regularization during training, could affect model convergence for the landmark detection. \subsubsection{Impact of $\sigma$} \label{Impact of parameter sigma} \begin{figure}[t] \centering \includegraphics[clip, trim=0.45cm 0.01cm 1.8cm 2.8cm,width=0.8\linewidth]{sigma_analysis.pdf} \caption{Illustration of CED curve on validation set for different values of kernel scaling parameter $\sigma$, where corresponding results using MSE$\pm$Std are shown in the parenthesis.} \label{sigma_analysis} \end{figure}% Here we conduct a sensitivity analysis to study the impact of Gaussian kernel scaling parameter $\sigma$ on the keypoint localization accuracy. Similar to the above analysis, we also utilize the proposed \emph{RTL-EO} with $\lambda = 2\times 10 ^{-3}$ to test a range of values for the parameter $\sigma$ on the validation set. As seen from Fig. \ref{sigma_analysis}, we observe that the best performance evaluated in both metrics of CED and MSE is obtained with $\sigma = 1.5$, and the results in general are varied within a reasonable range. \section{Discussion} \label{Discussion} \subsection{Strengths and Limitations} In this work, we have shown the importance of transferring knowledge from a pre-trained source classification model for learning the anatomical landmark detection with a limited availability of training data. This observation was validated by the experimental study in Section \ref{Comparison with Existing Approaches}, where transfer learning methods \cite{simple-baseline}, achieve noticeably better performance than other compared solutions. More importantly, the strength of this study is that the proposed methods are shown to better preserve facial semantics embedded in the source model for learning the anatomical landmark detection compared to finetuning. This can be best seen from the evaluations both quantitatively and qualitatively in Section \ref{Comparison with Existing Approaches}, where our proposed methods outperform the method of FT \cite{simple-baseline}. This property of the proposed framework is particularly useful to reduce ambiguity in landmark detection, where landmarks which are in close proximity can be semantically distinguished by reusing pre-computed facial semantics. However, the prerequisite for the proposed framework is the utilization of a pre-trained source task model, which may not be always available for other clinical applications. In Section \ref{Impact of Different Pre-trained Source Tasks}, we have demonstrated that the proposed approach performs better when incorporating the knowledge from VGGFace2 which is more relevant to the target task compared to that of ImageNet. Another important finding is that the proposed knowledge transfer with larger source datasets (ImageNet 14 million images and VGGFace2 3.31 million images) can generalize better on the target task regardless of task relevance. Moreover, evaluated results in Section \ref{Impact of Weighting Parameter} have shown that the proposed framework with different settings of the weighting parameter has a generally positive impact on the transfer learning process for anatomical landmark detection, but these empirical configurations may be only specific to the addressed clinical application. Hence, how to adaptively determine the required amount of domain knowledge for a given target task remains an open question. \subsection{Translational Potential} The motivating clinical need for accurate, anatomical landmark placement in fetal alcohol syndrome (FAS) analysis is 1) to identify linear and angular facial anthropometric measurements such as palpebral fissure length (PFL) and 2) to provide a surface-based analysis of facial form to compare an individual to unaffected controls. We link this need to our research findings. The proposed framework delivered particularly good performance for landmarks L1 and L2 (exocanthion and endocanthion), as presented in Section \ref{Impact of Different Regularization Constraints}, which is important for accurate estimation of PFL. Previous analysis using a dense surface model (DSM) for the surface-based study of facial shape has shown the ability to identify subtle facial dysmorphism across FAS \cite{FAS, three-facial,FAS-curvature,Combined-FAS}. However, to date, their construction has been reliant upon the manual placement of a sparse set of anatomical landmarks. Based on the evaluations in Fig. \ref{ced-results}, more than 95\% of the testing cases have been accurately estimated by the proposed framework, where \emph{RTL-SAM} and \emph{RTL-EO} perform the best. We believe that the proposed framework can provide an automated alternative to the manual anthropometric placement, and can be readily embedded in a clinical prediction tool owing to its real-time speed about 44 frames per second (FPS). Specifically the proposed methods of \emph{RTL-SAM} and \emph{RTL-EO} are recommended for the integration of a DSM into the clinical workflow for better identification of subjects with FAS. \section{Conclusions} \label{Conclusions} In this paper, we presented a new regularized transfer learning framework to address the problem of anatomical landmark detection in FAS. The proposed learning approach reused the rich visual semantics from a domain-similar source model as guidance for learning the landmark detector. Four regularization constraints were developed and investigated in the proposed framework, including constraining the feature outputs from classification and intermediate layers, as well as matching activation attention maps in both the spatial and channel levels. Experimental results show that the proposed learning framework performs well with limited training samples and outperforms other compared solutions. The generalization of the proposed learning framework to other clinical applications with the availability of domain or medical expert knowledge would be an interesting research avenue. Future work will integrate the automated anatomical landmarks with a dense surface model (DSM) into the clinical workflow for better early identification of those with FAS. \bibliographystyle{IEEEtran}
{'timestamp': '2021-09-14T02:21:33', 'yymm': '2109', 'arxiv_id': '2109.05485', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05485'}
arxiv
\section{Introduction} The tremendous compute power with high bandwidth memory and enormous storage capabilities makes high performance computing (HPC) facilities ideal infrastructures for various types of applications. The main tenant of HPC systems is batch applications, which are tightly coupled parallel jobs and are rigid in size. On-demand applications are time-critical applications requiring quick response and thus are used to running on their dedicated clusters. As the sizes of on-demand applications are rapidly expanding in recent years, the dedicated clusters cannot keep up with the rapid expansion in on-demand applications. As a result, HPC system becomes a more practical solution for on-demand applications. Malleable applications are loosely coupled applications consisting of a series of tasks and therefore they can adapt their sizes to changes in hardware availability. Malleable applications are typically running in datacenters. In recent years, an increasing number of HPC systems are equipped with accelerators. The superior computing power combined with the emerging accelerators makes HPC systems an attractive alternative for malleable applications. The production HPC job schedulers, such as Slurm, Moab/TORQUE, PBS, and Cobalt \cite{SLURM,Moab,PBS,Cobalt}, adopt the traditional batch job scheduling model, where users request a fixed amount of resources for a specific amount of time, while the scheduler decides when and where to run each job based on job priority and system availability. A number of studies attempt to address the hybrid workload scheduling on a single HPC system. Research on co-scheduling rigid and on-demand applications often aims at the high responsiveness of on-demand jobs. The common strategies include predicting on-demand jobs' requests, reserving resources for on-demand jobs, and preempting rigid jobs to make room for on-demand jobs \cite{Liu,Maurya}. Other studies focus on co-scheduling malleable jobs with rigid jobs on HPC systems \cite{Balsam,Carroll,Sun2011,Souza,Chadha,Hungershofer,Prabhakaran}. Unfortunately, none of the existing studies address the problem of co-scheduling all three types of applications, i.e., on-demand jobs, rigid jobs, and malleable jobs. Hence, the scheduling implications of co-running these applications are unknown. The potential benefits of executing the hybrid workloads on a single HPC system are supporting ever-increasing on-demand job sizes, reducing resource fragmentation, and improving system utilization by malleable jobs. However, this is a challenging task at both job scheduling level and resource management level. The job scheduler needs to maintain the delicate balance between several conflicting objectives, i.e., quick response to on-demand jobs, high system utilization, the incentive for shrinking malleable jobs, and low impact on rigid jobs. The resource manager has to execute the more complicated and frequent operations from job scheduler, i.e., start, preemption, shrink, and expansion operations. This requires more efficient draining processes and corporation with individual applications. In this paper, we concentrate on addressing HPC hybrid workloads problem from the job scheduling aspect. We propose six mechanisms to address the aforementioned challenges that rely on shrinking, expanding, checkpointing, and resuming techniques to dynamically make room for time-sensitive on-demand applications. Each mechanism focuses on different aspects of scheduling. Our proposed mechanisms are designed to be used in conjunction with the existing scheduling policies: while a scheduling policy determines the order of waiting jobs, our mechanisms manipulate the running jobs in order to meet on-demand requests with minimal impact on other applications. Our design is based on the fact that it is often possible for on-demand jobs to determine their requests within a short time (15-30 minutes) before their actual arrivals \cite{Liu}. Upon receiving on-demand job's advance notice, we provide both non-invasive and invasive mechanisms to reserve resources for the on-demand job. Once an on-demand job arrives, we provide several mechanisms to immediately vacate nodes from running malleable and rigid jobs. By combining the mechanisms used at on-demand job's advance notice and its arrival, we propose six mechanisms to handle hybrid workload scheduling problems. To comprehensively evaluate our mechanisms under various scenarios, we conduct a series of trace-based simulations using various workloads generated based on real workload traces collected from Theta \cite{Theta} at Argonne Leadership Computing Facility (ALCF). The results show that all of the proposed mechanisms achieve quick responsiveness for on-demand jobs. Additionally, the results reveal the impact of different mechanisms on system performance and the performance on malleable and rigid jobs. More importantly, we provide valuable insights for choosing these mechanisms under different situations. \section{Related Work and Challenges}\label{Background and Challenges} \subsection{HPC Application Types}\label{HPC application types} \textbf{Rigid job} is the most common type of job in HPC environments \cite{IPPS96}. Rigid jobs have fixed resource requirements throughout their life cycle. Most parallel applications, such as extreme-scale scientific simulations and modeling, are rigid in nature, requiring inter-process communication through message passing, and checkpointing for fault tolerance \cite{Qiao1}. They are tightly coupled applications that cannot be decomposed to a series of small-sized tasks and are prone to failure due to their sizes \cite{Fan8}. In order to handle hardware failures, rigid applications checkpoint regularly and restart from the latest checkpoint in the event of an interruption. \textbf{On-demand job} is a time-critical application needed to be completed in the shortest time possible. An example of the on-demand jobs is data analytical workloads after experiments \cite{Liu}. Traditionally, to ensure high responsiveness, on-demand jobs are running on dedicated clusters. The rapid experimental expansion requires increasingly large computing capabilities, which cannot be fulfilled by small clusters. The use of large-scale HPC systems becomes a viable solution for the ever-increasing on-demand workloads. \textbf{Malleable job} is another type of parallel job whose sizes can adapt to the number of nodes assigned to them. A malleable job specifies the minimum and the maximum number of nodes. They can shrink down to the minimum sizes or expand up to the maximum sizes based on resource availability. Typically, a malleable job consists of loosely coupled small-sized tasks and the running tasks can be dynamically adjusted based on the assigned nodes. In addition, preemption of malleable jobs causes less overhead than rigid jobs, because they can skip over the finished tasks and resume from the interrupted tasks. The typical examples of malleable jobs are high throughput jobs \cite{Raicu}, multi-task workflows \cite{Balsam}, machine learning applications, and hyperparameter searches in deep neural networks. While traditionally separated infrastructures have been used for rigid jobs and malleable jobs \cite{Sadooghi,He}, the next-generation HPC systems provide not only tremendous compute power on a single node (CPU and GPU), but also enormous high bandwidth memory, making them efficient platforms for malleable workloads \cite{Qiao2}. \subsection{Job Scheduling in HPC}\label{Job scheduling in HPC} HPC job scheduling is traditionally designed to manage and assign rigid jobs to resources. The resource allocation is commonly at the granularity of a node. When submitting a job, a user is required to provide job size and job runtime estimate. At each scheduling instance, the scheduler orders the jobs in the queue according to site policies and resource availability and executes jobs from the head of the queue. The most widely used HPC job scheduling policy is First Come First Serve (FCFS) with EASY backfilling \cite{Feitelson02}. FCFS sorts the jobs in the queue according to their arrival times, while backfilling is often used in conjunction with reservation to enhance system utilization. Backfilling allows subsequent jobs in the queue to move ahead under the condition that they do not delay the existing reservations. In the realm of executing on-demand jobs and rigid jobs on HPC systems, several groups have proposed to statically or dynamically reserve resources for on-demand requests. Dynamical reservation was achieved by predicting the on-demand request patterns \cite{Liu,Maurya}. In terms of accommodating malleable jobs and rigid jobs on HPC systems, several attempts have been made to shrink malleable jobs in order to reduce resource fragmentation problems \cite{Hungershofer,Prabhakaran,Carroll}. To the best of our knowledge, our work is the first attempt to schedule rigid, on-demand, and malleable jobs on a single HPC system. Our design processes on-demand requests by manipulating running rigid and malleable jobs, hence being compatible with existing HPC job scheduling policies concentrating on managing and assigning waiting jobs. Our work also differs from existing cloud resource managers like Mesos and Kubernetes \cite{Mesos,Kubernetes}. Cloud resource managers commonly allow jobs to share nodes. As the result, solutions for addressing bursty on-demand requests often rely on co-scheduling mixed workloads on a single node, which do not adhere to the constraints of HPC environment, i.e., batch jobs run exclusively on allocated nodes. \subsection{Technical Challenges} Managing hybrid workloads on a single large-scale HPC system offers several potential benefits, such as boosting system utilization, mitigating system fragmentation, and reducing job turnaround time. However, the mixed workloads also pose new challenges. \begin{itemize}[leftmargin=*] \item \textit{Maximize instant start rate of on-demand jobs.} One of the primary goals is to maximize the number of on-demand jobs that can start instantly upon their arrival. By moving the dedicated allocation of on-demand requests to a common resource pool, other types of jobs can utilize these resources and improve system utilization. However, the high system utilization also brings the challenge of the decrease in on-demand instant start rate. \item \textit{Minimize resource waste.} To accommodate the hybrid workloads, a proper mechanism must take advantage of job shrink, expansion, and checkpointing strategies. These strategies come with overheads. For example, to make room for time-critical on-demand requests, we could preempt running rigid/malleable jobs and resume them from the latest checkpoints. These preempted jobs will lose the computation after the checkpoints. Hence, an effective solution must take the resource waste into consideration when choosing running jobs for preemption. \item \textit{Incentive of being malleable.} For those jobs that are capable of being adjusted to different sizes, users can either declare them as rigid jobs or malleable jobs. The designed strategies need to provide incentives for users to declare them as malleable jobs by guaranteeing better job performance, i.e., lower average job turnaround time. This could discourage users from lying about their job types. \item \textit{Quick decision making.} To fulfill time-critical on-demand requests, the scheduler has to rapidly choose running jobs to make room for on-demand jobs. Malleable jobs can either be preempted or shrunk, which leads to additional complexity and makes the problem non-trivial. A proper design must be scalable and be capable of making high-quality decisions in a short time (e.g., in seconds). \end{itemize} \begin{figure}[htbp] \centering \centerline{\includegraphics[width=\linewidth]{fig/advance_notice1.png}} \caption{Four types of on-demand jobs.} \label{advance_notice} \vspace*{-.5cm} \end{figure} \section{Methodology}\label{Methodology} In this section, we first formally define our hybrid workload scheduling problem in \S\ref{Problem Formulation}. We then present the six scheduling mechanisms to solve this problem in \S\ref{Mechanisms}. \subsection{Problem Formulation}\label{Problem Formulation} Suppose an HPC system has $N$ identical nodes. Independent jobs $J_1, J_2, ..., J_n$ arrive and are scheduled in order. Jobs can be classified into three categories: \begin{itemize}[leftmargin=*] \item \textbf{Rigid job}: When submitting a rigid job, a user is required to provide two pieces of information: the number of nodes $n$ and job runtime estimate $t_{estimate}$. A rigid job requires a fixed number of nodes, which cannot be adjusted during execution. Job's actual runtime $t_{actual}$ cannot exceed the job runtime estimate ($t_{actual} \leq t_{estimate}$); otherwise, the job will be killed when reaching the runtime estimate \cite{Fan1}. At the beginning of job execution, a job needs some time $t_{setup}$ to set up communication and coordination. During job execution, the job might take regular checkpoints at frequency $t_f$. In case of interruption, the resumed job will first set up communication in $t_{setup}$ time and then resume from the latest checkpoint. As a result, the resumed job will lose the computation between the latest checkpoint and the preempted time. \item \textbf{On-demand job}: On-demand jobs are time-critical applications, which needed to start within a very short time after submission. On-demand jobs are often possible to determine their resource need within a short time (15-30 minutes) before submission. Advance notice includes the following information: estimated job arrival time, job size, and job runtime estimate. Based on the on-demand job's estimated arrival time and actual arrival time, on-demand jobs can be categorized into four groups as shown in Figure \ref{advance_notice}, i.e., without advance notice, with accurate advance notice, arrive early, and arrive late. \item \textbf{Malleable job}: When submitting a malleable job, a user provides the following information: minimum job size $n_{min}$, maximum job size $n_{max}$, job estimate runtime when running at maximum job size $t_{estimate}$. Similar to rigid jobs, we consider setup time at the beginning of the execution. A malleable job is able to run on any integer nodes between minimum job size and maximum job size ($n_{min} \leq n \leq n_{max}$). We assume the linear speedup in addition to the constant setup overhead. Therefore, we can model the job's actual runtime as: $t_{actual} = t_{single}/n + t_{setup}$. Here, $t_{single}$ is the application's runtime on a single compute node. Note that the size of malleable jobs can be adjusted before or during execution according to scheduling policies, which is slightly different from the well-adopted definition of malleable jobs in \cite{IPPS96}. A malleable job typically consists of small-sized tasks and the overhead of changing job size is negligible, and thus it is reasonable to assume no overhead involves in job expansion or shrink. In case of preemption, We adopt Amazon's two minutes warning strategy on spot instance \cite{AWSWarninng}. The scheduler provides two minutes for malleable jobs to make a checkpoint. The resumed malleable jobs first take $t_{setup}$ to set up and then resume from the previous preempted time. Note that we take the different checkpointing strategies for rigid jobs and malleable jobs. Two minutes is sufficient for a malleable job to store its states to disk and thus it can avoid regular checkpointing. \end{itemize} The scheduling problem we study is to allocate resources to on-demand jobs as soon as possible by reserving available nodes and preempting or shrinking running jobs. We aim to increase the responsiveness of on-demand requests with minimal impact on other jobs. \subsection{Mechanisms}\label{Mechanisms} We design our hybrid workloads scheduling problem as a series of decisions triggered by \textit{four types of events of on-demand jobs: advance notice, actual arrival, estimated arrival, and completion}. We propose different strategies to handle these events accordingly. \subsubsection{Advance notice} The advance notice allows the scheduler to prepare resources for on-demand jobs before their actual arrival. We propose three mechanisms to handle on-demand jobs' advance notice: \begin{itemize}[leftmargin=*] \item \textbf{Do nothing (N)}. This is the baseline strategy. The scheduler ignores advance notice and will handle on-demand requests when they actually arrive. \item \textbf{Collect-until-actual-arrival (CUA)}. When receiving an on-demand job's advance notice, the scheduler first collects available nodes for this on-demand job. If more nodes are needed, the scheduler collects nodes released by finished jobs until the requested number of nodes is fulfilled or the on-demand job actually arrives. In case of competition from multiple on-demand jobs, the released nodes are assigned to the on-demand job with the earliest advance notice. \item \textbf{Collect-until-predicted-arrival (CUP)}. This method first reserves the currently available nodes for the on-demand job. If the on-demand job needs more nodes, this method try to prepare sufficient nodes at its predicted arrival time. First, it collects the nodes that are expected to be released before the on-demand predicted arrival time. Second, it preempts running jobs before the on-demand job's predicted arrival time. To minimize the preemption overhead, we try to preempt rigid jobs immediately after checkpointing. If the on-demand job arrives earlier than its predicted arrival time, we stop the preparation and use the strategies in the following subsection to collect more nodes. \end{itemize} \begin{figure}[h] \centerline{\includegraphics[width=\linewidth]{fig/CUA_CUP.png}} \caption{CUA versus CUP. The solid rectangle is the time actually used by a job; the grid rectangle shows the time between job's actual and estimated finish time. CUA reserve the nodes released from J1 and J2. CUP first selects J1; J2 will be preempted immediately after checkpointing (the green dashed line). J2's unfinished computation will be resubmitted and resumed later.} \label{CUA_CUP} \vspace*{-.3cm} \end{figure} Figure \ref{CUA_CUP} uses an example to illustrate the differences between CUA and CUP. To improve the system utilization, the nodes reserved for on-demand jobs can be used to backfill jobs. But once the on-demand job arrives, all these backfilled jobs have to be preempted immediately. \subsubsection{On-demand job's actual arrival} When an on-demand job arrives, the scheduler first checks if there are sufficient available nodes and reserved nodes to run this job. If that is the case, the on-demand job can launch immediately. Otherwise, we propose two strategies to find more nodes: \begin{itemize}[leftmargin=*] \item \textbf{Preempt-at-actual-arrival (PAA)}: This method lists all currently running malleable and rigid jobs in ascending order of their preemption overheads. If the total number of the preemptable nodes is not sufficient, we cannot start the on-demand job instantly and have to put it to the front of the queue waiting for additional available nodes. If the preemptable nodes are sufficient, we preempt jobs from the front of the running list until the on-demand request is satisfied. We update the preempted jobs' estimated runtime, keep their original submit time, and automatically resubmit these jobs to the wait queue. The priority of the preempted jobs is determined by the scheduling policy. For example, FCFS might move the preempted jobs to the front of the queue, because they have very early first submission times. \item \textbf{Shrink-preempt-at-actual-arrival (SPAA)}: This method first finds all currently running malleable jobs and computes the maximum number of nodes they can supply by shrinking to their minimum sizes. If the supply can meet the on-demand job's request, the running malleable jobs will shrink their sizes evenly and linearly adjusts their estimated runtimes. If the supply cannot meet, we will use PAA method to handle the on-demand request. \end{itemize} \subsubsection{Completion of on-demand job} For job fairness, once an on-demand job is completed, the on-demand job will try to return its nodes to the lenders. If a job was preempted by this on-demand job and is still waiting in the queue, the leased nodes will return to this job and this job will resume immediately if possible. If a job was shrunk to make room for the on-demand job and the job is still running, we will expand this job to its original size. \subsubsection{On-demand job's estimated arrival} An on-demand job may arrive late or even do not show up. To preempt deadlock, if an on-demand job has not arrived after a certain period of time of its estimated arrival time, the scheduler will release the reserved nodes. By combining three advance notice strategies with two job arrival strategies, we obtain six mechanisms to schedule hybrid workloads on a single HPC system: \textit{N\&PAA, N\&SPAA, CUA\&PAA, CUA\&SPAA, CUP\&PAA, CUP\&SPAA}. \section{Experimental Setup}\label{Experimental Setup} In this section, we first describe the real workload trace collected from Theta and how to generate traces from the real trace to represent various scenarios (\S\ref{Workloads}). We then introduce the baseline configuration for our experiments (\S\ref{Configuration}) and our simulation environment (\S\ref{Simulation Platform}). Finally, we list the system- and user-centric metrics for evaluation (\S\ref{Evaluation Metrics}). \begin{table}[ht] \begin{minipage}[b]{0.5\linewidth} \centering \resizebox{\linewidth}{!}{ \begin{tabular}{|l|l|l|} \hline \rowcolor{LightCyan} &Theta \\ \hline \rowcolor{Gray} Location &ALCF \\ \hline \rowcolor{LightCyan} Scheduler & Cobalt \\ \hline \rowcolor{Gray} Compute Nodes & \begin{tabular}[c]{@{}l@{}}4,392 KNL\end{tabular} \\ \hline \rowcolor{LightCyan} Trace Period & Jan. - Dec. 2019 \\ \hline \rowcolor{Gray} Number of Jobs & 37,298 \\ \hline \rowcolor{LightCyan} Number of Projects & 211 \\ \hline \rowcolor{Gray} Maximum Job Length &1 day \\ \hline \rowcolor{LightCyan} Minimum Job Size &128 nodes \\ \hline \end{tabular} } \caption{Theta workload.} \label{Theta_workload_table} \end{minipage}\hfill \begin{minipage}[b]{0.5\linewidth} \centering \includegraphics[width=\textwidth]{fig/theta_distribution_pie_chart3.png} \captionof{figure}{The number of jobs (outer) and the total core hours (inner) in different size ranges.} \label{Theta_workload_fig} \end{minipage} \end{table} \begin{comment} \begin{table}[htp] \centering \caption{Theta workload.} \label{Theta_workload_table} \resizebox{0.75\linewidth}{!}{ \begin{tabular}{|l|l|l|} \hline \rowcolor{LightCyan} &Theta \\ \hline \rowcolor{Gray} Location &ALCF \\ \hline \rowcolor{LightCyan} Scheduler & Cobalt \\ \hline \rowcolor{Gray} Compute Nodes & \begin{tabular}[c]{@{}l@{}}4,392 KNL\end{tabular} \\ \hline \rowcolor{LightCyan} Trace Period & Jan. - Dec. 2019 \\ \hline \rowcolor{Gray} Number of Jobs & 37,298 \\ \hline \rowcolor{LightCyan} Number of Projects & 211 \\ \hline \rowcolor{Gray} Maximum Job Length &1 day \\ \hline \rowcolor{LightCyan} Minimum Job Size &128 nodes \\ \hline \end{tabular} } \end{table} \begin{figure}[h] \centerline{\includegraphics[width=0.95\linewidth]{fig/Theta_workload_fig.png}} \caption{The number of jobs and the total core hours in different job size ranges.} \label{Theta_workload_fig} \end{figure} \end{comment} \begin{comment} \begin{figure}[h] \centerline{\includegraphics[width=0.95\linewidth]{fig/on_demand_requests1.png}} \caption{The information of three sample traces denoted by blue, orange, and green lines. The figures present the number of on-demand jobs (top) and the total core-hours requested by the on-demand jobs (bottom) per week.} \label{on_demand_requests} \end{figure} \begin{figure}[!h] \centering \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\linewidth]{fig/job_distribution_15.png} \end{subfigure} \centering \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\linewidth]{fig/core_hours_distribution_15.png} \end{subfigure} \caption{Job type distributions on all traces used in our experiments. The left figure shows the distribution of the number of jobs; the right figure shows the distribution of the core hours used in each job category.} \label{job_distribution} \vspace*{-.2cm} \end{figure} \begin{figure}[!h] \centering \begin{subfigure}{0.241\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_jobs_count.png} \end{subfigure} \centering \begin{subfigure}{0.241\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_jobs_core_hours.png} \end{subfigure} \caption{Three sample traces denoted by blue, orange, and green lines. The figures present the number of on-demand jobs (left) and the total core-hours requested by on-demand jobs (right) per week. The figures demonstrate that the on-demand jobs have bursty behavior. } \label{on_demand_requests} \vspace*{-.5cm} \end{figure} \end{comment} \begin{table}[ht] \begin{minipage}[b]{0.5\linewidth} \centering \includegraphics[width=\textwidth]{fig/job_distribution_15.png} \captionof{figure}{Job type distributions on the traces in our experiments.} \label{job_distribution} \end{minipage}\hfill \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{fig/on_demand_jobs_count.png} \captionof{figure}{The number of on-demand jobs per week. Three sample traces, denoted by blue, orange, and green lines, show their bursty behavior.} \label{on_demand_requests} \end{minipage} \vspace*{-0.2in} \end{table} \subsection{Workloads}\label{Workloads} In this study, we use the one-year workload trace from Theta. Theta is a Cray XC40 machine located at ALCF consisting of 4392 compute nodes with 11.69PF peak performance. Table I summarizes the basic information and Figure 3 presents job characterization of Theta workload. The workload trace includes basic information for scheduling, such as job submission time, runtime estimate, size, username, and project name. Since the trace does not include job type information, we generate a series of workloads based on the real trace to cover various job distributions. Studies have been shown that real on-demand jobs are relatively small in size and have burst submission patterns \cite{Liu}. Users tend to submit a bunch of on-demand jobs in a short period of time. In order to mimic the bursty on-demand job submission pattern, we group jobs by their project names and assume that all jobs belonging to one project have the same job types (i.e., rigid, on-demand, or malleable jobs). For those large on-demand jobs (i.e., job size larger than half of the system size), we randomly reassign them to be rigid jobs or malleable jobs. Figure \ref{job_distribution} shows the statistics of traces used in our experiments. We observe that the rigid, on-demand, malleable job distributions differ significantly on different traces because different projects have significant differences in sizes and submission patterns. Figure \ref{on_demand_requests} shows the on-demand requests of three sample traces. The traces show the bursty on-demand job submission pattern. This enables us to extensively evaluate our mechanisms under various scenarios. \subsection{Configuration}\label{Configuration} In this section, we present the default configurations for different types of jobs. By default, waiting jobs are scheduled by FCFS with EASY backfilling. We assign that 10\% of projects submit on-demand jobs, 60\% of projects submit rigid jobs and the rest of projects submit malleable jobs. We made this assumption because rigid jobs are the main tenant and malleable jobs are emerging in HPC systems. HPC systems can support limited on-demand requests to ensure their responsiveness. In terms of rigid jobs, we set their setup overhead to be 5\%-10\% of their runtimes. We assume rigid jobs make regular checkpoints at the optimal frequency defined by Daly \cite{Daly}. Based on our experience and the current literature \cite{Topper,Moody}, we set each checkpointing overhead to 600 seconds if the job used less than 1K nodes; otherwise, we set it to 1200 seconds. In terms of on-demand jobs, we equally distribute them into the following categories: without advance notice, with accurate advance notice, arrive early, and arrive late. If an on-demand job arrives early, its arrival time is a random number between its advance notice and estimated arrival time. If an on-demand job arrives late, its arrival time is a random number within 30 minutes after its estimated arrival time. We set the threshold to release the reserved nodes to 10 minutes after the on-demand job's estimated arrival time. In terms of malleable jobs, we set their maximum job size to be their original requested job size and their minimum job size to be 20\% of their maximum size. The setup overhead is a random number between 0\%-5\% of their runtimes. \subsection{Trace-based Simulation}\label{Simulation Platform} We compare different scheduling mechanisms through trace-based simulation. Specifically, a trace-based, event-driven scheduling simulator called CQSim is used in our experiments \cite{xu01,Fan4,Li1,Fan5,CQSimGithub,Fan6,Fan7}. CQSim contains a queue manager and a scheduler that can plug in different scheduling policies. It emulates the actual scheduling environment. A real system takes jobs from user submission, while CQSim takes jobs by reading the job arrival information in the trace. Rather than executing jobs on system, CQSim simulates the execution by advancing the simulation clock according to the job runtime information in the trace. \subsection{Evaluation Metrics}\label{Evaluation Metrics} We evaluate the performance of different mechanisms using several user-level and system-level metrics. \begin{enumerate}[leftmargin=*] \item \textbf{Job turnaround time} is a user-level metric. It measures the interval between job submission and completion time. \item \textbf{On-demand jobs' instant start rate} is a user-level metric, which is calculated as the ratio between the number of on-demand jobs started instantly and the total number of on-demand jobs. \item \textbf{Preemption ratio} is a user-level metric to measure the percentage of rigid or malleable jobs being preempted. \item \textbf{System utilization} is a system-level metric that measures the ratio of node-hours used for useful job execution to the total elapsed node-hours. Note that system utilization excludes wasted computation due to preemption. \end{enumerate} \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.327\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.327\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.327\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround_malleable.png} \end{subfigure} \begin{subfigure}{0.245\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_system_uti.png} \end{subfigure} \begin{subfigure}{0.245\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_start_on_time_ratio.png} \end{subfigure} \begin{subfigure}{0.245\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.245\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_preemption_ratio_malleable.png} \end{subfigure} \caption{Scheduling performance under different advance notice accuracies (shown in Table \ref{advance_notice_workload_distribution}). To show the performance under various situations, we repeat the same experiment on ten randomly generated traces and the results in this section are averaged.} \label{advance_notice_results} \vspace*{-.4cm} \end{figure*} \begin{comment} \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.32\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.32\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.32\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround_malleable.png} \end{subfigure} \vspace*{-0.15in} \caption{Job average turnaround time under different advance notice accuracies and scheduling mechanisms. Each bar represents the average results of 10 randomly generated traces; the black line on each bar shows the standard deviation of the 10 results.} \label{on_demand_avg_turnaround} \vspace*{-1.5cm} \end{figure*} \begin{figure}[!h] \centering \begin{subfigure}{0.49\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_system_uti.png} \end{subfigure} \centering \begin{subfigure}{0.49\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_start_on_time_ratio.png} \end{subfigure} \caption{System utilization and on-demand jobs' instant start rate under different advance notice accuracies.} \label{on_demand_system_uti} \end{figure} \begin{figure}[!h] \centering \begin{subfigure}{0.49\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.49\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_preemption_ratio_malleable.png} \end{subfigure} \caption{Job's preemption ratio under different advance notice accuracies.} \label{on_demand_preemption_ratio} \end{figure} \end{comment} \section{Evaluation}\label{Evaluation} To comprehensively evaluate the six proposed mechanisms, we conduct a series of experiments to compare them under various situations/configurations, including different advance notice settings (\S\ref{Impact of the Accuracy of Advance Notice}), and different checkpoint settings (\S\ref{Impact of Checkpointing Frequency}) \begin{table}[h] \centering \caption{Baseline performance. Baseline algorithm is FCFS/EASY backfilling without special treatments on on-demand, rigid, and malleable jobs.} \label{baseline_performance} \begin{tabular}{|l|l|l|} \hline \rowcolor{LightCyan} Avg. Turnaround & System Util. & On-demand Jobs' Instant Start Rate\\ \hline \rowcolor{Gray} 15.6 hours & 83.93\% & 22.69\% \\ \hline \end{tabular} \vspace*{-.4cm} \end{table} \begin{table}[h] \centering \caption{Distribution of on-demand jobs in different workloads. Take W1 as an example: 70\% of on-demand jobs arrive without advance notice; 10\% of on-demand jobs arrive with accurate advance notice; 10\% of on-demand jobs arrive early; the rest 10\% of on-demand jobs arrive late.} \label{advance_notice_workload_distribution} \begin{tabular}{|l|l|l|l|l|} \hline \rowcolor{LightCyan} & No Notice & Accurate Notice & Arrive Early & Arrive Late \\ \hline \rowcolor{Gray} W1 & 70\% & 10\% & 10\% & 10\% \\ \hline \rowcolor{LightCyan} W2 & 10\% & 70\% & 10\% & 10\% \\ \hline \rowcolor{Gray} W3 & 10\% & 10\% & 70\% & 10\% \\ \hline \rowcolor{LightCyan} W4 & 10\% & 10\% & 10\% & 70\% \\ \hline \rowcolor{Gray} W5 & 25\% & 25\% & 25\% & 25\% \\ \hline \end{tabular} \vspace*{-.4cm} \end{table} \subsection{Overall Performance}\label{Overall Performance} Figure \ref{advance_notice_results} compares the performance of the five types of workloads, as shown in Table \ref{advance_notice_workload_distribution}, under different on-demand request accuracies. In this subsection, we make several interesting observations on overall performance from Figure \ref{advance_notice_results}. In the next subsection, we will analyze the impact of advance notice accuracies using these figures. \begin{observation} Comparing with FCFS/EASY, the proposed methods boost system utilization and on-demand jobs' instant start rate, while slightly increase average job turnaround time. \end{observation} Comparing results in Table \ref{baseline_performance} and Figure \ref{advance_notice_results}, we observe that the proposed methods improves system utilization up to 90\%. The on-demand jobs' instant start rate increases from 22\% to 98\%. The average job turnaround time increases from 15 hours to 22 hours, due to job preemption and shrink. \begin{observation} N\&PAA has the worst overall performance. \end{observation} N\&PAA obtains the worst results on average job turnaround time and system utilization. Additionally, its malleable jobs' preemption ratio is noticeably higher than other mechanisms. It suggests that this method has a higher preemption overhead and wastes more computation cycles than other methods. The high average job turnaround time is caused by the starvation of some high-priority jobs. Here, starvation means that jobs were preempted, but could not resume for a long period of time after preemption. Although on-demand jobs return their leased nodes to the lenders, the lenders might not resume immediately, because that on-demand jobs might need a portion of the preempted nodes and the rest are moved to the common resource pool. When the on-demand job is finished, the preempted job can only reclaim the nodes from the on-demand job and it has to wait until more nodes are available. \begin{observation} To achieve higher system utilization and lower malleable jobs' preemption ratio, SPAA methods are preferred than PAA methods. \end{observation} All three SPAA methods largely reduce malleable jobs' preemption ratio, while slightly increase the rigid jobs' preemption ratio. This is because SPAA attempts to find shrink options, which reduces malleable jobs' preemption ratio. Shrink, in general, has lower overhead and leads to fewer wasted computation cycles and therefore higher system utilization. \begin{observation} To obtain lower average job turnaround time and lower rigid jobs' preemption ratio, PAA methods are recommended than SPAA methods, except N\&PAA method. \end{observation} In general, SPAA methods tend to prolong average job turnaround time, especially malleable jobs, because it reduces all running malleable jobs' sizes and prolongs their execution time. On the other hand, PAA affects fewer running jobs and the preempted jobs might resume when the on-demand job finishes. However, N\&PAA is an exception. This is because CUA and CUP prepare some nodes for on-demand jobs before their arrival and PAA only needs to preempt small-sized running jobs upon on-demand job arrival. On the other hand, N\&PAA is more likely to preempt large-sized running jobs, which are more difficult to reclaim their preempted nodes It is interesting to notice that PAA methods lead to slightly lower rigid jobs' preemption ratio than SPAA methods. Since SPAA methods first try to shrink malleable jobs, the job sizes of running jobs are, on average, smaller than that of PAA methods. When the shrink option is not possible, SPAA methods need to preempt more running jobs, which causes the slight increases in the rigid jobs' preemption ratio. \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_avg_turnaround_malleable.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_system_uti.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_start_on_time_ratio.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_preemption_ratio_malleable.png} \end{subfigure} \caption{Impact of rigid jobs' checkpointing frequency on scheduling performance. 50\% means rigid jobs makes checkpoints twice as frequent as the optimal checkpointing frequency. } \vspace*{-0.5cm} \label{checkpoint_results} \end{figure*} \begin{comment} \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_avg_turnaround_malleable.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_system_uti.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_start_on_time_ratio.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_preemption_ratio_malleable.png} \end{subfigure} \caption{Impact of malleable job sizes on scheduling performance. 20\% means malleable job's minimum size is twenty percent of its maximum size. The larger the minimum size is, the less flexible the malleable job is.} \label{malleable_job_sizes_results} \vspace*{-.5cm} \end{figure*} \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_avg_turnaround_malleable.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_system_uti.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_start_on_time_ratio.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_preemption_ratio_malleable.png} \end{subfigure} \caption{Impact of rigid jobs' setup overheads on scheduling performance. 0\%-5\% means rigid job's overhead is randomly chosen between 0\% to 5\% of its runtime.} \label{setup_results} \vspace*{-.5cm} \end{figure*} \end{comment} \begin{observation} CUA methods, in most cases, perform better than CUP methods. \end{observation} As shown in Figure \ref{advance_notice_results}, CUA methods achieve slightly lower average job turnaround time and slightly higher system utilization. Recall that CUA methods passively collect released nodes, while CUP methods might need to preempt some running jobs before on-demand job arrival. CUA methods trigger fewer preemptions, leading to less resource waste and higher system utilization. \begin{observation} CUA\&PAA, CUA\&SPAA, CUP\&PAA, and CUP\&SPAA encourage users to honestly declare their malleable jobs. \end{observation} The malleable jobs' turnaround time of these four methods is noticeably lower than the rigid jobs' turnaround time. For all proposed mechanisms, the scheduler can choose malleable jobs' sizes at their start or resumed time. For SPAA methods, although malleable jobs might need to shrink their sizes upon arrival of on-demand jobs, they are guaranteed to expand to their original sizes by reclaiming their released nodes when the on-demand job finishes. The malleability feature significantly increases the chances of malleable jobs being chosen to execute, leading to lower average turnaround time compared with rigid jobs. The better job performance on malleable jobs discourages users from declaring malleable jobs as rigid jobs. \begin{observation} N\&SPAA method is a good option when the rigid jobs need to achieve low average turnaround time. \end{observation} N\&SPAA achieves the lowest rigid jobs' average turnaround time among the six methods. More importantly, both of its rigid jobs' average turnaround time and malleable jobs' average turnaround time are around 24 hours. When an on-demand job arrives, N\&SPAA first attempts to find shrink options. If there are viable shrink options, the selected malleable jobs will be shrunk and prolonged, while running rigid jobs are not impacted. Upon on-demand job arrival, N\&SPAA requests more nodes than CUA\&SPAA and CUP\&SPAA. Therefore, N\&SPAA has more noticeable adverse effects on malleable jobs than the other SPAA methods. Although N\&SPAA does not provide strong incentives for malleable jobs, it might be a good option for system administrators when rigid jobs have higher priority than malleable jobs. \begin{observation} Malleable jobs' preemption ratio is noticeably higher than rigid jobs' preemption ratio. \end{observation} This is due to the fact that the preemption overheads of malleable jobs are lower than rigid jobs. In order to minimize wasted computation cycles caused by preemption, the running jobs are preempted in ascending order of their preemption overheads. Malleable jobs only waste their setup times. On the other hand, rigid jobs not only waste their setup times but also lose the computation after the latest checkpoints. It is interesting to notice that despite the higher preemption ratio, malleable jobs achieve lower average turnaround times because they are more likely to run by shrinking their sizes. \begin{observation} All methods achieve extremely high on-demand jobs' instant start rate. \end{observation} As shown in Figure \ref{job_distribution}, on-demand jobs represent 3\%-15\% of total workloads. On average, 98\% of on-demand jobs start instantly. There is no significant difference in on-demand jobs' instant start rate between the different methods. The reason why an on-demand job fails to start immediately is that the nodes used by currently running on-demand jobs plus this on-demand job exceed the whole system capacity. This metric is more related to the on-demand jobs' submission pattern. Bursty on-demand job submission pattern could negatively affect the on-demand jobs' instant start rate. \begin{observation} The proposed mechanisms pose trivial scheduling overheads. \end{observation} Current HPC systems typically require a scheduler to respond in 10-30 seconds \cite{Fan3,Fan2}. In our experiments, the proposed methods take less than 10 milliseconds to make a decision, hence being feasible for online deployment. \subsection{Impact of Accuracy of Advance Notice}\label{Impact of the Accuracy of Advance Notice} \begin{observation} The performance of CUP methods highly relies on accuracy of advance notice. The more accurate advance notice, the better performance. \end{observation} CUP\&PAA and CUP\&SPAA methods achieve their best performance on W2, i.e., the workloads with the highest percentage of on-demand jobs with accurate advance notice. The accurate advance notice reduces the preemption ratio on both rigid and malleable jobs and therefore reduces wasted cycles and improves system utilization. The accurate advance notice also reduces average job turnaround time due to less interruption during execution. \begin{observation} The earlier the advance notice, the better the performance of CUA methods. \end{observation} CUA methods obtain the lowest average job turnaround time on W4, i.e., the workloads with the majority of on-demand jobs arrived late. W4 provides a longer period of time between advance notice and job actual arrival. As a result, CUA methods are more likely to collect nodes before the actual arrival of on-demand jobs, and thus decrease the chances of preempting or shrinking running jobs upon arrival of the on-demand jobs. In addition, by preparing more nodes for on-demand jobs before their arrival, it also slightly improves on-demand jobs' instant start rate. \subsection{Impact of Checkpointing Frequency}\label{Impact of Checkpointing Frequency} Figure \ref{checkpoint_results} presents the scheduling results under different checkpointing frequencies. \begin{observation} To achieve better rigid job performance and system performance, we suggest that rigid jobs take more frequent checkpoints than the optimal checkpointing frequency. \end{observation} All methods benefit from the more frequent checkpointing frequency. More frequent checkpoints can reduce rigid jobs' turnaround time and also improve system utilization. Daly's optimal checkpointing frequency is designed for fault tolerance \cite{Daly}. However, the interruption caused by failures is obviously much lower than preemption caused by draining nodes for on-demand jobs. Therefore, increasing checkpointing frequency reduces rigid jobs' lost computation and thus reduces their turnaround time. This also helps improve system utilization by reducing preemption overheads. \begin{comment} \subsection{Impact of Malleable Job Sizes}\label{Impact of Malleable Job Sizes} Figure \ref{malleable_job_sizes_results} present the scheduling results under different malleable job size ranges. \begin{observation} Reducing the job size range of malleable jobs has adverse effects on both system-level and user-level scheduling performance, especially on SPAA methods. \end{observation} The increases in the minimum malleable job sizes reduce the malleable jobs' size range, causing decreased chances of shrinking malleable jobs. Therefore, it increases the preemption ratio of both malleable and rigid jobs, which leads to slight decreases in system utilization. The changes in minimum malleable job sizes have a greater impact on SPAA methods. This is because SPAA cannot start or resume malleable jobs at smaller sizes and might not shrink malleable job sizes for on-demand jobs. \subsection{Impact of Setup Overheads}\label{Impact of Setup Overheads} Figure \ref{setup_results} presents the scheduling results under different rigid jobs' setup overheads. \begin{observation} The lower the setup overhead is, the better the scheduling performance is. \end{observation} When a preempted job resumes, it takes some time to set up. Therefore, the higher setup overhead means the higher preemption overhead and thus the higher average job turnaround time. Additionally, higher setup overhead decreases system utilization by wasting more computation cycles for setup. \begin{observation} If rigid jobs' setup overheads reduce to the amount which is similar to malleable jobs' setup overhead, the rigid jobs' preemption ratio will largely increase. \end{observation} In our experiments, malleable jobs' setup overhead is set to 0\%-5\%. If rigid jobs' setup overhead is reduced to 0\%-5\%, we notice the obvious increases in rigid jobs' preemption ratio and decreases in malleable jobs' preemption ratio, especially on PAA methods. This is because we order running jobs based on their preemption overheads. If we preempt rigid jobs immediately after their checkpoints, their preemption overhead is similar to the overhead of preempting malleable jobs. As a result, rigid jobs' preemption ratio is increased. Second, the performance of CUP methods highly relies on the accuracy of advance notice. CUP\&PAA and CUP\&SPAA methods achieve their best performance on W2, i.e., the workloads with the highest percentage of on-demand jobs with accurate advance notice. The accurate advance notice reduces the preemption ratio on both rigid and malleable jobs and therefore reduces wasted cycles and improves system utilization. The accurate advance notice also reduces on-demand jobs' rejection rate and average job turnaround time due to less interruption during execution. Third, the earlier the advance notice, the better the performance of CUA methods. CUA methods obtain lower average job turnaround time on W4 (the workloads with the majority of on-demand jobs arrived late). W4 provides a longer period of time between advance notice and job actual arrival. As a result, CUA methods are more likely to collect more nodes before the actual arrival of on-demand jobs and thus decrease the chances of preempting or shrinking running jobs when the on-demand job arrives. In addition, by preparing more nodes for on-demand jobs before their arrival, it also slightly reduces their rejection rate. Forth, PAA methods achieve better job turnaround time than SPAA methods, except N\&PAA method. In general, SPAA methods tend to prolong average job turnaround time, especially malleable jobs, because it reduces all running malleable jobs' sizes and prolongs their execution time. On the other hand, PAA affects less number of running jobs and the preempted jobs might resume when the on-demand job finishes. However, N\&PAA is an exception. This is because CUA and CUP methods prepare some nodes for on-demand jobs before their arrival and PAA method only needs to preempt small-sized running jobs when the on-demand jobs arrive. On the other hand, N\&PAA needs more nodes when the on-demand job arrives and thus is more likely to preempt large-sized running jobs. If the on-demand job uses only a portion of preempted nodes, the large-sized jobs are more difficult to claim the rest of the preempted nodes back. Fifth, the turnaround times of malleable jobs are lower than rigid jobs. For SPAA methods, malleable jobs are capable of shrinking their sizes when on-demand jobs need nodes. Unlike PAA methods, shrunk jobs are guaranteed to reclaim their leased nodes back when the on-demand job finishes, which mitigates job starvation problems. For all mechanisms, the scheduler can choose malleable jobs' sizes at their start and resume time. The malleability feature significantly increases the chances of malleable jobs being chosen and obtains a lower average turnaround time compared with rigid jobs. The better job performance on malleable jobs discourages users from declaring their malleable jobs as rigid jobs. Sixth, malleable jobs' preemption ratio is noticeably higher than rigid jobs. This is due to the fact that the preemption overheads of malleable jobs are lower than rigid jobs. In order to minimize wasted computation cycles caused by preemption, the running jobs are preempted in the order of their preemption overheads. Malleable jobs only waste their setup times. On the other hand, rigid jobs not only waste their setup times but also lose the computation after the latest checkpoints. Note that despite the higher preemption ratio, malleable jobs achieve lower average turnaround times because they are more likely to run by shrinking their sizes. Ninth, N\&PAA and N\&SPAA achieve slightly lower rejection rates when most on-demand jobs without advance or arrive early. The result suggests that if the advance notice is very short, preparation does not help to reduce the rejection rate. Tenth, more frequent checkpointing can reduce rigid jobs' turnaround time and also improve system utilization. The optimal checkpointing frequency is designed to minimize the negative effects of failures. However, the interruption caused by failures is obviously lower than preemption caused by draining nodes for on-demand jobs. Therefore, increasing checkpointing frequency reduces rigid jobs' lost computation and thus reduces their job turnaround time, especially for PAA methods. This also helps improve system utilization by reducing preemption overheads. Observation 11: Increasing the minimum malleable job sizes has adverse effects on scheduling performance, especially on SPAA methods. The increases in the minimum malleable job sizes reduce the malleable jobs' size range and also decrease the chances of shrinking malleable jobs. Therefore, it increases the preemption ratio of both malleable and rigid jobs, which leads to slight decreases in system utilization. The changes in minimum malleable job sizes have a greater impact on SPAA methods because SPAA can not only start or resume malleable jobs at smaller sizes but can also shrink malleable job sizes for on-demand jobs. Observation 12: When rigid jobs have higher setup overheads than malleable jobs, the rigid jobs' preemption ratio is noticeably lower than malleable jobs. The higher setup overheads plus the lost computation after the latest checkpoints make rigid jobs less likely to be preempted by the scheduler than malleable jobs. However, when rigid jobs and malleable jobs have similar setup overheads (0\%-5\% runtimes), rigid jobs' chances to be preempted are largely increased. Observation 13: The lower the setup overheads are, the better the scheduling performance is. The low setup overheads reduce the average job turnaround time, especially malleable jobs' turnaround time. Additionally, lower setup overhead improves system utilization by reducing setup wastes. \subsection{Result Summary} \begin{enumerate} \item N\&PAA method has the worst performance. \item To achieve higher system utilization and lower preemption ratio, SPAA methods are preferred than PAA methods. \item To obtain lower average job turnaround time, PAA methods are recommended than SPAA methods. \item CUA methods, in general, perform better than CUP methods, except when the majority of on-demand jobs providing accurate advance notice. In another word, the performance of CPU methods highly relies on the accuracy of advance notice. \item CUA\&PAA, CUA\&SPAA, CUP\&PAA, and CUP\&SPAA encourage users to declare their malleable jobs. On the other hand, N\&SPAA method is preferred when the rigid jobs need a lower average turnaround time. \item Reducing the job size range of malleable jobs has adverse effects on scheduling performance. \item Increasing the checkpointing frequency has beneficial effects on scheduling performance. \item Decreasing rigid jobs' setup overhead improves overall scheduling performance, i.e., system utilization, rigid and malleable jobs average turnaround time. \end{enumerate} \end{comment} \section{Conclusion}\label{Conclusion} In this paper, we have defined and modeled HPC hybrid workload scheduling problem within one HPC system. We have proposed several mechanisms to reconcile the demands from on-demand, rigid, and malleable applications. By exploring how different mechanisms behave under various configurations and workloads, we have found that our proposed mechanisms enable a single HPC system to accommodate on-demand jobs with minimal delay, encourage users to honestly declare their malleable applications, and minimize overheads caused by preemption. Additionally, we have provided several key insights on different mechanisms. In particular, upon on-demand job's advance notice, CUA performs better than CUP. SPAA is, in general, preferred over PAA upon on-demand job arrival. Finally, N\&SPAA achieves surprisingly good performance on rigid jobs. \section*{Acknowledgment} This work is supported in part by US National Science Foundation grants CNS-1717763, CCF-1618776 and U.S. Department of Energy, Office of Science, under contract DE-AC02-06CH11357. \balance \bibliographystyle{unsrt} \section{Introduction} The tremendous compute power with high bandwidth memory and enormous storage capabilities makes high performance computing (HPC) facilities ideal infrastructures for various types of applications. The main tenant of HPC systems is batch applications, which are tightly coupled parallel jobs and are rigid in size. On-demand applications are time-critical applications requiring quick response and thus are used to running on their dedicated clusters. As the sizes of on-demand applications are rapidly expanding in recent years, the dedicated clusters cannot keep up with the rapid expansion in on-demand applications. As a result, HPC system becomes a more practical solution for on-demand applications. Malleable applications are loosely coupled applications consisting of a series of tasks and therefore they can adapt their sizes to changes in hardware availability. Malleable applications are typically running in datacenters. In recent years, an increasing number of HPC systems are equipped with accelerators. The superior computing power combined with the emerging accelerators makes HPC systems an attractive alternative for malleable applications. The production HPC job schedulers, such as Slurm, Moab/TORQUE, PBS, and Cobalt \cite{SLURM,Moab,PBS,Cobalt}, adopt the traditional batch job scheduling model, where users request a fixed amount of resources for a specific amount of time, while the scheduler decides when and where to run each job based on job priority and system availability. A number of studies attempt to address the hybrid workload scheduling on a single HPC system. Research on co-scheduling rigid and on-demand applications often aims at the high responsiveness of on-demand jobs. The common strategies include predicting on-demand jobs' requests, reserving resources for on-demand jobs, and preempting rigid jobs to make room for on-demand jobs \cite{Liu,Maurya}. Other studies focus on co-scheduling malleable jobs with rigid jobs on HPC systems \cite{Balsam,Carroll,Sun2011,Souza,Chadha,Hungershofer,Prabhakaran}. Unfortunately, none of the existing studies address the problem of co-scheduling all three types of applications, i.e., on-demand jobs, rigid jobs, and malleable jobs. Hence, the scheduling implications of co-running these applications are unknown. The potential benefits of executing the hybrid workloads on a single HPC system are supporting ever-increasing on-demand job sizes, reducing resource fragmentation, and improving system utilization by malleable jobs. However, this is a challenging task at both job scheduling level and resource management level. The job scheduler needs to maintain the delicate balance between several conflicting objectives, i.e., quick response to on-demand jobs, high system utilization, the incentive for shrinking malleable jobs, and low impact on rigid jobs. The resource manager has to execute the more complicated and frequent operations from job scheduler, i.e., start, preemption, shrink, and expansion operations. This requires more efficient draining processes and corporation with individual applications. In this paper, we concentrate on addressing HPC hybrid workloads problem from the job scheduling aspect. We propose six mechanisms to address the aforementioned challenges that rely on shrinking, expanding, checkpointing, and resuming techniques to dynamically make room for time-sensitive on-demand applications. Each mechanism focuses on different aspects of scheduling. Our proposed mechanisms are designed to be used in conjunction with the existing scheduling policies: while a scheduling policy determines the order of waiting jobs, our mechanisms manipulate the running jobs in order to meet on-demand requests with minimal impact on other applications. Our design is based on the fact that it is often possible for on-demand jobs to determine their requests within a short time (15-30 minutes) before their actual arrivals \cite{Liu}. Upon receiving on-demand job's advance notice, we provide both non-invasive and invasive mechanisms to reserve resources for the on-demand job. Once an on-demand job arrives, we provide several mechanisms to immediately vacate nodes from running malleable and rigid jobs. By combining the mechanisms used at on-demand job's advance notice and its arrival, we propose six mechanisms to handle hybrid workload scheduling problems. To comprehensively evaluate our mechanisms under various scenarios, we conduct a series of trace-based simulations using various workloads generated based on real workload traces collected from Theta \cite{Theta} at Argonne Leadership Computing Facility (ALCF). The results show that all of the proposed mechanisms achieve quick responsiveness for on-demand jobs. Additionally, the results reveal the impact of different mechanisms on system performance and the performance on malleable and rigid jobs. More importantly, we provide valuable insights for choosing these mechanisms under different situations. \section{Related Work and Challenges}\label{Background and Challenges} \subsection{HPC Application Types}\label{HPC application types} \textbf{Rigid job} is the most common type of job in HPC environments \cite{IPPS96}. Rigid jobs have fixed resource requirements throughout their life cycle. Most parallel applications, such as extreme-scale scientific simulations and modeling, are rigid in nature, requiring inter-process communication through message passing, and checkpointing for fault tolerance \cite{Qiao1}. They are tightly coupled applications that cannot be decomposed to a series of small-sized tasks and are prone to failure due to their sizes \cite{Fan8}. In order to handle hardware failures, rigid applications checkpoint regularly and restart from the latest checkpoint in the event of an interruption. \textbf{On-demand job} is a time-critical application needed to be completed in the shortest time possible. An example of the on-demand jobs is data analytical workloads after experiments \cite{Liu}. Traditionally, to ensure high responsiveness, on-demand jobs are running on dedicated clusters. The rapid experimental expansion requires increasingly large computing capabilities, which cannot be fulfilled by small clusters. The use of large-scale HPC systems becomes a viable solution for the ever-increasing on-demand workloads. \textbf{Malleable job} is another type of parallel job whose sizes can adapt to the number of nodes assigned to them. A malleable job specifies the minimum and the maximum number of nodes. They can shrink down to the minimum sizes or expand up to the maximum sizes based on resource availability. Typically, a malleable job consists of loosely coupled small-sized tasks and the running tasks can be dynamically adjusted based on the assigned nodes. In addition, preemption of malleable jobs causes less overhead than rigid jobs, because they can skip over the finished tasks and resume from the interrupted tasks. The typical examples of malleable jobs are high throughput jobs \cite{Raicu}, multi-task workflows \cite{Balsam}, machine learning applications, and hyperparameter searches in deep neural networks. While traditionally separated infrastructures have been used for rigid jobs and malleable jobs \cite{Sadooghi,He}, the next-generation HPC systems provide not only tremendous compute power on a single node (CPU and GPU), but also enormous high bandwidth memory, making them efficient platforms for malleable workloads \cite{Qiao2}. \subsection{Job Scheduling in HPC}\label{Job scheduling in HPC} HPC job scheduling is traditionally designed to manage and assign rigid jobs to resources. The resource allocation is commonly at the granularity of a node. When submitting a job, a user is required to provide job size and job runtime estimate. At each scheduling instance, the scheduler orders the jobs in the queue according to site policies and resource availability and executes jobs from the head of the queue. The most widely used HPC job scheduling policy is First Come First Serve (FCFS) with EASY backfilling \cite{Feitelson02}. FCFS sorts the jobs in the queue according to their arrival times, while backfilling is often used in conjunction with reservation to enhance system utilization. Backfilling allows subsequent jobs in the queue to move ahead under the condition that they do not delay the existing reservations. In the realm of executing on-demand jobs and rigid jobs on HPC systems, several groups have proposed to statically or dynamically reserve resources for on-demand requests. Dynamical reservation was achieved by predicting the on-demand request patterns \cite{Liu,Maurya}. In terms of accommodating malleable jobs and rigid jobs on HPC systems, several attempts have been made to shrink malleable jobs in order to reduce resource fragmentation problems \cite{Hungershofer,Prabhakaran,Carroll}. To the best of our knowledge, our work is the first attempt to schedule rigid, on-demand, and malleable jobs on a single HPC system. Our design processes on-demand requests by manipulating running rigid and malleable jobs, hence being compatible with existing HPC job scheduling policies concentrating on managing and assigning waiting jobs. Our work also differs from existing cloud resource managers like Mesos and Kubernetes \cite{Mesos,Kubernetes}. Cloud resource managers commonly allow jobs to share nodes. As the result, solutions for addressing bursty on-demand requests often rely on co-scheduling mixed workloads on a single node, which do not adhere to the constraints of HPC environment, i.e., batch jobs run exclusively on allocated nodes. \subsection{Technical Challenges} Managing hybrid workloads on a single large-scale HPC system offers several potential benefits, such as boosting system utilization, mitigating system fragmentation, and reducing job turnaround time. However, the mixed workloads also pose new challenges. \begin{itemize}[leftmargin=*] \item \textit{Maximize instant start rate of on-demand jobs.} One of the primary goals is to maximize the number of on-demand jobs that can start instantly upon their arrival. By moving the dedicated allocation of on-demand requests to a common resource pool, other types of jobs can utilize these resources and improve system utilization. However, the high system utilization also brings the challenge of the decrease in on-demand instant start rate. \item \textit{Minimize resource waste.} To accommodate the hybrid workloads, a proper mechanism must take advantage of job shrink, expansion, and checkpointing strategies. These strategies come with overheads. For example, to make room for time-critical on-demand requests, we could preempt running rigid/malleable jobs and resume them from the latest checkpoints. These preempted jobs will lose the computation after the checkpoints. Hence, an effective solution must take the resource waste into consideration when choosing running jobs for preemption. \item \textit{Incentive of being malleable.} For those jobs that are capable of being adjusted to different sizes, users can either declare them as rigid jobs or malleable jobs. The designed strategies need to provide incentives for users to declare them as malleable jobs by guaranteeing better job performance, i.e., lower average job turnaround time. This could discourage users from lying about their job types. \item \textit{Quick decision making.} To fulfill time-critical on-demand requests, the scheduler has to rapidly choose running jobs to make room for on-demand jobs. Malleable jobs can either be preempted or shrunk, which leads to additional complexity and makes the problem non-trivial. A proper design must be scalable and be capable of making high-quality decisions in a short time (e.g., in seconds). \end{itemize} \begin{figure}[htbp] \centering \centerline{\includegraphics[width=\linewidth]{fig/advance_notice1.png}} \caption{Four types of on-demand jobs.} \label{advance_notice} \vspace*{-.5cm} \end{figure} \section{Methodology}\label{Methodology} In this section, we first formally define our hybrid workload scheduling problem in \S\ref{Problem Formulation}. We then present the six scheduling mechanisms to solve this problem in \S\ref{Mechanisms}. \subsection{Problem Formulation}\label{Problem Formulation} Suppose an HPC system has $N$ identical nodes. Independent jobs $J_1, J_2, ..., J_n$ arrive and are scheduled in order. Jobs can be classified into three categories: \begin{itemize}[leftmargin=*] \item \textbf{Rigid job}: When submitting a rigid job, a user is required to provide two pieces of information: the number of nodes $n$ and job runtime estimate $t_{estimate}$. A rigid job requires a fixed number of nodes, which cannot be adjusted during execution. Job's actual runtime $t_{actual}$ cannot exceed the job runtime estimate ($t_{actual} \leq t_{estimate}$); otherwise, the job will be killed when reaching the runtime estimate \cite{Fan1}. At the beginning of job execution, a job needs some time $t_{setup}$ to set up communication and coordination. During job execution, the job might take regular checkpoints at frequency $t_f$. In case of interruption, the resumed job will first set up communication in $t_{setup}$ time and then resume from the latest checkpoint. As a result, the resumed job will lose the computation between the latest checkpoint and the preempted time. \item \textbf{On-demand job}: On-demand jobs are time-critical applications, which needed to start within a very short time after submission. On-demand jobs are often possible to determine their resource need within a short time (15-30 minutes) before submission. Advance notice includes the following information: estimated job arrival time, job size, and job runtime estimate. Based on the on-demand job's estimated arrival time and actual arrival time, on-demand jobs can be categorized into four groups as shown in Figure \ref{advance_notice}, i.e., without advance notice, with accurate advance notice, arrive early, and arrive late. \item \textbf{Malleable job}: When submitting a malleable job, a user provides the following information: minimum job size $n_{min}$, maximum job size $n_{max}$, job estimate runtime when running at maximum job size $t_{estimate}$. Similar to rigid jobs, we consider setup time at the beginning of the execution. A malleable job is able to run on any integer nodes between minimum job size and maximum job size ($n_{min} \leq n \leq n_{max}$). We assume the linear speedup in addition to the constant setup overhead. Therefore, we can model the job's actual runtime as: $t_{actual} = t_{single}/n + t_{setup}$. Here, $t_{single}$ is the application's runtime on a single compute node. Note that the size of malleable jobs can be adjusted before or during execution according to scheduling policies, which is slightly different from the well-adopted definition of malleable jobs in \cite{IPPS96}. A malleable job typically consists of small-sized tasks and the overhead of changing job size is negligible, and thus it is reasonable to assume no overhead involves in job expansion or shrink. In case of preemption, We adopt Amazon's two minutes warning strategy on spot instance \cite{AWSWarninng}. The scheduler provides two minutes for malleable jobs to make a checkpoint. The resumed malleable jobs first take $t_{setup}$ to set up and then resume from the previous preempted time. Note that we take the different checkpointing strategies for rigid jobs and malleable jobs. Two minutes is sufficient for a malleable job to store its states to disk and thus it can avoid regular checkpointing. \end{itemize} The scheduling problem we study is to allocate resources to on-demand jobs as soon as possible by reserving available nodes and preempting or shrinking running jobs. We aim to increase the responsiveness of on-demand requests with minimal impact on other jobs. \subsection{Mechanisms}\label{Mechanisms} We design our hybrid workloads scheduling problem as a series of decisions triggered by \textit{four types of events of on-demand jobs: advance notice, actual arrival, estimated arrival, and completion}. We propose different strategies to handle these events accordingly. \subsubsection{Advance notice} The advance notice allows the scheduler to prepare resources for on-demand jobs before their actual arrival. We propose three mechanisms to handle on-demand jobs' advance notice: \begin{itemize}[leftmargin=*] \item \textbf{Do nothing (N)}. This is the baseline strategy. The scheduler ignores advance notice and will handle on-demand requests when they actually arrive. \item \textbf{Collect-until-actual-arrival (CUA)}. When receiving an on-demand job's advance notice, the scheduler first collects available nodes for this on-demand job. If more nodes are needed, the scheduler collects nodes released by finished jobs until the requested number of nodes is fulfilled or the on-demand job actually arrives. In case of competition from multiple on-demand jobs, the released nodes are assigned to the on-demand job with the earliest advance notice. \item \textbf{Collect-until-predicted-arrival (CUP)}. This method first reserves the currently available nodes for the on-demand job. If the on-demand job needs more nodes, this method try to prepare sufficient nodes at its predicted arrival time. First, it collects the nodes that are expected to be released before the on-demand predicted arrival time. Second, it preempts running jobs before the on-demand job's predicted arrival time. To minimize the preemption overhead, we try to preempt rigid jobs immediately after checkpointing. If the on-demand job arrives earlier than its predicted arrival time, we stop the preparation and use the strategies in the following subsection to collect more nodes. \end{itemize} \begin{figure}[h] \centerline{\includegraphics[width=\linewidth]{fig/CUA_CUP.png}} \caption{CUA versus CUP. The solid rectangle is the time actually used by a job; the grid rectangle shows the time between job's actual and estimated finish time. CUA reserve the nodes released from J1 and J2. CUP first selects J1; J2 will be preempted immediately after checkpointing (the green dashed line). J2's unfinished computation will be resubmitted and resumed later.} \label{CUA_CUP} \vspace*{-.3cm} \end{figure} Figure \ref{CUA_CUP} uses an example to illustrate the differences between CUA and CUP. To improve the system utilization, the nodes reserved for on-demand jobs can be used to backfill jobs. But once the on-demand job arrives, all these backfilled jobs have to be preempted immediately. \subsubsection{On-demand job's actual arrival} When an on-demand job arrives, the scheduler first checks if there are sufficient available nodes and reserved nodes to run this job. If that is the case, the on-demand job can launch immediately. Otherwise, we propose two strategies to find more nodes: \begin{itemize}[leftmargin=*] \item \textbf{Preempt-at-actual-arrival (PAA)}: This method lists all currently running malleable and rigid jobs in ascending order of their preemption overheads. If the total number of the preemptable nodes is not sufficient, we cannot start the on-demand job instantly and have to put it to the front of the queue waiting for additional available nodes. If the preemptable nodes are sufficient, we preempt jobs from the front of the running list until the on-demand request is satisfied. We update the preempted jobs' estimated runtime, keep their original submit time, and automatically resubmit these jobs to the wait queue. The priority of the preempted jobs is determined by the scheduling policy. For example, FCFS might move the preempted jobs to the front of the queue, because they have very early first submission times. \item \textbf{Shrink-preempt-at-actual-arrival (SPAA)}: This method first finds all currently running malleable jobs and computes the maximum number of nodes they can supply by shrinking to their minimum sizes. If the supply can meet the on-demand job's request, the running malleable jobs will shrink their sizes evenly and linearly adjusts their estimated runtimes. If the supply cannot meet, we will use PAA method to handle the on-demand request. \end{itemize} \subsubsection{Completion of on-demand job} For job fairness, once an on-demand job is completed, the on-demand job will try to return its nodes to the lenders. If a job was preempted by this on-demand job and is still waiting in the queue, the leased nodes will return to this job and this job will resume immediately if possible. If a job was shrunk to make room for the on-demand job and the job is still running, we will expand this job to its original size. \subsubsection{On-demand job's estimated arrival} An on-demand job may arrive late or even do not show up. To preempt deadlock, if an on-demand job has not arrived after a certain period of time of its estimated arrival time, the scheduler will release the reserved nodes. By combining three advance notice strategies with two job arrival strategies, we obtain six mechanisms to schedule hybrid workloads on a single HPC system: \textit{N\&PAA, N\&SPAA, CUA\&PAA, CUA\&SPAA, CUP\&PAA, CUP\&SPAA}. \section{Experimental Setup}\label{Experimental Setup} In this section, we first describe the real workload trace collected from Theta and how to generate traces from the real trace to represent various scenarios (\S\ref{Workloads}). We then introduce the baseline configuration for our experiments (\S\ref{Configuration}) and our simulation environment (\S\ref{Simulation Platform}). Finally, we list the system- and user-centric metrics for evaluation (\S\ref{Evaluation Metrics}). \begin{table}[ht] \begin{minipage}[b]{0.5\linewidth} \centering \resizebox{\linewidth}{!}{ \begin{tabular}{|l|l|l|} \hline \rowcolor{LightCyan} &Theta \\ \hline \rowcolor{Gray} Location &ALCF \\ \hline \rowcolor{LightCyan} Scheduler & Cobalt \\ \hline \rowcolor{Gray} Compute Nodes & \begin{tabular}[c]{@{}l@{}}4,392 KNL\end{tabular} \\ \hline \rowcolor{LightCyan} Trace Period & Jan. - Dec. 2019 \\ \hline \rowcolor{Gray} Number of Jobs & 37,298 \\ \hline \rowcolor{LightCyan} Number of Projects & 211 \\ \hline \rowcolor{Gray} Maximum Job Length &1 day \\ \hline \rowcolor{LightCyan} Minimum Job Size &128 nodes \\ \hline \end{tabular} } \caption{Theta workload.} \label{Theta_workload_table} \end{minipage}\hfill \begin{minipage}[b]{0.5\linewidth} \centering \includegraphics[width=\textwidth]{fig/theta_distribution_pie_chart3.png} \captionof{figure}{The number of jobs (outer) and the total core hours (inner) in different size ranges.} \label{Theta_workload_fig} \end{minipage} \end{table} \begin{comment} \begin{table}[htp] \centering \caption{Theta workload.} \label{Theta_workload_table} \resizebox{0.75\linewidth}{!}{ \begin{tabular}{|l|l|l|} \hline \rowcolor{LightCyan} &Theta \\ \hline \rowcolor{Gray} Location &ALCF \\ \hline \rowcolor{LightCyan} Scheduler & Cobalt \\ \hline \rowcolor{Gray} Compute Nodes & \begin{tabular}[c]{@{}l@{}}4,392 KNL\end{tabular} \\ \hline \rowcolor{LightCyan} Trace Period & Jan. - Dec. 2019 \\ \hline \rowcolor{Gray} Number of Jobs & 37,298 \\ \hline \rowcolor{LightCyan} Number of Projects & 211 \\ \hline \rowcolor{Gray} Maximum Job Length &1 day \\ \hline \rowcolor{LightCyan} Minimum Job Size &128 nodes \\ \hline \end{tabular} } \end{table} \begin{figure}[h] \centerline{\includegraphics[width=0.95\linewidth]{fig/Theta_workload_fig.png}} \caption{The number of jobs and the total core hours in different job size ranges.} \label{Theta_workload_fig} \end{figure} \end{comment} \begin{comment} \begin{figure}[h] \centerline{\includegraphics[width=0.95\linewidth]{fig/on_demand_requests1.png}} \caption{The information of three sample traces denoted by blue, orange, and green lines. The figures present the number of on-demand jobs (top) and the total core-hours requested by the on-demand jobs (bottom) per week.} \label{on_demand_requests} \end{figure} \begin{figure}[!h] \centering \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\linewidth]{fig/job_distribution_15.png} \end{subfigure} \centering \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\linewidth]{fig/core_hours_distribution_15.png} \end{subfigure} \caption{Job type distributions on all traces used in our experiments. The left figure shows the distribution of the number of jobs; the right figure shows the distribution of the core hours used in each job category.} \label{job_distribution} \vspace*{-.2cm} \end{figure} \begin{figure}[!h] \centering \begin{subfigure}{0.241\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_jobs_count.png} \end{subfigure} \centering \begin{subfigure}{0.241\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_jobs_core_hours.png} \end{subfigure} \caption{Three sample traces denoted by blue, orange, and green lines. The figures present the number of on-demand jobs (left) and the total core-hours requested by on-demand jobs (right) per week. The figures demonstrate that the on-demand jobs have bursty behavior. } \label{on_demand_requests} \vspace*{-.5cm} \end{figure} \end{comment} \begin{table}[ht] \begin{minipage}[b]{0.5\linewidth} \centering \includegraphics[width=\textwidth]{fig/job_distribution_15.png} \captionof{figure}{Job type distributions on the traces in our experiments.} \label{job_distribution} \end{minipage}\hfill \begin{minipage}[b]{0.48\linewidth} \centering \includegraphics[width=\textwidth]{fig/on_demand_jobs_count.png} \captionof{figure}{The number of on-demand jobs per week. Three sample traces, denoted by blue, orange, and green lines, show their bursty behavior.} \label{on_demand_requests} \end{minipage} \vspace*{-0.2in} \end{table} \subsection{Workloads}\label{Workloads} In this study, we use the one-year workload trace from Theta. Theta is a Cray XC40 machine located at ALCF consisting of 4392 compute nodes with 11.69PF peak performance. Table I summarizes the basic information and Figure 3 presents job characterization of Theta workload. The workload trace includes basic information for scheduling, such as job submission time, runtime estimate, size, username, and project name. Since the trace does not include job type information, we generate a series of workloads based on the real trace to cover various job distributions. Studies have been shown that real on-demand jobs are relatively small in size and have burst submission patterns \cite{Liu}. Users tend to submit a bunch of on-demand jobs in a short period of time. In order to mimic the bursty on-demand job submission pattern, we group jobs by their project names and assume that all jobs belonging to one project have the same job types (i.e., rigid, on-demand, or malleable jobs). For those large on-demand jobs (i.e., job size larger than half of the system size), we randomly reassign them to be rigid jobs or malleable jobs. Figure \ref{job_distribution} shows the statistics of traces used in our experiments. We observe that the rigid, on-demand, malleable job distributions differ significantly on different traces because different projects have significant differences in sizes and submission patterns. Figure \ref{on_demand_requests} shows the on-demand requests of three sample traces. The traces show the bursty on-demand job submission pattern. This enables us to extensively evaluate our mechanisms under various scenarios. \subsection{Configuration}\label{Configuration} In this section, we present the default configurations for different types of jobs. By default, waiting jobs are scheduled by FCFS with EASY backfilling. We assign that 10\% of projects submit on-demand jobs, 60\% of projects submit rigid jobs and the rest of projects submit malleable jobs. We made this assumption because rigid jobs are the main tenant and malleable jobs are emerging in HPC systems. HPC systems can support limited on-demand requests to ensure their responsiveness. In terms of rigid jobs, we set their setup overhead to be 5\%-10\% of their runtimes. We assume rigid jobs make regular checkpoints at the optimal frequency defined by Daly \cite{Daly}. Based on our experience and the current literature \cite{Topper,Moody}, we set each checkpointing overhead to 600 seconds if the job used less than 1K nodes; otherwise, we set it to 1200 seconds. In terms of on-demand jobs, we equally distribute them into the following categories: without advance notice, with accurate advance notice, arrive early, and arrive late. If an on-demand job arrives early, its arrival time is a random number between its advance notice and estimated arrival time. If an on-demand job arrives late, its arrival time is a random number within 30 minutes after its estimated arrival time. We set the threshold to release the reserved nodes to 10 minutes after the on-demand job's estimated arrival time. In terms of malleable jobs, we set their maximum job size to be their original requested job size and their minimum job size to be 20\% of their maximum size. The setup overhead is a random number between 0\%-5\% of their runtimes. \subsection{Trace-based Simulation}\label{Simulation Platform} We compare different scheduling mechanisms through trace-based simulation. Specifically, a trace-based, event-driven scheduling simulator called CQSim is used in our experiments \cite{xu01,Fan4,Li1,Fan5,CQSimGithub,Fan6,Fan7}. CQSim contains a queue manager and a scheduler that can plug in different scheduling policies. It emulates the actual scheduling environment. A real system takes jobs from user submission, while CQSim takes jobs by reading the job arrival information in the trace. Rather than executing jobs on system, CQSim simulates the execution by advancing the simulation clock according to the job runtime information in the trace. \subsection{Evaluation Metrics}\label{Evaluation Metrics} We evaluate the performance of different mechanisms using several user-level and system-level metrics. \begin{enumerate}[leftmargin=*] \item \textbf{Job turnaround time} is a user-level metric. It measures the interval between job submission and completion time. \item \textbf{On-demand jobs' instant start rate} is a user-level metric, which is calculated as the ratio between the number of on-demand jobs started instantly and the total number of on-demand jobs. \item \textbf{Preemption ratio} is a user-level metric to measure the percentage of rigid or malleable jobs being preempted. \item \textbf{System utilization} is a system-level metric that measures the ratio of node-hours used for useful job execution to the total elapsed node-hours. Note that system utilization excludes wasted computation due to preemption. \end{enumerate} \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.327\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.327\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.327\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround_malleable.png} \end{subfigure} \begin{subfigure}{0.245\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_system_uti.png} \end{subfigure} \begin{subfigure}{0.245\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_start_on_time_ratio.png} \end{subfigure} \begin{subfigure}{0.245\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.245\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_preemption_ratio_malleable.png} \end{subfigure} \caption{Scheduling performance under different advance notice accuracies (shown in Table \ref{advance_notice_workload_distribution}). To show the performance under various situations, we repeat the same experiment on ten randomly generated traces and the results in this section are averaged.} \label{advance_notice_results} \vspace*{-.4cm} \end{figure*} \begin{comment} \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.32\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.32\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.32\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_avg_turnaround_malleable.png} \end{subfigure} \vspace*{-0.15in} \caption{Job average turnaround time under different advance notice accuracies and scheduling mechanisms. Each bar represents the average results of 10 randomly generated traces; the black line on each bar shows the standard deviation of the 10 results.} \label{on_demand_avg_turnaround} \vspace*{-1.5cm} \end{figure*} \begin{figure}[!h] \centering \begin{subfigure}{0.49\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_system_uti.png} \end{subfigure} \centering \begin{subfigure}{0.49\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_start_on_time_ratio.png} \end{subfigure} \caption{System utilization and on-demand jobs' instant start rate under different advance notice accuracies.} \label{on_demand_system_uti} \end{figure} \begin{figure}[!h] \centering \begin{subfigure}{0.49\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.49\textwidth} \centering \includegraphics[width=\linewidth]{fig/on_demand_preemption_ratio_malleable.png} \end{subfigure} \caption{Job's preemption ratio under different advance notice accuracies.} \label{on_demand_preemption_ratio} \end{figure} \end{comment} \section{Evaluation}\label{Evaluation} To comprehensively evaluate the six proposed mechanisms, we conduct a series of experiments to compare them under various situations/configurations, including different advance notice settings (\S\ref{Impact of the Accuracy of Advance Notice}), and different checkpoint settings (\S\ref{Impact of Checkpointing Frequency}) \begin{table}[h] \centering \caption{Baseline performance. Baseline algorithm is FCFS/EASY backfilling without special treatments on on-demand, rigid, and malleable jobs.} \label{baseline_performance} \begin{tabular}{|l|l|l|} \hline \rowcolor{LightCyan} Avg. Turnaround & System Util. & On-demand Jobs' Instant Start Rate\\ \hline \rowcolor{Gray} 15.6 hours & 83.93\% & 22.69\% \\ \hline \end{tabular} \vspace*{-.4cm} \end{table} \begin{table}[h] \centering \caption{Distribution of on-demand jobs in different workloads. Take W1 as an example: 70\% of on-demand jobs arrive without advance notice; 10\% of on-demand jobs arrive with accurate advance notice; 10\% of on-demand jobs arrive early; the rest 10\% of on-demand jobs arrive late.} \label{advance_notice_workload_distribution} \begin{tabular}{|l|l|l|l|l|} \hline \rowcolor{LightCyan} & No Notice & Accurate Notice & Arrive Early & Arrive Late \\ \hline \rowcolor{Gray} W1 & 70\% & 10\% & 10\% & 10\% \\ \hline \rowcolor{LightCyan} W2 & 10\% & 70\% & 10\% & 10\% \\ \hline \rowcolor{Gray} W3 & 10\% & 10\% & 70\% & 10\% \\ \hline \rowcolor{LightCyan} W4 & 10\% & 10\% & 10\% & 70\% \\ \hline \rowcolor{Gray} W5 & 25\% & 25\% & 25\% & 25\% \\ \hline \end{tabular} \vspace*{-.4cm} \end{table} \subsection{Overall Performance}\label{Overall Performance} Figure \ref{advance_notice_results} compares the performance of the five types of workloads, as shown in Table \ref{advance_notice_workload_distribution}, under different on-demand request accuracies. In this subsection, we make several interesting observations on overall performance from Figure \ref{advance_notice_results}. In the next subsection, we will analyze the impact of advance notice accuracies using these figures. \begin{observation} Comparing with FCFS/EASY, the proposed methods boost system utilization and on-demand jobs' instant start rate, while slightly increase average job turnaround time. \end{observation} Comparing results in Table \ref{baseline_performance} and Figure \ref{advance_notice_results}, we observe that the proposed methods improves system utilization up to 90\%. The on-demand jobs' instant start rate increases from 22\% to 98\%. The average job turnaround time increases from 15 hours to 22 hours, due to job preemption and shrink. \begin{observation} N\&PAA has the worst overall performance. \end{observation} N\&PAA obtains the worst results on average job turnaround time and system utilization. Additionally, its malleable jobs' preemption ratio is noticeably higher than other mechanisms. It suggests that this method has a higher preemption overhead and wastes more computation cycles than other methods. The high average job turnaround time is caused by the starvation of some high-priority jobs. Here, starvation means that jobs were preempted, but could not resume for a long period of time after preemption. Although on-demand jobs return their leased nodes to the lenders, the lenders might not resume immediately, because that on-demand jobs might need a portion of the preempted nodes and the rest are moved to the common resource pool. When the on-demand job is finished, the preempted job can only reclaim the nodes from the on-demand job and it has to wait until more nodes are available. \begin{observation} To achieve higher system utilization and lower malleable jobs' preemption ratio, SPAA methods are preferred than PAA methods. \end{observation} All three SPAA methods largely reduce malleable jobs' preemption ratio, while slightly increase the rigid jobs' preemption ratio. This is because SPAA attempts to find shrink options, which reduces malleable jobs' preemption ratio. Shrink, in general, has lower overhead and leads to fewer wasted computation cycles and therefore higher system utilization. \begin{observation} To obtain lower average job turnaround time and lower rigid jobs' preemption ratio, PAA methods are recommended than SPAA methods, except N\&PAA method. \end{observation} In general, SPAA methods tend to prolong average job turnaround time, especially malleable jobs, because it reduces all running malleable jobs' sizes and prolongs their execution time. On the other hand, PAA affects fewer running jobs and the preempted jobs might resume when the on-demand job finishes. However, N\&PAA is an exception. This is because CUA and CUP prepare some nodes for on-demand jobs before their arrival and PAA only needs to preempt small-sized running jobs upon on-demand job arrival. On the other hand, N\&PAA is more likely to preempt large-sized running jobs, which are more difficult to reclaim their preempted nodes It is interesting to notice that PAA methods lead to slightly lower rigid jobs' preemption ratio than SPAA methods. Since SPAA methods first try to shrink malleable jobs, the job sizes of running jobs are, on average, smaller than that of PAA methods. When the shrink option is not possible, SPAA methods need to preempt more running jobs, which causes the slight increases in the rigid jobs' preemption ratio. \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_avg_turnaround_malleable.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_system_uti.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_start_on_time_ratio.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/checkpoint_preemption_ratio_malleable.png} \end{subfigure} \caption{Impact of rigid jobs' checkpointing frequency on scheduling performance. 50\% means rigid jobs makes checkpoints twice as frequent as the optimal checkpointing frequency. } \vspace*{-0.5cm} \label{checkpoint_results} \end{figure*} \begin{comment} \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_avg_turnaround_malleable.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_system_uti.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_start_on_time_ratio.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/malleable_job_size_preemption_ratio_malleable.png} \end{subfigure} \caption{Impact of malleable job sizes on scheduling performance. 20\% means malleable job's minimum size is twenty percent of its maximum size. The larger the minimum size is, the less flexible the malleable job is.} \label{malleable_job_sizes_results} \vspace*{-.5cm} \end{figure*} \begin{figure*}[!h] \centering \begin{subfigure}{\textwidth} \includegraphics[width=\linewidth]{fig/legend.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_avg_turnaround.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_avg_turnaround_rigid.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_avg_turnaround_malleable.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_system_uti.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_start_on_time_ratio.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_preemption_ratio_rigid.png} \end{subfigure} \begin{subfigure}{0.23\textwidth} \centering \includegraphics[width=\linewidth]{fig/setup_preemption_ratio_malleable.png} \end{subfigure} \caption{Impact of rigid jobs' setup overheads on scheduling performance. 0\%-5\% means rigid job's overhead is randomly chosen between 0\% to 5\% of its runtime.} \label{setup_results} \vspace*{-.5cm} \end{figure*} \end{comment} \begin{observation} CUA methods, in most cases, perform better than CUP methods. \end{observation} As shown in Figure \ref{advance_notice_results}, CUA methods achieve slightly lower average job turnaround time and slightly higher system utilization. Recall that CUA methods passively collect released nodes, while CUP methods might need to preempt some running jobs before on-demand job arrival. CUA methods trigger fewer preemptions, leading to less resource waste and higher system utilization. \begin{observation} CUA\&PAA, CUA\&SPAA, CUP\&PAA, and CUP\&SPAA encourage users to honestly declare their malleable jobs. \end{observation} The malleable jobs' turnaround time of these four methods is noticeably lower than the rigid jobs' turnaround time. For all proposed mechanisms, the scheduler can choose malleable jobs' sizes at their start or resumed time. For SPAA methods, although malleable jobs might need to shrink their sizes upon arrival of on-demand jobs, they are guaranteed to expand to their original sizes by reclaiming their released nodes when the on-demand job finishes. The malleability feature significantly increases the chances of malleable jobs being chosen to execute, leading to lower average turnaround time compared with rigid jobs. The better job performance on malleable jobs discourages users from declaring malleable jobs as rigid jobs. \begin{observation} N\&SPAA method is a good option when the rigid jobs need to achieve low average turnaround time. \end{observation} N\&SPAA achieves the lowest rigid jobs' average turnaround time among the six methods. More importantly, both of its rigid jobs' average turnaround time and malleable jobs' average turnaround time are around 24 hours. When an on-demand job arrives, N\&SPAA first attempts to find shrink options. If there are viable shrink options, the selected malleable jobs will be shrunk and prolonged, while running rigid jobs are not impacted. Upon on-demand job arrival, N\&SPAA requests more nodes than CUA\&SPAA and CUP\&SPAA. Therefore, N\&SPAA has more noticeable adverse effects on malleable jobs than the other SPAA methods. Although N\&SPAA does not provide strong incentives for malleable jobs, it might be a good option for system administrators when rigid jobs have higher priority than malleable jobs. \begin{observation} Malleable jobs' preemption ratio is noticeably higher than rigid jobs' preemption ratio. \end{observation} This is due to the fact that the preemption overheads of malleable jobs are lower than rigid jobs. In order to minimize wasted computation cycles caused by preemption, the running jobs are preempted in ascending order of their preemption overheads. Malleable jobs only waste their setup times. On the other hand, rigid jobs not only waste their setup times but also lose the computation after the latest checkpoints. It is interesting to notice that despite the higher preemption ratio, malleable jobs achieve lower average turnaround times because they are more likely to run by shrinking their sizes. \begin{observation} All methods achieve extremely high on-demand jobs' instant start rate. \end{observation} As shown in Figure \ref{job_distribution}, on-demand jobs represent 3\%-15\% of total workloads. On average, 98\% of on-demand jobs start instantly. There is no significant difference in on-demand jobs' instant start rate between the different methods. The reason why an on-demand job fails to start immediately is that the nodes used by currently running on-demand jobs plus this on-demand job exceed the whole system capacity. This metric is more related to the on-demand jobs' submission pattern. Bursty on-demand job submission pattern could negatively affect the on-demand jobs' instant start rate. \begin{observation} The proposed mechanisms pose trivial scheduling overheads. \end{observation} Current HPC systems typically require a scheduler to respond in 10-30 seconds \cite{Fan3,Fan2}. In our experiments, the proposed methods take less than 10 milliseconds to make a decision, hence being feasible for online deployment. \subsection{Impact of Accuracy of Advance Notice}\label{Impact of the Accuracy of Advance Notice} \begin{observation} The performance of CUP methods highly relies on accuracy of advance notice. The more accurate advance notice, the better performance. \end{observation} CUP\&PAA and CUP\&SPAA methods achieve their best performance on W2, i.e., the workloads with the highest percentage of on-demand jobs with accurate advance notice. The accurate advance notice reduces the preemption ratio on both rigid and malleable jobs and therefore reduces wasted cycles and improves system utilization. The accurate advance notice also reduces average job turnaround time due to less interruption during execution. \begin{observation} The earlier the advance notice, the better the performance of CUA methods. \end{observation} CUA methods obtain the lowest average job turnaround time on W4, i.e., the workloads with the majority of on-demand jobs arrived late. W4 provides a longer period of time between advance notice and job actual arrival. As a result, CUA methods are more likely to collect nodes before the actual arrival of on-demand jobs, and thus decrease the chances of preempting or shrinking running jobs upon arrival of the on-demand jobs. In addition, by preparing more nodes for on-demand jobs before their arrival, it also slightly improves on-demand jobs' instant start rate. \subsection{Impact of Checkpointing Frequency}\label{Impact of Checkpointing Frequency} Figure \ref{checkpoint_results} presents the scheduling results under different checkpointing frequencies. \begin{observation} To achieve better rigid job performance and system performance, we suggest that rigid jobs take more frequent checkpoints than the optimal checkpointing frequency. \end{observation} All methods benefit from the more frequent checkpointing frequency. More frequent checkpoints can reduce rigid jobs' turnaround time and also improve system utilization. Daly's optimal checkpointing frequency is designed for fault tolerance \cite{Daly}. However, the interruption caused by failures is obviously much lower than preemption caused by draining nodes for on-demand jobs. Therefore, increasing checkpointing frequency reduces rigid jobs' lost computation and thus reduces their turnaround time. This also helps improve system utilization by reducing preemption overheads. \begin{comment} \subsection{Impact of Malleable Job Sizes}\label{Impact of Malleable Job Sizes} Figure \ref{malleable_job_sizes_results} present the scheduling results under different malleable job size ranges. \begin{observation} Reducing the job size range of malleable jobs has adverse effects on both system-level and user-level scheduling performance, especially on SPAA methods. \end{observation} The increases in the minimum malleable job sizes reduce the malleable jobs' size range, causing decreased chances of shrinking malleable jobs. Therefore, it increases the preemption ratio of both malleable and rigid jobs, which leads to slight decreases in system utilization. The changes in minimum malleable job sizes have a greater impact on SPAA methods. This is because SPAA cannot start or resume malleable jobs at smaller sizes and might not shrink malleable job sizes for on-demand jobs. \subsection{Impact of Setup Overheads}\label{Impact of Setup Overheads} Figure \ref{setup_results} presents the scheduling results under different rigid jobs' setup overheads. \begin{observation} The lower the setup overhead is, the better the scheduling performance is. \end{observation} When a preempted job resumes, it takes some time to set up. Therefore, the higher setup overhead means the higher preemption overhead and thus the higher average job turnaround time. Additionally, higher setup overhead decreases system utilization by wasting more computation cycles for setup. \begin{observation} If rigid jobs' setup overheads reduce to the amount which is similar to malleable jobs' setup overhead, the rigid jobs' preemption ratio will largely increase. \end{observation} In our experiments, malleable jobs' setup overhead is set to 0\%-5\%. If rigid jobs' setup overhead is reduced to 0\%-5\%, we notice the obvious increases in rigid jobs' preemption ratio and decreases in malleable jobs' preemption ratio, especially on PAA methods. This is because we order running jobs based on their preemption overheads. If we preempt rigid jobs immediately after their checkpoints, their preemption overhead is similar to the overhead of preempting malleable jobs. As a result, rigid jobs' preemption ratio is increased. Second, the performance of CUP methods highly relies on the accuracy of advance notice. CUP\&PAA and CUP\&SPAA methods achieve their best performance on W2, i.e., the workloads with the highest percentage of on-demand jobs with accurate advance notice. The accurate advance notice reduces the preemption ratio on both rigid and malleable jobs and therefore reduces wasted cycles and improves system utilization. The accurate advance notice also reduces on-demand jobs' rejection rate and average job turnaround time due to less interruption during execution. Third, the earlier the advance notice, the better the performance of CUA methods. CUA methods obtain lower average job turnaround time on W4 (the workloads with the majority of on-demand jobs arrived late). W4 provides a longer period of time between advance notice and job actual arrival. As a result, CUA methods are more likely to collect more nodes before the actual arrival of on-demand jobs and thus decrease the chances of preempting or shrinking running jobs when the on-demand job arrives. In addition, by preparing more nodes for on-demand jobs before their arrival, it also slightly reduces their rejection rate. Forth, PAA methods achieve better job turnaround time than SPAA methods, except N\&PAA method. In general, SPAA methods tend to prolong average job turnaround time, especially malleable jobs, because it reduces all running malleable jobs' sizes and prolongs their execution time. On the other hand, PAA affects less number of running jobs and the preempted jobs might resume when the on-demand job finishes. However, N\&PAA is an exception. This is because CUA and CUP methods prepare some nodes for on-demand jobs before their arrival and PAA method only needs to preempt small-sized running jobs when the on-demand jobs arrive. On the other hand, N\&PAA needs more nodes when the on-demand job arrives and thus is more likely to preempt large-sized running jobs. If the on-demand job uses only a portion of preempted nodes, the large-sized jobs are more difficult to claim the rest of the preempted nodes back. Fifth, the turnaround times of malleable jobs are lower than rigid jobs. For SPAA methods, malleable jobs are capable of shrinking their sizes when on-demand jobs need nodes. Unlike PAA methods, shrunk jobs are guaranteed to reclaim their leased nodes back when the on-demand job finishes, which mitigates job starvation problems. For all mechanisms, the scheduler can choose malleable jobs' sizes at their start and resume time. The malleability feature significantly increases the chances of malleable jobs being chosen and obtains a lower average turnaround time compared with rigid jobs. The better job performance on malleable jobs discourages users from declaring their malleable jobs as rigid jobs. Sixth, malleable jobs' preemption ratio is noticeably higher than rigid jobs. This is due to the fact that the preemption overheads of malleable jobs are lower than rigid jobs. In order to minimize wasted computation cycles caused by preemption, the running jobs are preempted in the order of their preemption overheads. Malleable jobs only waste their setup times. On the other hand, rigid jobs not only waste their setup times but also lose the computation after the latest checkpoints. Note that despite the higher preemption ratio, malleable jobs achieve lower average turnaround times because they are more likely to run by shrinking their sizes. Ninth, N\&PAA and N\&SPAA achieve slightly lower rejection rates when most on-demand jobs without advance or arrive early. The result suggests that if the advance notice is very short, preparation does not help to reduce the rejection rate. Tenth, more frequent checkpointing can reduce rigid jobs' turnaround time and also improve system utilization. The optimal checkpointing frequency is designed to minimize the negative effects of failures. However, the interruption caused by failures is obviously lower than preemption caused by draining nodes for on-demand jobs. Therefore, increasing checkpointing frequency reduces rigid jobs' lost computation and thus reduces their job turnaround time, especially for PAA methods. This also helps improve system utilization by reducing preemption overheads. Observation 11: Increasing the minimum malleable job sizes has adverse effects on scheduling performance, especially on SPAA methods. The increases in the minimum malleable job sizes reduce the malleable jobs' size range and also decrease the chances of shrinking malleable jobs. Therefore, it increases the preemption ratio of both malleable and rigid jobs, which leads to slight decreases in system utilization. The changes in minimum malleable job sizes have a greater impact on SPAA methods because SPAA can not only start or resume malleable jobs at smaller sizes but can also shrink malleable job sizes for on-demand jobs. Observation 12: When rigid jobs have higher setup overheads than malleable jobs, the rigid jobs' preemption ratio is noticeably lower than malleable jobs. The higher setup overheads plus the lost computation after the latest checkpoints make rigid jobs less likely to be preempted by the scheduler than malleable jobs. However, when rigid jobs and malleable jobs have similar setup overheads (0\%-5\% runtimes), rigid jobs' chances to be preempted are largely increased. Observation 13: The lower the setup overheads are, the better the scheduling performance is. The low setup overheads reduce the average job turnaround time, especially malleable jobs' turnaround time. Additionally, lower setup overhead improves system utilization by reducing setup wastes. \subsection{Result Summary} \begin{enumerate} \item N\&PAA method has the worst performance. \item To achieve higher system utilization and lower preemption ratio, SPAA methods are preferred than PAA methods. \item To obtain lower average job turnaround time, PAA methods are recommended than SPAA methods. \item CUA methods, in general, perform better than CUP methods, except when the majority of on-demand jobs providing accurate advance notice. In another word, the performance of CPU methods highly relies on the accuracy of advance notice. \item CUA\&PAA, CUA\&SPAA, CUP\&PAA, and CUP\&SPAA encourage users to declare their malleable jobs. On the other hand, N\&SPAA method is preferred when the rigid jobs need a lower average turnaround time. \item Reducing the job size range of malleable jobs has adverse effects on scheduling performance. \item Increasing the checkpointing frequency has beneficial effects on scheduling performance. \item Decreasing rigid jobs' setup overhead improves overall scheduling performance, i.e., system utilization, rigid and malleable jobs average turnaround time. \end{enumerate} \end{comment} \section{Conclusion}\label{Conclusion} In this paper, we have defined and modeled HPC hybrid workload scheduling problem within one HPC system. We have proposed several mechanisms to reconcile the demands from on-demand, rigid, and malleable applications. By exploring how different mechanisms behave under various configurations and workloads, we have found that our proposed mechanisms enable a single HPC system to accommodate on-demand jobs with minimal delay, encourage users to honestly declare their malleable applications, and minimize overheads caused by preemption. Additionally, we have provided several key insights on different mechanisms. In particular, upon on-demand job's advance notice, CUA performs better than CUP. SPAA is, in general, preferred over PAA upon on-demand job arrival. Finally, N\&SPAA achieves surprisingly good performance on rigid jobs. \section*{Acknowledgment} This work is supported in part by US National Science Foundation grants CNS-1717763, CCF-1618776 and U.S. Department of Energy, Office of Science, under contract DE-AC02-06CH11357. \balance \bibliographystyle{unsrt}
{'timestamp': '2021-09-14T02:18:39', 'yymm': '2109', 'arxiv_id': '2109.05412', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05412'}
arxiv
\section{Introduction} In recent years, machine learning (ML) has gained much popularity and became an integral part of our daily life. Current state-of-the-art algorithms are complex models which are difficult to interpret and rely on thousands, and even billions of parameters. Gaining insight into how these complex algorithms work is a key step towards better understanding our environment. Further, it is a crucial step for enabling ML algorithms to support and assist human decision making in complex fields (for example, as in medicine \citep{lundberg2018explainable}). FI is one of the basic tools for this purpose. The general FI framework scores input variables by their contribution to the predictive model, allowing us to gain insight into which features are important for this task. GBM \citep{friedman2001greedy} is an ensemble of base (weak) learners. These learners are typically standard implementations of tree-based models such are CART \citep{breiman1984classification}, C4.5 \citep{quinlan1986induction}, and others. GBM's are among the current state-of-the-art ML techniques on tabular data in a variety of tasks such as click prediction \citep{richardson2007predicting}, ranking \citep{burges2010ranknet} and others. Besides its accuracy, the GBM framework holds many virtues which makes it a favorable choice for many learning tasks. It is efficient, can handle categorical variables and deals with any kind of differential loss function. Further, it supports missing values and invariant to feature scaling. However, it is well known that GBM base learners are biased towards categorical variables with large cardinalities \citep{breiman1984classification}. As a consequence, ensemble methods that rely on such biased learners suffer from the same flaw \citep{strobl2007bias}. In this work we study the effect of base learners' bias on FI measures, in standard GBM implementations. We show that in the presence of categorical features with large alphabets, most FI measures are typically biased. This results in miss-interpreted models. To overcome this caveat, we utilize a cross-validated boosting (CVB) framework. CVB addresses the tree's bias through a simple modification: during the training stage of the tree, a variable is selected for splitting based on its cross-validated performance, rather than on its training sample performance (see \cite{painsky2016cross}, for example). This way, we conduct a ''fair” comparison between features, utilizing only high cardinality categorical features that show to be informative, in terms of their estimated generalization abilities. The rest of this manuscript is organized as follows, in Section \ref{Background} we review previous related work. In Section \ref{Formulation Of CVB} we formalize and define cross-validated boosting (CVB). Section \ref{Methods} outlines the experiment design in which we compare CVB to other GBM frameworks. In Section \ref{simulation_studies} we compare CVB to common open-source GBM implementations and show that CVB is the only algorithm that does not suffer from biased FI in high cardinality features through simulation studies. Finally, Section \ref{Real Data Case Studies} contains two comprehensive real data case studies, showing that CVB FI is more reliable than alternative schemes. We conclude the manuscript in Section \ref{discussion}. \section{Background} \label{Background} \subsection{Decision Trees} Decision trees are a long standing staple of predictive modeling. Popular tree building algorithms can handle both numerical and categorical variables, and build models for regression, binary and multi-class classification. Decision trees are built recursively to minimize a given loss function. At each step, the split which optimizes a given criterion is selected from all possible splits over on all variables. We hereby present the CART approach, which is one of the most widely used tree implementation in current GBM implementations. Let $\{x_i, y_i\}_{i=1}^{N}$ be a training set with $N$ samples , where $x_i \in \mathbb{R}^p, y_i \in \mathbb{R}$. The standard CART approach is a binary tree which utilizes either squared error loss impurity criterion (regression) or the Gini index (classification) to evaluate a possible split. At each internal node of a tree, a split $s$ is a partition of $n$ observations to two disjoint subsets $R(s)$ and $L(s)$. In regression tress, the squared error impurity criterion is defined as \begin{equation} \label{equation1} \mathcal{I}(s) = \Sigma_{i \in L(s)} (y_i - \bar{y}_L)^2 +\Sigma_{i \in R(s)} (y_i - \bar{y}_R)^2, \end{equation} where $\bar{y}_L, \bar{y}_R$ are the means of the response $y$ over the sets $L(s), R(s)$ respectively. The split gain (SG) is defined as the amount of decrease in impurity of the split: \begin{equation} \label{equation2} SG(s) = \Sigma_{i=1}^n (y_i - \bar{y})^2 - \mathcal{I}(s). \end{equation} At each node, CART examines all possible splits for each feature and selects the split with the minimum impurity (maximum gain). For each variable $j$, we denote the set of possible splits by $S_j$ and their cardinality by $|S_j|$. Let $K_j$ be the number of categories in a categorical feature $j$. For each numerical/ordinal variable, CART considers only splits along the sorted variable. Therefore, there are $|S_j| \leq n-1$ possible splits between its unique sorted values. For a categorical variable, there are $|S_j| = 2^{K_j -1}$ possible binary splits, but it is sufficient to sort the categories by their mean response value and search for splits along this axis \citep{breiman1984classification}, reducing the complexity to only $K_j-1$ splits. Without any regularization mechanism, terminal nodes are split and deep, complex trees are formed. Thus, stopping criteria are typically applied to prevent over-fitting and reduce tree complexity. Several common stopping criteria are the maximum tree depth, minimum samples to split, minimum samples leaf and minimum impurity decrease. It is also possible to grow a tree to its maximum depth and then to prune it, such as in minimal cost-complexity pruning \citep{breiman1984classification}. An additional commonly used decision tree implementation is C4.5 \citep{quinlan1986induction}. C4.5 considers K-way splits for categorical features (as opposed to binary splits in CART). C4.5 trees may be problematic for large cardinality categorical features as they result in splits with very few samples, and henceforth induce variance. Further, C4.5 trees are not used in recent GBM implementations. A comprehensive discussion on different splitting frameworks is provided in \citep{loh2014fifty}. \subsection{Gradient Boosting Trees} GBM is an ensemble model of $M$ regression trees, trained sequentially one after the other, in order to predict the previous trees' errors. GBM may be viewed as gradient descent in a functional space, where in each iteration of GBM, a tree is grown to estimate the gradient of the objective function. Let $F_m : \mathbb{R}^p \rightarrow \mathbb{R}$ be a predictive model at stage $m$, where $m = 1,....,M$. Let $\mathcal{L}(y_i,F_m(x_i))$ be a differentiable loss function. For example, $\mathcal{L}_{SE}(y_i,F_m(x_i))=(y_i-F_m(x_i))^2$ is the squared error loss in the standard regression case. GBM initializes with a constant model by estimating a parameter that minimizes the overall loss (for the squared error $F_0(x_i) = \bar{y}$). Then, at every iteration $m$, a regression decision tree $h_m$ is trained to minimize the empirical risk \begin{equation*} h_m = \operatorname*{argmin}_h \Sigma_{i=1}^N \mathcal{L}(y_i,F_{m-1}(x_i) + h(x_i)). \end{equation*} $h_m$ is obtained by fitting a regression tree to the gradients of each sample with respect to the current estimator at stage $m$. The optimal step size is calculated per each leaf by a line search. $h_m$ can be seen as the best greedy step in order to minimize the empirical risk. In order to reduce over-fitting, a learning-rate $\alpha$ is used and the model is updated, $F_m = F_{m-1} + \alpha h_m$. This process is repeated until $M$ trees are grown. Later, inspired by Breiman's bootstrap-aggregating (bagging) \citep{breiman1996bagging}, Friedman showed that a stochastic modification to GBM can substantially improve the prediction error of GBM \citep{friedman2002stochastic}. In its stochastic form, GBM fits each tree on a sub-sample of the training-set, sampled at random without replacement. \subsection{GBM Implementations} \label{gbm_implementations} There are many implementations of GBM in the literature. Many of these implementations follow Friedman's GBM, which is based on CART trees. In the age of big data, modern ML tasks require very large datasets. Therefore, the need for more scalable, distributed, GBM solutions arouse (such as \cite{tyree2011parallel}). This line of work mostly focuses on efficient implementation of GBM in distributed environments such as MapReduce \citep{condie2010mapreduce}. Here, the most notable implementation is XGBoost \citep{chen2016xgboost}. XGBoost has two main advantages. First, it unifies previous ideas of distributed computing with novel optimizations such as out-of-core-computation and sparsity-awareness. Thus, producing much lower run-time both on a single machine and in a distributed environment. Second, XGBoost introduces a new regularized learning objective which penalizes the complexity of the model. The result is a highly scaled end-to-end open-source implementation that produces state-of-the-art results, winning multiple data science open competitions. Unfortunately, the main drawback of the XGBoost framework is the lack of categorical variables support. Specifically, in order to utilize a categorical feature one needs to transform it to numeric variables such as in one-hot-encoding or to use \textit{term statistics}. One-hot-encoding is a valid method to transform categorical features to numeric ones, but in cases of high cardinality variables, it substantially increases the number of features and henceforth the execution time. \textit{Term statistics} is a method to transform a categorical feature to numeric by using the target value. Here, each category is replaced with its respective mean response value or a smoothed version of it \citep{prokhorenkova2018catboost}. The main problem with this approach is that it implies an order among the categories, and limits the expressive power of CART in categorical splits. Following XGBoost, Microsoft introduced LightGBM (LGBM) \citep{ke2017lightgbm}. LGBM is a faster implementation of GBM which supports categorical features. LGBM uses sampling techniques to exclude data instances with small gradients and \textit{exclusive feature bundling} to reduce the number of features tested to split at each node while achieving almost the same accuracy. More importantly, LGBM supports categorical features out-of-the-box and follows the original CART approach. Lately, CatBoost pushed the envelope of treating categorical features in GBM even further. CatBoost addresses a \textit{target leakage} (see \cite{prokhorenkova2018catboost}) to significantly improve the prediction error. For categorical variables, CatBoost uses ordered \textit{term statistics} and it is henceforth more memory efficient than LGBM. Further, CatBoost utilizes oblivious trees as base learners. Oblivious decision trees are decision trees for which all nodes at the same level use the same feature to split. These trees are balanced, less prone to over-fitting, and allow speeding up execution at testing time. Finally, CatBoost uses combinations of categorical features as additional categorical features to capture high-order dependencies between categorical features. \subsection{FI Methods} Understanding the decision-making mechanism of a ML algorithm is an important task in many applications. First, in several setups, attaining the best prediction is not our sole intent; we would like to know more about the problem and the data. Second, model interpretability is a key step for achieving and quantifying other desirable properties in artificial intelligence (AI) such as fairness, robustness, and causality \citep{doshi2017towards}. Finally, as AI enters new domains as health and transportation (autonomous vehicles), interpretation is essential to trust those mechanisms and adopt them as an integral part of our lives. While some ML algorithms are intrinsically interpretive (linear regression), they tend to be over-simplistic and generally suffer from a high bias. As modern ML evolves and computing power increases, complex algorithms are developed to attain superior prediction capabilities but in turn provide little interpretation. For this reason, many methods are developed to make these non-interpretable ML methods more understandable. These methods typically provide summary statistics for each variable, which can also be visualised for better understanding. Global FI measures attempt to summarise to which extent each feature is important for the prediction task. Given an algorithm, train and/or test data, a global FI method outputs a single number per each feature that reflects its importance. A local FI measure outputs a FI vector per each observation. Thus, it provides a more detailed, personalized FI. Local explanations are crucial in fields such as personalized medicine. For instance, local explanations can assist anesthesiologists to avoid hypoxemia during surgery, by providing real-time interpretable risks and contributing factors \citep{lundberg2018explainable}. Interaction FI are methods that measure the strength of the interaction between two features. A FI method is said to be model agnostic if it can be applied in the same manner for any ML algorithm. On the other hand, a FI measure is said to be model specific if it only applies for a specific algorithm \citep{molnar2020interpretable}. While FI aims to understand which features are important given a trained model, feature selection methods usually train a model several times in order to reduce dimensionality for speed considerations \citep{pan2009feature} or to avoid over-fitting in cases such as ''large-p small-n" tasks. While FI measures can be used as a means for variable selection by taking the most influential features, variable selection methods can not always be used as FI measures. For example, methods that rely on greedy backward elimination of features (such as \citep{kursa2010feature,gregorutti2017correlation}), still need to use a FI measure to score each variable in the final selected feature subset. \subsubsection{Global FI Methods} As mentioned above, global FI measures can be agnostic or model-specific. A global model-specific FI for GBM can be derived by evaluating its individual trees FI and averaging them across all trees in the ensemble \citep{friedman2001greedy}. Given a tree, there are many methods to interpret how important is a feature by inspecting the non-terminal nodes and their corresponding features which were used for splitting. The most prominent measures are: \begin{itemize} \item Split count - the number of times a feature is selected for a split in a tree. \item Cover - the number of observations in the training set that a node had split. Specifically, for every feature $j$, Cover is the total number of observations in splits that involve this feature. \item Gain or the decrease in impurity \citep{breiman1984classification} - for every feature $j$, Gain is the sum of SG (\ref{equation2}) that utilize this feature. \end{itemize} These measures are intuitive, simple and achieve a FI score that is often consistent with other FI measures at a low computational cost. Unfortunately, they are also extremely biased towards categorical variables with large cardinalities \citep{strobl2007bias}, as later described in Section \ref{fi_bias}. Among the model agnostic global FI methods, the Permutation FI (PFI) \citep{breiman2001random} is perhaps the most common approach. Its rationale is as follow. By randomly permuting the $j^{th}$ feature, its original association with the response variable is broken. Assume that the $j^{th}$ feature is associated with the outcome. As we apply the permuted feature, together with the remaining un-permuted features, to a given learning algorithm, the prediction accuracy is expected to substantially decrease. Thus, a reasonable measure for FI is the difference between the prediction error before and after permuting the variable. The PFI measure relies on random permutations which greatly varies. Unfortunately, to achieve a reliable estimate, it is required to conduct multiple permutations, which is computationally demanding. PFI can be calculated both on the train-set and on the test-set, where each approach has its advantages \citep{molnar2020interpretable}. The train-set can be used to estimate the amount of model reliance on each feature. However, model error based on train data is often too optimistic and does not reflect the generalization performance \citep{molnar2020interpretable}. Using the PFI on the test-set reflects the extent to which a feature contributes to the model on unseen data, but may not reflect cases where the model heavily relies on a feature (see Section \ref{simulation_studies}). A key problem with PFI is in cases where the dataset contains correlated features. Here, forcing a specific value of a feature may be misleading. For example, consider the case of two given features, \textit{Gender} and \textit{Pregnant}. Forcing the gender variable to be \textit{Male} might result in a pregnant male as a data point. Further, it was shown that correlated features tend to "benefit" from the presence of each other and thus their PFI tends to inflate \citep{nicodemus2010behaviour}. The leave one covariate out (LOCO) \citep{lei2018distribution} is another type of a model agnostic FI measure, which resembles in spirit to the PFI. LOCO evaluates the variable importance as the difference between the test-error of a model which was trained on all the data, and a model which is trained on all the data but the specified variable. Since training a model can be time consuming, this method may not be suitable in the presence of large data with many observations and features. Similarly to the PFI, LOCO may vary quite notably. Therefore, to obtain a reliable estimate, it is better to repeat this procedure a large number of times. Unfortunately, it substantially increases the execution time. Another popular global FI measure is the surrogate model. A global surrogate model trains an interpretable ML model in order to estimate the predictions of a black-box model. Then, the FI of the black-box model derived from the interpretable surrogate model. Finally, it is important to mention that global FI can also be obtained by averaging the results of local FI measure (see \ref{local_fi_measures} below) measures across observations. Specifically, a global FI of a feature is just the mean of the local FI for this variable, over all observations. \subsubsection{Local FI Methods} \label{local_fi_measures} Similarity to global FI, the local methods are also either model-specific or model-agnostic. The model-specific measures typically obtain a FI score for each tree, and average the scores along the ensemble. \cite{sabaas} was the first to propose a local FI for decision tree ensembles. Inspired by Gain FI, \cite{sabaas} evaluates the change of the expected value before and after a split in non-terminal nodes. To attain a model-agnostic local FI measure it is possible to utilize a local surrogate model. For example, \textit{local surrogate model interpretable model-Agnostic} (LIME) \citep{ribeiro2016should} was proposed to attain a FI for a specific observation by training an interpretable model in the proximity of this observation. Specifically, for each observation, LIME creates an artificial dataset and trains an interpretable model on this data. The observation FI is estimated as the global FI of the interpretable model. In \textit{SHapley Additive exPlanations} (SHAP) \cite{lundberg2017unified} unify surrogate models with ideas from cooperative game-theory by estimating the \textit{Shapely} value. The \textit{Shapely} value of each prediction is the average marginal contribution of a feature to the prediction over all possible feature subsets. The Shapely value has many theoretical guarantees and desirable properties. In general, obtaining the exact \textit{Shapely} value in a model agnostic scenario requires exponential time. Later, \cite{lundberg2018consistent} introduced an exact polynomial-time algorithm to compute the SHAP values for trees (TreeSHAP) and tree ensembles. Although theoretically promising, TreeSHAP can assign a non-zero value to features that have no influence on the prediction \citep{molnar2020interpretable}. Along the global and local FI methods, there are graphical approaches to further interpret the decision making principles of a black- box ML algorithhm \citep{molnar2020interpretable}. In this work, we focus on global FI measures since they are more popular, and demonstrate the bias of high cardinality categorical features most clearly and concisely. For the rest of the paper, and unless stated otherwise, global FI is referred to as FI. \subsection{Bias in Tree Based Algorithms} \label{fi_bias} It is well-known that decision trees are biased towards categorical features with many categories. The reason for this phenomenon is quite obvious. During the training process, a node is split according to the variable which minimizes the error on the train-set (\ref{equation2}). Since categorical features allow more possible splits than numerical ones, they are more likely to be selected for a split. For example an \textit{ID} feature, which consists of a unique category for each observation, would minimize the spitting criterion compared to any possible feature. Based on this observation, most contributions which aim to achieve an unbiased FI measure focus on eliminating the bias on the tree level \citep{strobl2007bias, painsky2016cross}. A variety of solutions to tree-bias were suggested over the years. The first line of work focuses on unbiased variable selection using hypothesis testing frameworks \citep{loh2002regression,kim2003classification,loh1997split}. For example, in QUEST \citep{loh1997split}, the authors test the association of each feature with the labels and choose the variable with the most significant p-value to split. For numerical features, the p-values are derived from an ANOVA F-statistics while in categorical features they are derived from a $\chi^2$ test. Later, Hothorn et al. generalized these methods by conditional inference trees (CIT), which utilizes nonparametric tests for the same purpose \citep{hothorn2006unbiased}. These approaches are built on a well defined statistical theory, which either assumes a-priori modeling assumptions on the distribution of the features \citep{loh1997split} or using permutation or nonparametric tests such as in CIT \citep{hothorn2006unbiased}. One of the main problems with these methods are the a-priori assumptions, which are not always reasonable. On the other hand, nonparametric statistical tests may be computationally demanding. When an ensemble of trees is sequentially built (as in GBM) this problem becomes more evident. Further, notice that the most ''informative" feature at each node is the one that splits the observations such that the generalization error (GE) is minimal. This is not necessarily the variable that achieves the smallest p-values under the null assumption \citep{painsky2016cross}. Thus, these methods may decrease the predictive performance of CART. For these reasons, a second line of work suggests ranking categorical features by their estimated GE. Ranking categorical features according to their GE was previously proposed for trees with k-way splits by \cite{sabato2008ranking} using Leave-One-Out (LOO) cross-validation \citep{frank1996selecting,frank1998using}. Recently, \cite{painsky2016cross} introduced \textit{adaptive LOO variable selection} (ALOOF) that is applicable for binary trees. ALOOF constructs an unbiased tree by conducting a ''fair" comparison between both numerical and categorical variables, using LOO estimates. This way, a large cardinality categorical feature is selected for a split if it proves to be effective on out-of-sample observations. \section{Formulation Of CVB} \label{Formulation Of CVB} CVB introduces a single modification to the original GBM framework. We hereby present the K-fold approach which is used in our CVB implementation. At the node selection phase, CVB selects the split based on cross-validation, and then splits it similarly to CART. Let $\mathcal{A}$ be the collection of all observations in a given node. We randomly divide the samples in $\mathcal{A}$ to $T$ equal sets of observations. Let $\{\mathcal{A}_t\}_{t=1}^T$ be the $T$ (non-overlapping) sets. For each set $\mathcal{A}_t$ we denote $\bar{\mathcal{A}}^t$ as the set of all observations that are not in $\mathcal{A}_t$. Specifically, $\bar{\mathcal{A}}^t = \mathcal{A} \setminus \mathcal{A}_t$. For every $t=1,\dots,T$, we find the optimal split over $\bar{\mathcal{A}}^t$, according to (\ref{equation1}). Then, we evaluate the permanence of the split on $\mathcal{A}_t$. The rank of the feature is the average performance over all $t=1,\dots,T$. We choose the split with the lowest rank and split it following CART's splitting rule. Notice that CVB is similar in spirit to \citep{painsky2016cross}, as it applies a K-fold CV to evaluate every possible split. A Python implementation of CVB is publicly available at Github\footnote{https://github.com/aba27059/unbiased\_fi\_for\_gb}. \subsection{CVB Stopping Criteria} Tree algorithms like CART require a stopping criterion to avoid over-complex models that typically overfit. In GBM, it is most common to restrict the tree depth rather than using pruning approaches for speed considerations. Another common regularization technique in trees is the minimum gain decrease as shown in (\ref{equation2}). If the gain of the best split is less than a predefined hyper-parameter, the tree branch stops to grow and becomes a leaf. Although using the minimum gain decrease is a valid method to avoid over-fitting, it is more difficult for humans to interpret, as it is measured in units that depend on the impurity criterion and change greatly from one dataset to the other. In CVB, a tree ceases to grow if the best estimated GE across all features is greater than the impurity before the split. The result is a built-in regularization mechanism, which resembles minimum gain decrease. In practice, it leads to more interpretable models; CVB demonstrates a significant reduction in the number of trees, as well as a reduction in the number of leaves. \section{Methods} \label{Methods} In the following sections we compare different FI measures in current GBM implementations on binary classification and regression tasks. We use GBM implementations that provide built-in categorical variables handling. Specifically, CatBoost, LGBM, and Friedman's GBM (Vanilla GBM). We leave XGBoost outside the scope of this paper as it requires either one-hot-encoding which results in unfeasible run-time on the studied problems. We use the following FI measures: Gain, PFI, and SHAP. Since SHAP is a local method, we derive its global FI\footnote{https://github.com/slundberg/shap}. It is important to emphasize that these FI measures are not (directly) integrated in some of the GBM implementations mentioned above. Specifically, CatBoost interface does not offer Gain FI nor node inspection data. Therefore, we use its Gain inspired default FI as in the official documentation\footnote{https://CatBoost.ai/docs/concepts/fstr.html}. Further, since SHAP FI official package has built-in integration for CatBoost and LGBM open-source implementations, we report it when possible or refer to its results in the Appendix. We set the following hyper-parameters across all our experiments (and for all the studied algorithms): maximum tree depth = $3$, number of base learners (number of trees) = $100$, learning rate (shrinkage) = $0.1$. We do not change other default hyper-parameters values and do not apply bagging (stochastic GBM). We focus on mean squared error (MSE) to measure the regression error and log-loss \citep{painsky2018universality} to measure the binary classification error. When evaluating PFI, we apply twenty permutations to estimate the decrease in model performance. On real datasets, we use K-fold cross-validation to compute error and FI metrics (with K = 30 unless stated otherwise). In CVB, for the node selection phase, we use $T = 5$. Throughout our experiments, we report the scaled FI. That is, we scale the FI values over all variables, so they sum to one\footnote{In some cases, the PFI can also be negative; we consider this case as zero importance.}. \section{Bias In Gradient Boosting FI} \label{simulation_studies} We start with a simple synthetic data experiment that demonstrates the FI bias in current GBM implementations. We follow the setup introduced by \cite{strobl2007bias}, which studied a binary classification task with five features. In their setup, X0 is a numeric feature which follows a standard normal distribution, and X1 to X4 are four categorical features which follow a uniform distribution over alphabet sizes 10, 20, 50 and 100 respectively. In our experiment, we draw $n=6000$ observations, train a GBM model and compare the corresponding FI measures. We repeat this experiment $100$ times and report the average merits. \subsection{Null Case} In the first experiment, which we refer to as the \textit{null case}, the target variable is independent of the features and follows a Bernoulli distribution with a parameter $p=0.5$. In this setup, none of the features are informative with respect to the response variable. Thus, a perfect FI measure shall score each feature a zero score. Figure \ref{null_exp} demonstrates the PFI and Gain FI results. The Gain FI \textit{(left)} illustrates the discussed bias in categorical variables. Specifically, we observe that categorical features with high cardinality tend to attain a greater FI than the rest, despite the fact that all features are not informative. In vanilla GBM and LGBM this phenomenon is more evident where $X3$ and $X4$ account together for almost $90\%$ of the overall FI whereas in CatBoost we observe a more subtle and monotone effect. CVB reliably recognizes uninformative features and scores zero importance for each feature. It is important to emphasize that although the reported scores are scaled, CVB attains zero FI scores. The reason lies on the standard convention, stating that if all scores are zero defined (which corresponds to stub trees), then their scaled score is zero as well. The right charts in Figure \ref{null_exp} demonstrate the PFI. Here, the mean FI of uninformative variables is around zero. This is not quite surprising, as the PFI is measured on the test-set. Nevertheless, we observe that features with high cardinality result in a greater variance than the rest, both in LGBM, Vanilla GBM, and CatBoost. CatBoost outperforms LGBM and Vanilla GBM and obtains around 10 times smaller FI for the uninformative variables. CVB outperforms CatBoost and again scores the uninformative features with zero importance. For LGBM and CatBoost, the SHAP FI (Appendix A) demonstrates the same monotonic behavior and scores similarly to the CatBoost Gain FI. Although in LGBM the slope is greater, CatBoost demonstrates a much greater variance. \begin{figure*}[t] \centering \fontsize{18}{28} \textbf{Simulation 1: \textit{null case}}\par\medskip \hspace*{-0.5cm} \includegraphics[width=13.5cm, height = 8cm]{plots/null_exp} \vspace*{-10mm} \caption{\textit{Scaled Gain FI (left) and PFI (right) for the \textit{null case} experiment where all displayed features are uninformative.}} \label{null_exp} \end{figure*} \subsection{Power Case} In the second experiment $Y$ depends on $X1$ in the following manner: \begin{equation} Y = \begin{cases} \text{Ber}(0.5 + \alpha) \text{, X1} \in \{0,1,2,3,4\} \\ \text{Ber}(0.5 - \alpha) \text{, X1} \in \{5,6,7,8,9\} \end{cases} \end{equation} where $\text{Ber}$ is a Bernoulli distribution and $\alpha$ is a predefined parameter. In this experiment, for $\alpha>0$, a perfect FI measure would assign a positive importance to $X1$ whereas the rest of the features shall attain zero importance. Figure \ref{power_exp} demonstrates the results we achieve for the uninformative features (all but $X1$) for the case where $\alpha = 0.2$. The Gain FI \textit{(left)} assigns only $37\%$ and $42\%$ FI to $X1$ for Vanilla GBM and LGBM where CatBoost performs better with $91\%$ FI for $X1$. CVB outperforms all the baseline schemes with $99.5\%$ FI assigned to the informative feature. As with the \textit{null case}, LGBM and Vanilla GBM over-fit the train-set in cases where high cardinality features are present, and attain a significantly greater FI for $X3$ and $X4$. In CatBoost, this phenomenon is considerably more subtle. Similarly to the \textit{null case}, the PFI \textit{(right)} variance increases with the category size, for all the algorithms besides CVB. CatBoost outperforms the baselines with a variance that is an order of magnitude smaller than LGBM and Vanilla LGBM. Let us now focus on the scaled PFI. LGBM and Vanilla GBM assigns $95.4\%$ importance for $X1$ whereas CatBoost assigns $99.4\%$ for it. CVB outperforms CatBoost and assigns $99.9\%$ FI for $X1$. Finally, SHAP FI (Appendix A) scores $55.3\%$ and $90.0\%$ FI for X1 in LGBM and CatBoost respectively. Following Strobel's study \citep{strobl2007bias}, we conclude that all GBM implementations exhibits FI bias to some extent. Specifically, Vanilla GBM and LGBM perform the worst and are highly prone to over-fit large cardinality categorical features. CatBoost is one scale better then the former, attaining a significantly smaller bias than its alternatives. Finally, CVB is superior even to CatBoost, and demonstrates a reliable FI measure with almost no bias. \begin{figure*}[t] \centering \fontsize{18}{28} \textbf{Simulation 2: \textit{power case}}\par\medskip \hspace*{-0.5cm} \includegraphics[width=13.5cm, height = 8.3cm]{plots/0.2_exp} \vspace*{-10mm} \caption{\textit{Scaled Gain FI (left) and PFI (right) for the \textit{power case} experiment where only $X1$ is informative. Since $X1$ is informative it is on a different scale and it is threfore omitted to improve visualization. Its mean values are $0.186$, $0.181$, $0.166$, $0.145$ for Vanilla GBM, LGBM, CatBoost and CVB respectively.}} \label{power_exp} \end{figure*} \section{Real Data Case Studies} \label{Real Data Case Studies} We now apply the CVB approach to real-world datasets and compare it to CatBoost, LGBM, and Vanilla GBM. We examine a collection of datasets (see Tables \ref{regression_error} and \ref{classification_error}) which typically consists of categorical features with a relatively large number of categories. As opposed to Section \ref{simulation_studies}, we do not know the ``true" FI values in these real-world problems. Therefore, we focus our attention to datasets for which the studied methods disagree. It is important to emphasize that the examined datasets undergo a preprocessing stage which eliminates allegedly uninformative features (such as indexing, or different group membership indicators). These features typically cause severe FI inaccuracies in currently known methods, as opposed to our proposed framework (as demonstrated in Section \ref{simulation_studies}). We do not report these results for brevity, and only focus on the more insightful examples. We start with a comprehensive case study of the Amazon dataset\footnote{https://www.kaggle.com/c/amazon-employee-access-challenge}. \subsection{Amazon Dataset} The \textit{Amazon} dataset is a binary classification task where the purpose is to predict whether a specific employee should get access to a specific resource. The dataset contains $n = 32,769$ observations and $p = 9$ categorical variables, including \textit{Resource} - an ID for each resource (7518 categories), and \textit{Mgr\_id} - the manager ID of the employee (4243 categories). We begin our analysis by applying different GBM algorithms and corresponding FI measures (Figure \ref{amazon_fi}). The reported results are obtained by a 30-fold cross validation procedure, to attain statistically meaningful results. As we study the results we attain, we observe the following: \begin{enumerate} \item As in the simulation experiments, Vanilla GBM mostly utilizes high cardinality features and attains large values of FI for higher cardinality features (which appear on the left side of the plots). \item The \textit{Resource} variable attains a significantly large FI value in all methods besides CVB (in a significance level of 1\%). \item As we further study the \textit{Resource} variable, we observe that Vanilla GBM, LGBM, and CatBoost demonstrate a significant gap between the PFI on the train-set and the PFI on the test-set. Since both are in the same units, a gap in favor of the former suggests that this feature is quite dominant in the train-set, but has less effect on the test-set. This may suggest an over-fitted model. \end{enumerate} \begin{figure*}[t] \centering \fontsize{18}{28} \textbf{Amazon FI}\par\medskip \vspace*{-1.5mm} \hspace*{-1.75cm} \includegraphics[width= 15.5cm, height = 6.3cm]{plots/Amazon_Feature_Importance_2_3.png} \vspace*{-10mm} \caption{\textit{Scaled FI on the \textit{Amazon} dataset, across $30$ folds. Variables are ordered by their cardinality, from left to right, in descending order.}} \label{amazon_fi} \vspace*{5mm} \end{figure*} To validate the alleged over-fitting, we conduct the following experiment. We compare the prediction error of each GBM implementation with and without the \textit{Resource} variable. Figure \ref{amazon_error} illustrates the results we achieve. We observe that Vanilla GBM and LGBM perform better without the \textit{Resource} variable. CatBoost and CVB demonstrate quite similar results - while the median error in CatBoost is smaller than CVB, its variance is greater. In both cases it is not clear whether the \textit{Resource} variable contributes to the model performance. However, CVB is the only method that reflects it in its FI. Overall, we conclude that some implementations may rely on features in a different manner. For example, CVB does not rely on the \textit{Resource} variable while CatBoost does depend on it and may even benefit to its prediction accuracy. Finally, we observe that CVB FI methods are consistent and equal to each other. This means that even simple approaches as Gain FI perform well without the need for more complex FI methods. \begin{figure}[ht] \centering \fontsize{14}{28} \textbf{Error on Amazon}\par\medskip \hspace*{-5mm} \includegraphics[width =0.5\textwidth,bb= 5 0 520 480,clip]{plots/error_on_amazon_with_without_Resource} \caption{\textit{Error (log-loss) on the \textit{Amazon} dataset, across 30 folds, with and without the \textit{Resource} variable.}} \label{amazon_error} \end{figure} \subsection{Criteo CTR Dataset} The \textit{Criteo Click-Through Rate} (CTR) challenge\footnote{https://www.kaggle.com/c/criteo-display-ad-challenge} is a binary classification task where the goal is to predict whether a user clicks on an on-line ad. The dataset contains $n = 40,428,967$ observations and $p = 23$ categorical variables. Due to run-time considerations, we decrease the size of the dataset in the following manner. We randomly sample $30,000$ observations, such that half of them have a positive label and the others are negative (following \cite{he2009learning}). We remove the \textit{ID} feature which is unique identifier of each observation. We remain with $p = 22$ variables including: \textit{Device\_ip} (25,573 categories), \textit{Device\_id} (4,928 categories), \textit{Device\_model} (2,154 categories). We apply different GBM methods and obtain the corresponding FI measures. Figure \ref{criteo_fi} summarizes the results we obtain. We observe the following: \begin{figure*}[t] \centering \fontsize{18}{28} \textbf{Criteo CTR FI}\par\medskip \vspace*{-1.5mm} \hspace*{-1.75cm} \includegraphics[width= 15.5cm, height = 6.3cm]{plots/Criteo_CTR_Feature_Importance_2_3.png} \vspace*{-7mm} \caption{\textit{Scaled FI on the \textit{Criteo CTR} dataset, across $30$ folds. Variables are ordered by their cardinality, from left to right, in descending order. For visualisation, FI results for features with low cardinality that have small FI values are grouped.}} \label{criteo_fi} \end{figure*} \begin{enumerate} \item As in the previous experiment, Vanilla GBM is biased towards high categorical variables and over-fits the train-set with Gain and PFI on train data close to one for the \textit{Device\_ip} feature. \item The results for LGBM and CatBoost are quite similar and score high cardinality features with larger scores compared to CVB results. They also over-estimate high cardinality features with a relatively small difference between the PFI on train data and PFI on test data for high cardinality features. \item In LGBM, \textit{Device\_ip} attains a large SHAP value in contrast to other FI measures while in CatBoost SHAP FI is more consistent with other metrics, especially Gain and PFI on test data. As in the previous experiment, we examine whether CVB FI results are reliable by comparing the models error with and without a feature set. Figure \ref{criteo_error} demonstrates the results we achieve by comparing the set of all features to a the set of features CVB scores a positive FI. The results are quite similar to the \textit{Amazon} data-set experiment. \end{enumerate} \begin{figure}[ht] \centering \fontsize{14}{28} \textbf{Error on Criteo CTR}\par\medskip \centering \hspace*{-5mm} \includegraphics[width =0.5\textwidth,bb= 5 0 520 480,clip]{plots/Error_on_Criteo_with_without.png} \caption{\textit{Error (log-loss) on the \textit{Criteo dataset}, across 30 folds, with and without the following variables: \textit{Device\_ip, Device\_id, Device\_model}.}} \label{criteo_error} \end{figure} \subsection{Prediction Accuracy} Open-source implementations such as CatBoost and LGBM have many hyper-parameters that are tuned to obtain the best results in practice. Further, some implementations introduce different enhancements to the original GBM implementation to achieve a even better prediction accuracy as discussed in Section \ref{gbm_implementations}. Since improving the prediction accuracy is not the main focus of this study, we show that CVB is competitive with LGBM, CatBoost, and Vanilla GBM in a fixed hyper-parameters setting (number of trees = 100, learning rate = 0.1, maximum tree depth = 3). Table \ref{regression_error} summarizes the 10-fold mean RMSE of each algorithm on four different well-known datasets - \textit{Allstate claim severity}, \textit{Bike rentals}, \textit{Boston house pricing} and \textit{Kaggle house pricing} . Table \ref{classification_error} demonstrates the classification error over six classification datasets - \textit{Amazon} \textit{Breast cancer}, \textit{Don't get kicked}, \textit{Criteo CTR}, \textit{KDD upselling} and \textit{Adult}. In all of our experiments, CVB demonstrates competitive (and sometimes even superior) prediction accuracy to state-of-the-art methods. \begin{table} \centering \fontsize{12}{28} \textbf{Regression RMSE}\par\medskip \fontsize{9}{28} \begin{tabular}{|p{2.6cm}|p{1.5cm}|p{1.5cm}|p{1.5cm}|p{1.5cm}|} \hline Dataset & CVB & CatBoost & LGBM & Vanilla GBM\\ \hline \textit{Allstate}$^9$ & 0.3115 & 0.3242 & 0.3120 & 0.3123 \\ & (0.0036) & (0.0036) & (0.0038) & (0.0041)\\ \hline \textit{Bike Rentals}$^{10}$ & 0.2554 & 0.4484 & 0.2376 & 0.2470 \\ & (0.021) & (0.0415) & (0.0096) & (0.0173)\\ \hline \textit{Boston HP}$^9$ & 0.0276 & 0.0241 & 0.0238 & 0.0243 \\ & (0.0143) & (0.0102) & (0.0108) & (0.0115)\\ \hline \textit{Kaggle HP}$^9$ & 0.0185 & 0.0187 & 0.0162 & 0.0159 \\ & (0.0038) & (0.0042) & (0.0034) & (0.0034)\\ \hline\end{tabular} \vspace*{1mm} \caption{\textit{Mean and standard deviation of the RMSE across 10 folds. For visibility reasons we applied log transformation on the target. HP refers to \textit{house pricing}.}} \label{regression_error} \end{table} \vspace*{1cm} \begin{table}[ht] \centering \fontsize{12}{28} \textbf{Classification log-loss}\par\medskip \fontsize{9}{28} \begin{tabular}{|p{2.6cm}|p{1.5cm}|p{1.5cm}|p{1.5cm}|p{1.5cm}|} \hline Dataset&{CVB}&{CatBoost}&{LGBM}&{Vanilla GBM}\\ \hline KDD upselling$^8$& 0.1686 & 0.1681 & 0.1733 & 0.3416 \\ & (0.0074) & (0.0072) & (0.0071) & (0.0145) \\ \hline \textit{Amazon}$^9$ & 0.1716 & 0.1606 & 0.1724 & 0.2795 \\ & (0.0186) & (0.0216) & (0.0243) & (0.0355)\\ \hline \textit{Breast Cancer}$^{10}$ & 0.1091 & 0.0933 & 0.1080 & 0.1043\\ &(0.0872) & (0.0682) & (0.1008) & (0.1008)\\ \hline \textit{Don't Get Kicked}$^9$ & 0.3425 & 0.3433 & 0.3416 & 0.3584 \\ & (0.0064) & (0.0066) & (0.0071) & (0.0070)\\ \hline \textit{Criteo CTR} & 0.6161 & 0.6157 & 0.6241 & 0.9150 \\ & (0.0083) & (0.0095) & (0.0124) & (0.0376) \\ \hline \textit{Adult}$^{10}$ & 0.2982 & 0.3021 & 0.2892 & 0.2917 \\ & (0.0043) & (0.0095) & (0.0088) & (0.0038) \\ \hline\end{tabular} \vspace*{0.1mm} \caption{\textit{Mean and standard deviation of the log loss across 10 folds (30 on \textit{Amazon} and \textit{Criteo CTR}).}} \label{classification_error} \end{table} \newcommand\blfootnote[1]{% \begingroup \renewcommand\thefootnote{}\footnote{#1}% \addtocounter{footnote}{-1}% \endgroup } \blfootnote{$^8$https://www.kdd.org/kdd-cup/view/kdd-cup-2009/Data} \blfootnote{$^9$https://www.kaggle.com} \blfootnote{$^{10}$https://archive.ics.uci.edu/ml/datasets} \section{Discussion And Conclusion} \label{discussion} Although common implementations of GBM utilize biased decision trees, they typically perform quite well, and demonstrate high prediction accuracy. Unfortunately, their FI is shown to be biased. To overcome this basic limitation, we introduce a CVB framework which utilizes unbiased decision trees. We show that CVB attains unbiased FI while maintaining a competitive level of generalization abilities. Further, we show that FI is not model-agnostic or universal. In fact, it is a unique property of each GBM implementation; given a prediction task, two different implementations may introduce relatively the same error but much different FI scores. CVB is a naive, not optimized implementation of GBM. Our experiments show that even this simple implementation results in better FI and a competitive accuracy. One may wonder how an optimized version of CVB may perform. For example, it is interesting to examine more efficient validation schemes, and introduce state-of-the-art GBM enhancements to our current CVB implementation. For example, a future enhancement of CVB may consider stochastic GBM with feature selection using out-of-bag examples. Finally, CVB may also be applied to correct the bias in local FI measures. This would result in accurate local FI measure for personalization purposes. \section{Introduction} In recent years, machine learning (ML) has gained much popularity and became an integral part of our daily life. Current state-of-the-art algorithms are complex models which are difficult to interpret and rely on thousands, and even billions of parameters. Gaining insight into how these complex algorithms work is a key step towards better understanding our environment. Further, it is a crucial step for enabling ML algorithms to support and assist human decision making in complex fields (for example, as in medicine \citep{lundberg2018explainable}). FI is one of the basic tools for this purpose. The general FI framework scores input variables by their contribution to the predictive model, allowing us to gain insight into which features are important for this task. GBM \citep{friedman2001greedy} is an ensemble of base (weak) learners. These learners are typically standard implementations of tree-based models such are CART \citep{breiman1984classification}, C4.5 \citep{quinlan1986induction}, and others. GBM's are among the current state-of-the-art ML techniques on tabular data in a variety of tasks such as click prediction \citep{richardson2007predicting}, ranking \citep{burges2010ranknet} and others. Besides its accuracy, the GBM framework holds many virtues which makes it a favorable choice for many learning tasks. It is efficient, can handle categorical variables and deals with any kind of differential loss function. Further, it supports missing values and invariant to feature scaling. However, it is well known that GBM base learners are biased towards categorical variables with large cardinalities \citep{breiman1984classification}. As a consequence, ensemble methods that rely on such biased learners suffer from the same flaw \citep{strobl2007bias}. In this work we study the effect of base learners' bias on FI measures, in standard GBM implementations. We show that in the presence of categorical features with large alphabets, most FI measures are typically biased. This results in miss-interpreted models. To overcome this caveat, we utilize a cross-validated boosting (CVB) framework. CVB addresses the tree's bias through a simple modification: during the training stage of the tree, a variable is selected for splitting based on its cross-validated performance, rather than on its training sample performance (see \cite{painsky2016cross}, for example). This way, we conduct a ''fair” comparison between features, utilizing only high cardinality categorical features that show to be informative, in terms of their estimated generalization abilities. The rest of this manuscript is organized as follows, in Section \ref{Background} we review previous related work. In Section \ref{Formulation Of CVB} we formalize and define cross-validated boosting (CVB). Section \ref{Methods} outlines the experiment design in which we compare CVB to other GBM frameworks. In Section \ref{simulation_studies} we compare CVB to common open-source GBM implementations and show that CVB is the only algorithm that does not suffer from biased FI in high cardinality features through simulation studies. Finally, Section \ref{Real Data Case Studies} contains two comprehensive real data case studies, showing that CVB FI is more reliable than alternative schemes. We conclude the manuscript in Section \ref{discussion}. \section{Background} \label{Background} \subsection{Decision Trees} Decision trees are a long standing staple of predictive modeling. Popular tree building algorithms can handle both numerical and categorical variables, and build models for regression, binary and multi-class classification. Decision trees are built recursively to minimize a given loss function. At each step, the split which optimizes a given criterion is selected from all possible splits over on all variables. We hereby present the CART approach, which is one of the most widely used tree implementation in current GBM implementations. Let $\{x_i, y_i\}_{i=1}^{N}$ be a training set with $N$ samples , where $x_i \in \mathbb{R}^p, y_i \in \mathbb{R}$. The standard CART approach is a binary tree which utilizes either squared error loss impurity criterion (regression) or the Gini index (classification) to evaluate a possible split. At each internal node of a tree, a split $s$ is a partition of $n$ observations to two disjoint subsets $R(s)$ and $L(s)$. In regression tress, the squared error impurity criterion is defined as \begin{equation} \label{equation1} \mathcal{I}(s) = \Sigma_{i \in L(s)} (y_i - \bar{y}_L)^2 +\Sigma_{i \in R(s)} (y_i - \bar{y}_R)^2, \end{equation} where $\bar{y}_L, \bar{y}_R$ are the means of the response $y$ over the sets $L(s), R(s)$ respectively. The split gain (SG) is defined as the amount of decrease in impurity of the split: \begin{equation} \label{equation2} SG(s) = \Sigma_{i=1}^n (y_i - \bar{y})^2 - \mathcal{I}(s). \end{equation} At each node, CART examines all possible splits for each feature and selects the split with the minimum impurity (maximum gain). For each variable $j$, we denote the set of possible splits by $S_j$ and their cardinality by $|S_j|$. Let $K_j$ be the number of categories in a categorical feature $j$. For each numerical/ordinal variable, CART considers only splits along the sorted variable. Therefore, there are $|S_j| \leq n-1$ possible splits between its unique sorted values. For a categorical variable, there are $|S_j| = 2^{K_j -1}$ possible binary splits, but it is sufficient to sort the categories by their mean response value and search for splits along this axis \citep{breiman1984classification}, reducing the complexity to only $K_j-1$ splits. Without any regularization mechanism, terminal nodes are split and deep, complex trees are formed. Thus, stopping criteria are typically applied to prevent over-fitting and reduce tree complexity. Several common stopping criteria are the maximum tree depth, minimum samples to split, minimum samples leaf and minimum impurity decrease. It is also possible to grow a tree to its maximum depth and then to prune it, such as in minimal cost-complexity pruning \citep{breiman1984classification}. An additional commonly used decision tree implementation is C4.5 \citep{quinlan1986induction}. C4.5 considers K-way splits for categorical features (as opposed to binary splits in CART). C4.5 trees may be problematic for large cardinality categorical features as they result in splits with very few samples, and henceforth induce variance. Further, C4.5 trees are not used in recent GBM implementations. A comprehensive discussion on different splitting frameworks is provided in \citep{loh2014fifty}. \subsection{Gradient Boosting Trees} GBM is an ensemble model of $M$ regression trees, trained sequentially one after the other, in order to predict the previous trees' errors. GBM may be viewed as gradient descent in a functional space, where in each iteration of GBM, a tree is grown to estimate the gradient of the objective function. Let $F_m : \mathbb{R}^p \rightarrow \mathbb{R}$ be a predictive model at stage $m$, where $m = 1,....,M$. Let $\mathcal{L}(y_i,F_m(x_i))$ be a differentiable loss function. For example, $\mathcal{L}_{SE}(y_i,F_m(x_i))=(y_i-F_m(x_i))^2$ is the squared error loss in the standard regression case. GBM initializes with a constant model by estimating a parameter that minimizes the overall loss (for the squared error $F_0(x_i) = \bar{y}$). Then, at every iteration $m$, a regression decision tree $h_m$ is trained to minimize the empirical risk \begin{equation*} h_m = \operatorname*{argmin}_h \Sigma_{i=1}^N \mathcal{L}(y_i,F_{m-1}(x_i) + h(x_i)). \end{equation*} $h_m$ is obtained by fitting a regression tree to the gradients of each sample with respect to the current estimator at stage $m$. The optimal step size is calculated per each leaf by a line search. $h_m$ can be seen as the best greedy step in order to minimize the empirical risk. In order to reduce over-fitting, a learning-rate $\alpha$ is used and the model is updated, $F_m = F_{m-1} + \alpha h_m$. This process is repeated until $M$ trees are grown. Later, inspired by Breiman's bootstrap-aggregating (bagging) \citep{breiman1996bagging}, Friedman showed that a stochastic modification to GBM can substantially improve the prediction error of GBM \citep{friedman2002stochastic}. In its stochastic form, GBM fits each tree on a sub-sample of the training-set, sampled at random without replacement. \subsection{GBM Implementations} \label{gbm_implementations} There are many implementations of GBM in the literature. Many of these implementations follow Friedman's GBM, which is based on CART trees. In the age of big data, modern ML tasks require very large datasets. Therefore, the need for more scalable, distributed, GBM solutions arouse (such as \cite{tyree2011parallel}). This line of work mostly focuses on efficient implementation of GBM in distributed environments such as MapReduce \citep{condie2010mapreduce}. Here, the most notable implementation is XGBoost \citep{chen2016xgboost}. XGBoost has two main advantages. First, it unifies previous ideas of distributed computing with novel optimizations such as out-of-core-computation and sparsity-awareness. Thus, producing much lower run-time both on a single machine and in a distributed environment. Second, XGBoost introduces a new regularized learning objective which penalizes the complexity of the model. The result is a highly scaled end-to-end open-source implementation that produces state-of-the-art results, winning multiple data science open competitions. Unfortunately, the main drawback of the XGBoost framework is the lack of categorical variables support. Specifically, in order to utilize a categorical feature one needs to transform it to numeric variables such as in one-hot-encoding or to use \textit{term statistics}. One-hot-encoding is a valid method to transform categorical features to numeric ones, but in cases of high cardinality variables, it substantially increases the number of features and henceforth the execution time. \textit{Term statistics} is a method to transform a categorical feature to numeric by using the target value. Here, each category is replaced with its respective mean response value or a smoothed version of it \citep{prokhorenkova2018catboost}. The main problem with this approach is that it implies an order among the categories, and limits the expressive power of CART in categorical splits. Following XGBoost, Microsoft introduced LightGBM (LGBM) \citep{ke2017lightgbm}. LGBM is a faster implementation of GBM which supports categorical features. LGBM uses sampling techniques to exclude data instances with small gradients and \textit{exclusive feature bundling} to reduce the number of features tested to split at each node while achieving almost the same accuracy. More importantly, LGBM supports categorical features out-of-the-box and follows the original CART approach. Lately, CatBoost pushed the envelope of treating categorical features in GBM even further. CatBoost addresses a \textit{target leakage} (see \cite{prokhorenkova2018catboost}) to significantly improve the prediction error. For categorical variables, CatBoost uses ordered \textit{term statistics} and it is henceforth more memory efficient than LGBM. Further, CatBoost utilizes oblivious trees as base learners. Oblivious decision trees are decision trees for which all nodes at the same level use the same feature to split. These trees are balanced, less prone to over-fitting, and allow speeding up execution at testing time. Finally, CatBoost uses combinations of categorical features as additional categorical features to capture high-order dependencies between categorical features. \subsection{FI Methods} Understanding the decision-making mechanism of a ML algorithm is an important task in many applications. First, in several setups, attaining the best prediction is not our sole intent; we would like to know more about the problem and the data. Second, model interpretability is a key step for achieving and quantifying other desirable properties in artificial intelligence (AI) such as fairness, robustness, and causality \citep{doshi2017towards}. Finally, as AI enters new domains as health and transportation (autonomous vehicles), interpretation is essential to trust those mechanisms and adopt them as an integral part of our lives. While some ML algorithms are intrinsically interpretive (linear regression), they tend to be over-simplistic and generally suffer from a high bias. As modern ML evolves and computing power increases, complex algorithms are developed to attain superior prediction capabilities but in turn provide little interpretation. For this reason, many methods are developed to make these non-interpretable ML methods more understandable. These methods typically provide summary statistics for each variable, which can also be visualised for better understanding. Global FI measures attempt to summarise to which extent each feature is important for the prediction task. Given an algorithm, train and/or test data, a global FI method outputs a single number per each feature that reflects its importance. A local FI measure outputs a FI vector per each observation. Thus, it provides a more detailed, personalized FI. Local explanations are crucial in fields such as personalized medicine. For instance, local explanations can assist anesthesiologists to avoid hypoxemia during surgery, by providing real-time interpretable risks and contributing factors \citep{lundberg2018explainable}. Interaction FI are methods that measure the strength of the interaction between two features. A FI method is said to be model agnostic if it can be applied in the same manner for any ML algorithm. On the other hand, a FI measure is said to be model specific if it only applies for a specific algorithm \citep{molnar2020interpretable}. While FI aims to understand which features are important given a trained model, feature selection methods usually train a model several times in order to reduce dimensionality for speed considerations \citep{pan2009feature} or to avoid over-fitting in cases such as ''large-p small-n" tasks. While FI measures can be used as a means for variable selection by taking the most influential features, variable selection methods can not always be used as FI measures. For example, methods that rely on greedy backward elimination of features (such as \citep{kursa2010feature,gregorutti2017correlation}), still need to use a FI measure to score each variable in the final selected feature subset. \subsubsection{Global FI Methods} As mentioned above, global FI measures can be agnostic or model-specific. A global model-specific FI for GBM can be derived by evaluating its individual trees FI and averaging them across all trees in the ensemble \citep{friedman2001greedy}. Given a tree, there are many methods to interpret how important is a feature by inspecting the non-terminal nodes and their corresponding features which were used for splitting. The most prominent measures are: \begin{itemize} \item Split count - the number of times a feature is selected for a split in a tree. \item Cover - the number of observations in the training set that a node had split. Specifically, for every feature $j$, Cover is the total number of observations in splits that involve this feature. \item Gain or the decrease in impurity \citep{breiman1984classification} - for every feature $j$, Gain is the sum of SG (\ref{equation2}) that utilize this feature. \end{itemize} These measures are intuitive, simple and achieve a FI score that is often consistent with other FI measures at a low computational cost. Unfortunately, they are also extremely biased towards categorical variables with large cardinalities \citep{strobl2007bias}, as later described in Section \ref{fi_bias}. Among the model agnostic global FI methods, the Permutation FI (PFI) \citep{breiman2001random} is perhaps the most common approach. Its rationale is as follow. By randomly permuting the $j^{th}$ feature, its original association with the response variable is broken. Assume that the $j^{th}$ feature is associated with the outcome. As we apply the permuted feature, together with the remaining un-permuted features, to a given learning algorithm, the prediction accuracy is expected to substantially decrease. Thus, a reasonable measure for FI is the difference between the prediction error before and after permuting the variable. The PFI measure relies on random permutations which greatly varies. Unfortunately, to achieve a reliable estimate, it is required to conduct multiple permutations, which is computationally demanding. PFI can be calculated both on the train-set and on the test-set, where each approach has its advantages \citep{molnar2020interpretable}. The train-set can be used to estimate the amount of model reliance on each feature. However, model error based on train data is often too optimistic and does not reflect the generalization performance \citep{molnar2020interpretable}. Using the PFI on the test-set reflects the extent to which a feature contributes to the model on unseen data, but may not reflect cases where the model heavily relies on a feature (see Section \ref{simulation_studies}). A key problem with PFI is in cases where the dataset contains correlated features. Here, forcing a specific value of a feature may be misleading. For example, consider the case of two given features, \textit{Gender} and \textit{Pregnant}. Forcing the gender variable to be \textit{Male} might result in a pregnant male as a data point. Further, it was shown that correlated features tend to "benefit" from the presence of each other and thus their PFI tends to inflate \citep{nicodemus2010behaviour}. The leave one covariate out (LOCO) \citep{lei2018distribution} is another type of a model agnostic FI measure, which resembles in spirit to the PFI. LOCO evaluates the variable importance as the difference between the test-error of a model which was trained on all the data, and a model which is trained on all the data but the specified variable. Since training a model can be time consuming, this method may not be suitable in the presence of large data with many observations and features. Similarly to the PFI, LOCO may vary quite notably. Therefore, to obtain a reliable estimate, it is better to repeat this procedure a large number of times. Unfortunately, it substantially increases the execution time. Another popular global FI measure is the surrogate model. A global surrogate model trains an interpretable ML model in order to estimate the predictions of a black-box model. Then, the FI of the black-box model derived from the interpretable surrogate model. Finally, it is important to mention that global FI can also be obtained by averaging the results of local FI measure (see \ref{local_fi_measures} below) measures across observations. Specifically, a global FI of a feature is just the mean of the local FI for this variable, over all observations. \subsubsection{Local FI Methods} \label{local_fi_measures} Similarity to global FI, the local methods are also either model-specific or model-agnostic. The model-specific measures typically obtain a FI score for each tree, and average the scores along the ensemble. \cite{sabaas} was the first to propose a local FI for decision tree ensembles. Inspired by Gain FI, \cite{sabaas} evaluates the change of the expected value before and after a split in non-terminal nodes. To attain a model-agnostic local FI measure it is possible to utilize a local surrogate model. For example, \textit{local surrogate model interpretable model-Agnostic} (LIME) \citep{ribeiro2016should} was proposed to attain a FI for a specific observation by training an interpretable model in the proximity of this observation. Specifically, for each observation, LIME creates an artificial dataset and trains an interpretable model on this data. The observation FI is estimated as the global FI of the interpretable model. In \textit{SHapley Additive exPlanations} (SHAP) \cite{lundberg2017unified} unify surrogate models with ideas from cooperative game-theory by estimating the \textit{Shapely} value. The \textit{Shapely} value of each prediction is the average marginal contribution of a feature to the prediction over all possible feature subsets. The Shapely value has many theoretical guarantees and desirable properties. In general, obtaining the exact \textit{Shapely} value in a model agnostic scenario requires exponential time. Later, \cite{lundberg2018consistent} introduced an exact polynomial-time algorithm to compute the SHAP values for trees (TreeSHAP) and tree ensembles. Although theoretically promising, TreeSHAP can assign a non-zero value to features that have no influence on the prediction \citep{molnar2020interpretable}. Along the global and local FI methods, there are graphical approaches to further interpret the decision making principles of a black- box ML algorithhm \citep{molnar2020interpretable}. In this work, we focus on global FI measures since they are more popular, and demonstrate the bias of high cardinality categorical features most clearly and concisely. For the rest of the paper, and unless stated otherwise, global FI is referred to as FI. \subsection{Bias in Tree Based Algorithms} \label{fi_bias} It is well-known that decision trees are biased towards categorical features with many categories. The reason for this phenomenon is quite obvious. During the training process, a node is split according to the variable which minimizes the error on the train-set (\ref{equation2}). Since categorical features allow more possible splits than numerical ones, they are more likely to be selected for a split. For example an \textit{ID} feature, which consists of a unique category for each observation, would minimize the spitting criterion compared to any possible feature. Based on this observation, most contributions which aim to achieve an unbiased FI measure focus on eliminating the bias on the tree level \citep{strobl2007bias, painsky2016cross}. A variety of solutions to tree-bias were suggested over the years. The first line of work focuses on unbiased variable selection using hypothesis testing frameworks \citep{loh2002regression,kim2003classification,loh1997split}. For example, in QUEST \citep{loh1997split}, the authors test the association of each feature with the labels and choose the variable with the most significant p-value to split. For numerical features, the p-values are derived from an ANOVA F-statistics while in categorical features they are derived from a $\chi^2$ test. Later, Hothorn et al. generalized these methods by conditional inference trees (CIT), which utilizes nonparametric tests for the same purpose \citep{hothorn2006unbiased}. These approaches are built on a well defined statistical theory, which either assumes a-priori modeling assumptions on the distribution of the features \citep{loh1997split} or using permutation or nonparametric tests such as in CIT \citep{hothorn2006unbiased}. One of the main problems with these methods are the a-priori assumptions, which are not always reasonable. On the other hand, nonparametric statistical tests may be computationally demanding. When an ensemble of trees is sequentially built (as in GBM) this problem becomes more evident. Further, notice that the most ''informative" feature at each node is the one that splits the observations such that the generalization error (GE) is minimal. This is not necessarily the variable that achieves the smallest p-values under the null assumption \citep{painsky2016cross}. Thus, these methods may decrease the predictive performance of CART. For these reasons, a second line of work suggests ranking categorical features by their estimated GE. Ranking categorical features according to their GE was previously proposed for trees with k-way splits by \cite{sabato2008ranking} using Leave-One-Out (LOO) cross-validation \citep{frank1996selecting,frank1998using}. Recently, \cite{painsky2016cross} introduced \textit{adaptive LOO variable selection} (ALOOF) that is applicable for binary trees. ALOOF constructs an unbiased tree by conducting a ''fair" comparison between both numerical and categorical variables, using LOO estimates. This way, a large cardinality categorical feature is selected for a split if it proves to be effective on out-of-sample observations. \section{Formulation Of CVB} \label{Formulation Of CVB} CVB introduces a single modification to the original GBM framework. We hereby present the K-fold approach which is used in our CVB implementation. At the node selection phase, CVB selects the split based on cross-validation, and then splits it similarly to CART. Let $\mathcal{A}$ be the collection of all observations in a given node. We randomly divide the samples in $\mathcal{A}$ to $T$ equal sets of observations. Let $\{\mathcal{A}_t\}_{t=1}^T$ be the $T$ (non-overlapping) sets. For each set $\mathcal{A}_t$ we denote $\bar{\mathcal{A}}^t$ as the set of all observations that are not in $\mathcal{A}_t$. Specifically, $\bar{\mathcal{A}}^t = \mathcal{A} \setminus \mathcal{A}_t$. For every $t=1,\dots,T$, we find the optimal split over $\bar{\mathcal{A}}^t$, according to (\ref{equation1}). Then, we evaluate the permanence of the split on $\mathcal{A}_t$. The rank of the feature is the average performance over all $t=1,\dots,T$. We choose the split with the lowest rank and split it following CART's splitting rule. Notice that CVB is similar in spirit to \citep{painsky2016cross}, as it applies a K-fold CV to evaluate every possible split. A Python implementation of CVB is publicly available at Github\footnote{https://github.com/aba27059/unbiased\_fi\_for\_gb}. \subsection{CVB Stopping Criteria} Tree algorithms like CART require a stopping criterion to avoid over-complex models that typically overfit. In GBM, it is most common to restrict the tree depth rather than using pruning approaches for speed considerations. Another common regularization technique in trees is the minimum gain decrease as shown in (\ref{equation2}). If the gain of the best split is less than a predefined hyper-parameter, the tree branch stops to grow and becomes a leaf. Although using the minimum gain decrease is a valid method to avoid over-fitting, it is more difficult for humans to interpret, as it is measured in units that depend on the impurity criterion and change greatly from one dataset to the other. In CVB, a tree ceases to grow if the best estimated GE across all features is greater than the impurity before the split. The result is a built-in regularization mechanism, which resembles minimum gain decrease. In practice, it leads to more interpretable models; CVB demonstrates a significant reduction in the number of trees, as well as a reduction in the number of leaves. \section{Methods} \label{Methods} In the following sections we compare different FI measures in current GBM implementations on binary classification and regression tasks. We use GBM implementations that provide built-in categorical variables handling. Specifically, CatBoost, LGBM, and Friedman's GBM (Vanilla GBM). We leave XGBoost outside the scope of this paper as it requires either one-hot-encoding which results in unfeasible run-time on the studied problems. We use the following FI measures: Gain, PFI, and SHAP. Since SHAP is a local method, we derive its global FI\footnote{https://github.com/slundberg/shap}. It is important to emphasize that these FI measures are not (directly) integrated in some of the GBM implementations mentioned above. Specifically, CatBoost interface does not offer Gain FI nor node inspection data. Therefore, we use its Gain inspired default FI as in the official documentation\footnote{https://CatBoost.ai/docs/concepts/fstr.html}. Further, since SHAP FI official package has built-in integration for CatBoost and LGBM open-source implementations, we report it when possible or refer to its results in the Appendix. We set the following hyper-parameters across all our experiments (and for all the studied algorithms): maximum tree depth = $3$, number of base learners (number of trees) = $100$, learning rate (shrinkage) = $0.1$. We do not change other default hyper-parameters values and do not apply bagging (stochastic GBM). We focus on mean squared error (MSE) to measure the regression error and log-loss \citep{painsky2018universality} to measure the binary classification error. When evaluating PFI, we apply twenty permutations to estimate the decrease in model performance. On real datasets, we use K-fold cross-validation to compute error and FI metrics (with K = 30 unless stated otherwise). In CVB, for the node selection phase, we use $T = 5$. Throughout our experiments, we report the scaled FI. That is, we scale the FI values over all variables, so they sum to one\footnote{In some cases, the PFI can also be negative; we consider this case as zero importance.}. \section{Bias In Gradient Boosting FI} \label{simulation_studies} We start with a simple synthetic data experiment that demonstrates the FI bias in current GBM implementations. We follow the setup introduced by \cite{strobl2007bias}, which studied a binary classification task with five features. In their setup, X0 is a numeric feature which follows a standard normal distribution, and X1 to X4 are four categorical features which follow a uniform distribution over alphabet sizes 10, 20, 50 and 100 respectively. In our experiment, we draw $n=6000$ observations, train a GBM model and compare the corresponding FI measures. We repeat this experiment $100$ times and report the average merits. \subsection{Null Case} In the first experiment, which we refer to as the \textit{null case}, the target variable is independent of the features and follows a Bernoulli distribution with a parameter $p=0.5$. In this setup, none of the features are informative with respect to the response variable. Thus, a perfect FI measure shall score each feature a zero score. Figure \ref{null_exp} demonstrates the PFI and Gain FI results. The Gain FI \textit{(left)} illustrates the discussed bias in categorical variables. Specifically, we observe that categorical features with high cardinality tend to attain a greater FI than the rest, despite the fact that all features are not informative. In vanilla GBM and LGBM this phenomenon is more evident where $X3$ and $X4$ account together for almost $90\%$ of the overall FI whereas in CatBoost we observe a more subtle and monotone effect. CVB reliably recognizes uninformative features and scores zero importance for each feature. It is important to emphasize that although the reported scores are scaled, CVB attains zero FI scores. The reason lies on the standard convention, stating that if all scores are zero defined (which corresponds to stub trees), then their scaled score is zero as well. The right charts in Figure \ref{null_exp} demonstrate the PFI. Here, the mean FI of uninformative variables is around zero. This is not quite surprising, as the PFI is measured on the test-set. Nevertheless, we observe that features with high cardinality result in a greater variance than the rest, both in LGBM, Vanilla GBM, and CatBoost. CatBoost outperforms LGBM and Vanilla GBM and obtains around 10 times smaller FI for the uninformative variables. CVB outperforms CatBoost and again scores the uninformative features with zero importance. For LGBM and CatBoost, the SHAP FI (Appendix A) demonstrates the same monotonic behavior and scores similarly to the CatBoost Gain FI. Although in LGBM the slope is greater, CatBoost demonstrates a much greater variance. \begin{figure*}[t] \centering \fontsize{18}{28} \textbf{Simulation 1: \textit{null case}}\par\medskip \hspace*{-0.5cm} \includegraphics[width=13.5cm, height = 8cm]{plots/null_exp} \vspace*{-10mm} \caption{\textit{Scaled Gain FI (left) and PFI (right) for the \textit{null case} experiment where all displayed features are uninformative.}} \label{null_exp} \end{figure*} \subsection{Power Case} In the second experiment $Y$ depends on $X1$ in the following manner: \begin{equation} Y = \begin{cases} \text{Ber}(0.5 + \alpha) \text{, X1} \in \{0,1,2,3,4\} \\ \text{Ber}(0.5 - \alpha) \text{, X1} \in \{5,6,7,8,9\} \end{cases} \end{equation} where $\text{Ber}$ is a Bernoulli distribution and $\alpha$ is a predefined parameter. In this experiment, for $\alpha>0$, a perfect FI measure would assign a positive importance to $X1$ whereas the rest of the features shall attain zero importance. Figure \ref{power_exp} demonstrates the results we achieve for the uninformative features (all but $X1$) for the case where $\alpha = 0.2$. The Gain FI \textit{(left)} assigns only $37\%$ and $42\%$ FI to $X1$ for Vanilla GBM and LGBM where CatBoost performs better with $91\%$ FI for $X1$. CVB outperforms all the baseline schemes with $99.5\%$ FI assigned to the informative feature. As with the \textit{null case}, LGBM and Vanilla GBM over-fit the train-set in cases where high cardinality features are present, and attain a significantly greater FI for $X3$ and $X4$. In CatBoost, this phenomenon is considerably more subtle. Similarly to the \textit{null case}, the PFI \textit{(right)} variance increases with the category size, for all the algorithms besides CVB. CatBoost outperforms the baselines with a variance that is an order of magnitude smaller than LGBM and Vanilla LGBM. Let us now focus on the scaled PFI. LGBM and Vanilla GBM assigns $95.4\%$ importance for $X1$ whereas CatBoost assigns $99.4\%$ for it. CVB outperforms CatBoost and assigns $99.9\%$ FI for $X1$. Finally, SHAP FI (Appendix A) scores $55.3\%$ and $90.0\%$ FI for X1 in LGBM and CatBoost respectively. Following Strobel's study \citep{strobl2007bias}, we conclude that all GBM implementations exhibits FI bias to some extent. Specifically, Vanilla GBM and LGBM perform the worst and are highly prone to over-fit large cardinality categorical features. CatBoost is one scale better then the former, attaining a significantly smaller bias than its alternatives. Finally, CVB is superior even to CatBoost, and demonstrates a reliable FI measure with almost no bias. \begin{figure*}[t] \centering \fontsize{18}{28} \textbf{Simulation 2: \textit{power case}}\par\medskip \hspace*{-0.5cm} \includegraphics[width=13.5cm, height = 8.3cm]{plots/0.2_exp} \vspace*{-10mm} \caption{\textit{Scaled Gain FI (left) and PFI (right) for the \textit{power case} experiment where only $X1$ is informative. Since $X1$ is informative it is on a different scale and it is threfore omitted to improve visualization. Its mean values are $0.186$, $0.181$, $0.166$, $0.145$ for Vanilla GBM, LGBM, CatBoost and CVB respectively.}} \label{power_exp} \end{figure*} \section{Real Data Case Studies} \label{Real Data Case Studies} We now apply the CVB approach to real-world datasets and compare it to CatBoost, LGBM, and Vanilla GBM. We examine a collection of datasets (see Tables \ref{regression_error} and \ref{classification_error}) which typically consists of categorical features with a relatively large number of categories. As opposed to Section \ref{simulation_studies}, we do not know the ``true" FI values in these real-world problems. Therefore, we focus our attention to datasets for which the studied methods disagree. It is important to emphasize that the examined datasets undergo a preprocessing stage which eliminates allegedly uninformative features (such as indexing, or different group membership indicators). These features typically cause severe FI inaccuracies in currently known methods, as opposed to our proposed framework (as demonstrated in Section \ref{simulation_studies}). We do not report these results for brevity, and only focus on the more insightful examples. We start with a comprehensive case study of the Amazon dataset\footnote{https://www.kaggle.com/c/amazon-employee-access-challenge}. \subsection{Amazon Dataset} The \textit{Amazon} dataset is a binary classification task where the purpose is to predict whether a specific employee should get access to a specific resource. The dataset contains $n = 32,769$ observations and $p = 9$ categorical variables, including \textit{Resource} - an ID for each resource (7518 categories), and \textit{Mgr\_id} - the manager ID of the employee (4243 categories). We begin our analysis by applying different GBM algorithms and corresponding FI measures (Figure \ref{amazon_fi}). The reported results are obtained by a 30-fold cross validation procedure, to attain statistically meaningful results. As we study the results we attain, we observe the following: \begin{enumerate} \item As in the simulation experiments, Vanilla GBM mostly utilizes high cardinality features and attains large values of FI for higher cardinality features (which appear on the left side of the plots). \item The \textit{Resource} variable attains a significantly large FI value in all methods besides CVB (in a significance level of 1\%). \item As we further study the \textit{Resource} variable, we observe that Vanilla GBM, LGBM, and CatBoost demonstrate a significant gap between the PFI on the train-set and the PFI on the test-set. Since both are in the same units, a gap in favor of the former suggests that this feature is quite dominant in the train-set, but has less effect on the test-set. This may suggest an over-fitted model. \end{enumerate} \begin{figure*}[t] \centering \fontsize{18}{28} \textbf{Amazon FI}\par\medskip \vspace*{-1.5mm} \hspace*{-1.75cm} \includegraphics[width= 15.5cm, height = 6.3cm]{plots/Amazon_Feature_Importance_2_3.png} \vspace*{-10mm} \caption{\textit{Scaled FI on the \textit{Amazon} dataset, across $30$ folds. Variables are ordered by their cardinality, from left to right, in descending order.}} \label{amazon_fi} \vspace*{5mm} \end{figure*} To validate the alleged over-fitting, we conduct the following experiment. We compare the prediction error of each GBM implementation with and without the \textit{Resource} variable. Figure \ref{amazon_error} illustrates the results we achieve. We observe that Vanilla GBM and LGBM perform better without the \textit{Resource} variable. CatBoost and CVB demonstrate quite similar results - while the median error in CatBoost is smaller than CVB, its variance is greater. In both cases it is not clear whether the \textit{Resource} variable contributes to the model performance. However, CVB is the only method that reflects it in its FI. Overall, we conclude that some implementations may rely on features in a different manner. For example, CVB does not rely on the \textit{Resource} variable while CatBoost does depend on it and may even benefit to its prediction accuracy. Finally, we observe that CVB FI methods are consistent and equal to each other. This means that even simple approaches as Gain FI perform well without the need for more complex FI methods. \begin{figure}[ht] \centering \fontsize{14}{28} \textbf{Error on Amazon}\par\medskip \hspace*{-5mm} \includegraphics[width =0.5\textwidth,bb= 5 0 520 480,clip]{plots/error_on_amazon_with_without_Resource} \caption{\textit{Error (log-loss) on the \textit{Amazon} dataset, across 30 folds, with and without the \textit{Resource} variable.}} \label{amazon_error} \end{figure} \subsection{Criteo CTR Dataset} The \textit{Criteo Click-Through Rate} (CTR) challenge\footnote{https://www.kaggle.com/c/criteo-display-ad-challenge} is a binary classification task where the goal is to predict whether a user clicks on an on-line ad. The dataset contains $n = 40,428,967$ observations and $p = 23$ categorical variables. Due to run-time considerations, we decrease the size of the dataset in the following manner. We randomly sample $30,000$ observations, such that half of them have a positive label and the others are negative (following \cite{he2009learning}). We remove the \textit{ID} feature which is unique identifier of each observation. We remain with $p = 22$ variables including: \textit{Device\_ip} (25,573 categories), \textit{Device\_id} (4,928 categories), \textit{Device\_model} (2,154 categories). We apply different GBM methods and obtain the corresponding FI measures. Figure \ref{criteo_fi} summarizes the results we obtain. We observe the following: \begin{figure*}[t] \centering \fontsize{18}{28} \textbf{Criteo CTR FI}\par\medskip \vspace*{-1.5mm} \hspace*{-1.75cm} \includegraphics[width= 15.5cm, height = 6.3cm]{plots/Criteo_CTR_Feature_Importance_2_3.png} \vspace*{-7mm} \caption{\textit{Scaled FI on the \textit{Criteo CTR} dataset, across $30$ folds. Variables are ordered by their cardinality, from left to right, in descending order. For visualisation, FI results for features with low cardinality that have small FI values are grouped.}} \label{criteo_fi} \end{figure*} \begin{enumerate} \item As in the previous experiment, Vanilla GBM is biased towards high categorical variables and over-fits the train-set with Gain and PFI on train data close to one for the \textit{Device\_ip} feature. \item The results for LGBM and CatBoost are quite similar and score high cardinality features with larger scores compared to CVB results. They also over-estimate high cardinality features with a relatively small difference between the PFI on train data and PFI on test data for high cardinality features. \item In LGBM, \textit{Device\_ip} attains a large SHAP value in contrast to other FI measures while in CatBoost SHAP FI is more consistent with other metrics, especially Gain and PFI on test data. As in the previous experiment, we examine whether CVB FI results are reliable by comparing the models error with and without a feature set. Figure \ref{criteo_error} demonstrates the results we achieve by comparing the set of all features to a the set of features CVB scores a positive FI. The results are quite similar to the \textit{Amazon} data-set experiment. \end{enumerate} \begin{figure}[ht] \centering \fontsize{14}{28} \textbf{Error on Criteo CTR}\par\medskip \centering \hspace*{-5mm} \includegraphics[width =0.5\textwidth,bb= 5 0 520 480,clip]{plots/Error_on_Criteo_with_without.png} \caption{\textit{Error (log-loss) on the \textit{Criteo dataset}, across 30 folds, with and without the following variables: \textit{Device\_ip, Device\_id, Device\_model}.}} \label{criteo_error} \end{figure} \subsection{Prediction Accuracy} Open-source implementations such as CatBoost and LGBM have many hyper-parameters that are tuned to obtain the best results in practice. Further, some implementations introduce different enhancements to the original GBM implementation to achieve a even better prediction accuracy as discussed in Section \ref{gbm_implementations}. Since improving the prediction accuracy is not the main focus of this study, we show that CVB is competitive with LGBM, CatBoost, and Vanilla GBM in a fixed hyper-parameters setting (number of trees = 100, learning rate = 0.1, maximum tree depth = 3). Table \ref{regression_error} summarizes the 10-fold mean RMSE of each algorithm on four different well-known datasets - \textit{Allstate claim severity}, \textit{Bike rentals}, \textit{Boston house pricing} and \textit{Kaggle house pricing} . Table \ref{classification_error} demonstrates the classification error over six classification datasets - \textit{Amazon} \textit{Breast cancer}, \textit{Don't get kicked}, \textit{Criteo CTR}, \textit{KDD upselling} and \textit{Adult}. In all of our experiments, CVB demonstrates competitive (and sometimes even superior) prediction accuracy to state-of-the-art methods. \begin{table} \centering \fontsize{12}{28} \textbf{Regression RMSE}\par\medskip \fontsize{9}{28} \begin{tabular}{|p{2.6cm}|p{1.5cm}|p{1.5cm}|p{1.5cm}|p{1.5cm}|} \hline Dataset & CVB & CatBoost & LGBM & Vanilla GBM\\ \hline \textit{Allstate}$^9$ & 0.3115 & 0.3242 & 0.3120 & 0.3123 \\ & (0.0036) & (0.0036) & (0.0038) & (0.0041)\\ \hline \textit{Bike Rentals}$^{10}$ & 0.2554 & 0.4484 & 0.2376 & 0.2470 \\ & (0.021) & (0.0415) & (0.0096) & (0.0173)\\ \hline \textit{Boston HP}$^9$ & 0.0276 & 0.0241 & 0.0238 & 0.0243 \\ & (0.0143) & (0.0102) & (0.0108) & (0.0115)\\ \hline \textit{Kaggle HP}$^9$ & 0.0185 & 0.0187 & 0.0162 & 0.0159 \\ & (0.0038) & (0.0042) & (0.0034) & (0.0034)\\ \hline\end{tabular} \vspace*{1mm} \caption{\textit{Mean and standard deviation of the RMSE across 10 folds. For visibility reasons we applied log transformation on the target. HP refers to \textit{house pricing}.}} \label{regression_error} \end{table} \vspace*{1cm} \begin{table}[ht] \centering \fontsize{12}{28} \textbf{Classification log-loss}\par\medskip \fontsize{9}{28} \begin{tabular}{|p{2.6cm}|p{1.5cm}|p{1.5cm}|p{1.5cm}|p{1.5cm}|} \hline Dataset&{CVB}&{CatBoost}&{LGBM}&{Vanilla GBM}\\ \hline KDD upselling$^8$& 0.1686 & 0.1681 & 0.1733 & 0.3416 \\ & (0.0074) & (0.0072) & (0.0071) & (0.0145) \\ \hline \textit{Amazon}$^9$ & 0.1716 & 0.1606 & 0.1724 & 0.2795 \\ & (0.0186) & (0.0216) & (0.0243) & (0.0355)\\ \hline \textit{Breast Cancer}$^{10}$ & 0.1091 & 0.0933 & 0.1080 & 0.1043\\ &(0.0872) & (0.0682) & (0.1008) & (0.1008)\\ \hline \textit{Don't Get Kicked}$^9$ & 0.3425 & 0.3433 & 0.3416 & 0.3584 \\ & (0.0064) & (0.0066) & (0.0071) & (0.0070)\\ \hline \textit{Criteo CTR} & 0.6161 & 0.6157 & 0.6241 & 0.9150 \\ & (0.0083) & (0.0095) & (0.0124) & (0.0376) \\ \hline \textit{Adult}$^{10}$ & 0.2982 & 0.3021 & 0.2892 & 0.2917 \\ & (0.0043) & (0.0095) & (0.0088) & (0.0038) \\ \hline\end{tabular} \vspace*{0.1mm} \caption{\textit{Mean and standard deviation of the log loss across 10 folds (30 on \textit{Amazon} and \textit{Criteo CTR}).}} \label{classification_error} \end{table} \newcommand\blfootnote[1]{% \begingroup \renewcommand\thefootnote{}\footnote{#1}% \addtocounter{footnote}{-1}% \endgroup } \blfootnote{$^8$https://www.kdd.org/kdd-cup/view/kdd-cup-2009/Data} \blfootnote{$^9$https://www.kaggle.com} \blfootnote{$^{10}$https://archive.ics.uci.edu/ml/datasets} \section{Discussion And Conclusion} \label{discussion} Although common implementations of GBM utilize biased decision trees, they typically perform quite well, and demonstrate high prediction accuracy. Unfortunately, their FI is shown to be biased. To overcome this basic limitation, we introduce a CVB framework which utilizes unbiased decision trees. We show that CVB attains unbiased FI while maintaining a competitive level of generalization abilities. Further, we show that FI is not model-agnostic or universal. In fact, it is a unique property of each GBM implementation; given a prediction task, two different implementations may introduce relatively the same error but much different FI scores. CVB is a naive, not optimized implementation of GBM. Our experiments show that even this simple implementation results in better FI and a competitive accuracy. One may wonder how an optimized version of CVB may perform. For example, it is interesting to examine more efficient validation schemes, and introduce state-of-the-art GBM enhancements to our current CVB implementation. For example, a future enhancement of CVB may consider stochastic GBM with feature selection using out-of-bag examples. Finally, CVB may also be applied to correct the bias in local FI measures. This would result in accurate local FI measure for personalization purposes.
{'timestamp': '2021-09-14T02:20:52', 'yymm': '2109', 'arxiv_id': '2109.05468', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05468'}
arxiv
\section{Introduction} {\let\thefootnote\relax\footnote{Accepted as a long paper in EMNLP 2021 (Conference on Empirical Methods in Natural Language Processing).}} Relation extraction aims to detect the relation between two entities contained in a sentence, which is the cornerstone of various natural language processing (NLP) applications, including knowledge base enrichment \cite{trisedya-etal-2019-neural}, biomedical knowledge discovery \cite{DBLP:conf/ijcai/GuoN0C20}, and question answering \cite{DBLP:conf/ijcai/HanCW20}. Conventional neural methods \cite{miwa-bansal-2016-end, tran-etal-2019-relation} train a deep network through a large amount of labeled data with extensive relations, so that the model can recognize these relations during the test phase. Although impressive performance has been achieved, these methods are difficult to adapt to novel relations that have never been seen in the training process. In contrast, humans can identify new relations with very few examples. It is thus of great interest to enable the model to generalize to new relations with a handful of labeled instances. \begin{figure}[t!] \flushleft \includegraphics[width=\linewidth]{intro.pdf} \caption{An example of easy few-shot task (top) and hard few-shot task (bottom). This is a 3-way-1-shot setup -- each task involves three relations, and each relation has one supporting instance. Blue and red colors indicate head and tail entities respectively. For the easy task, the relations are very different, and it is easy to classify the query instance. However, due to the subtle differences among the relations in the hard tasks, it is challenging to correctly predict the true relation.} \label{intro} \end{figure} Inspired by the success of few-shot learning in the computer vision (CV) community \cite{DBLP:conf/cvpr/SungYZXTH18, DBLP:conf/iclr/SatorrasE18}, \citet{han-etal-2018-fewrel} first introduce the task of few-shot relation extraction (FSRE). {\color{black}FSRE requires models to be capable of handling classification of novel relations with scarce labeled instances. A popular framework for few-shot learning is meta-learning \cite{DBLP:conf/icml/SantoroBBWL16, DBLP:conf/nips/VinyalsBLKW16}, which optimizes the model through collections of few-shot tasks sampled from the external data containing disjoint relations with novel relations, so that the model can learn cross-task knowledge and use the knowledge to acclimate rapidly to new tasks.} A simple yet effective algorithm based on meta-learning is prototypical network \citep{DBLP:conf/nips/SnellSZ17}, aiming to learn a metric space in which a query instance is classified according to its distance to class prototypes. Recently, many works \cite{DBLP:conf/aaai/GaoH0S19, DBLP:conf/icml/QuGXT20, DBLP:conf/cikm/YangZDHHC20} for FSRE are in line with prototypical networks, which achieve remarkable performance. Nonetheless, the difficulty of distinguishing relations varies in different tasks \cite{DBLP:journals/corr/abs-2007-06240}, depending on the similarity between relations. As illustrated in Figure~\ref{intro}, there are easy few-shot tasks whose relations are quite different, so that they can be consistently well-classified, and also hard few-shot tasks with subtle inter-relation variations which are prone to misclassification. Current FSRE methods struggle with handling the hard tasks given limited labeled instances due to two main reasons. First, most works mainly focus on general tasks to learn generalized representations, and ignore modeling subtle and local differences of relations effectively, which may hinder these models from dealing with hard tasks well. Second, current meta-learning methods treat training tasks equally, which are randomly sampled and have different degrees of difficulty. The generated easy tasks can overwhelm the training process training and lead to a degenerate model. {\color{black}To fill this gap, this paper proposes a {\em {H}ybrid {C}ontrastive {R}elation-{P}rototype} (HCRP) approach, which focuses on improving the performance on hard FSRE tasks.} {\color{black}Concretely, we first propose a hybrid prototypical network, capable of capturing global and local features to generate the informative class prototypes.} Next, we present a novel relation-prototype contrastive learning method, which leverages relation descriptions as anchors, and pulls the prototype of the same class closer in representation space and pushes those of different classes away. In this way, the model gains diverse and discriminative prototype representations, which could be beneficial to distinguish the subtle difference of confusing relations in hard few-shot tasks. Furthermore, we design a task-adaptive training strategy based on focal loss \citep{DBLP:conf/iccv/LinGGHD17} to learn more from hard tasks, which allocates dynamic weights to different tasks according to task difficulty. Extensive experiments on two large-scale benchmarks show that our model significantly outperforms the baselines. Ablation and case studies demonstrate the effectiveness of the proposed modules. Our code is available at {\url{https://github.com/hanjiale/HCRP}} . The contributions of this paper are summarized as follows: \begin{itemize} \item {\color{black}We present HCRP to explore task difficulty as useful information for FSRE, which boosts hybrid prototypical network with relation-prototype contrastive learning to capture diverse and discriminative representations.} \item We design a novel task adaptive focal loss to focus training on hard tasks, which enables the model to achieve higher robustness and better performance. \item Qualitative and quantitative experiments on two FSRE benchmarks demonstrate the effectiveness of our model. \end{itemize} \section{Related Work} \subsection{Few-shot Relation Extraction} Relation extraction is a foundational and important task in NLP and attracts many recent attentions \cite{nan-etal-2020-reasoning, DBLP:journals/corr/abs-2104-07650}. Few-shot relation extraction aims to predict novel relations by exploring a few labeled instances. \citet{han-etal-2018-fewrel} first present a large-scale benchmark FewRel for FSRE. \citet{DBLP:conf/aaai/GaoH0S19} design a hybrid attention-based prototypical network to highlight the crucial instances and features. \citet{ye-ling-2019-multi} propose a prototypical network with multi-level matching and aggregation. \citet{sun-etal-2019-hierarchical} present a hierarchical attention prototypical network to enhance the representation ability of semantic space. \citet{DBLP:conf/icml/QuGXT20} utilize an external relation graph to study the relationships between different relations. \citet{wang-etal-2020-learning} apply added relative position information and syntactic relation information to enhance prototypical networks. \citet{DBLP:conf/cikm/YangZDHHC20} fuse text descriptions of relations and entities by a collaborative attention mechanism. And \citet{yang-etal-2021-entity} introduce the inherent concepts of entities to provide clues for relation classification. There are also some methods \cite{baldini-soares-etal-2019-matching, peng-etal-2020-learning} combining prototypical networks with pre-trained language models, which achieve impressive results. {\color{black}However, the task difficulty of FSRE has not been explored. In this work, we focus on the hard tasks and propose a hybrid contrastive relation-prototype method to better model subtle {\color{black}variations across different relations}.} \subsection{Contrastive Learning} \begin{figure*}[tbp!] \centering \includegraphics[width=0.8\textwidth]{model.pdf} \caption{The overall framework of HCRP. Best viewed in color. The rectangles represent the class prototypes, the circles represent the relations, and different colors represent different classes. } \label{framework} \end{figure*} Contrastive learning \cite{DBLP:journals/corr/abs-2011-00362} has gained popularity recently in the CV community. The core idea is to contrast the similarities and dissimilarities between data instances, which pulls the positives closer and pushes negatives away simultaneously. CPC \cite{DBLP:journals/corr/abs-1807-03748} proposes a universal unsupervised learning approach. MoCo \cite{DBLP:conf/cvpr/He0WXG20} presents a mechanism for building dynamic dictionaries for contrastive learning. SimCLR \cite{DBLP:conf/icml/ChenK0H20} improves contrastive learning by using larger batch size and data augmentation. \citet{DBLP:conf/nips/KhoslaTWSTIMLK20} extend the self-supervised contrastive approach to the supervised setting. \citet{Nan_2021_CVPR} propose a dual contrastive learning approach for video grounding. There are also some applications of contrastive learning in the field of NLP. \citet{DBLP:journals/corr/abs-2005-12766} employ back translation and MoCo to learn sentence-level representations. \citet{gunel2021supervised} design supervised contrastive learning for pre-trained language model fine-tuning. Inspired by these works, we propose a heterogeneous relation-prototype contrastive learning in a supervised way to obtain more discriminative representations. \section{Task Definition} {\color{black}We follow a typical few-shot task setting, namely the $N$-way-$K$-shot setup}, which contains a support set $\mathcal{S}$ and a query set $\mathcal{Q}$. The support set $\mathcal{S}$ includes $N$ novel classes, each with $K$ labeled instances. The query set $\mathcal{Q}$ contains the same $N$ classes as $\mathcal{S}$. And the task is evaluated on query set $\mathcal{Q}$, trying to predict the relations of instances in $\mathcal{Q}$. What's more, an auxiliary dataset $\mathcal{D}_{base}$ is given, which contains abundant base classes, each with a large number of labeled examples. Note the base classes and novel classes are disjoint with each other. The few-shot learner aims to acquire knowledge from base classes and use the knowledge to recognize novel classes. One popular approach is the meta-learning paradigm \cite{DBLP:conf/nips/VinyalsBLKW16}, which mimics the few-shot learning settings at training stage. Specifically, in each training iteration, we randomly select $N$ classes from base classes, each with $K$ instances to form a support set $\mathcal{S}=\{s_k^i; i=1, \dots , N, k=1, \dots , K\}$. Meanwhile, $R$ instances are sampled from the remaining data of the $N$ classes to construct a query set $\mathcal{Q}=\{q_j; j=1, \dots , R\}$. The model is optimized by collections of few-shot tasks sampled from base classes, so that it can rapidly adapt to new tasks. For an FSRE task, each instance consists of a set of samples $(x, e, y)$, where $x$ denotes a natural language sentence, $e=(e_{h}, e_{t})$ indicates a pair of head entity and tail entity, and $y$ is the relation label. The name and description for each relation are also provided as auxiliary support evidence for relation extraction. For example, for a relation with its relation id ``P726'' in a dataset that we use, we can obtain its name ``\textit{candidate}'' and description ``\textit{person or party that is an option for an office in an election}''. \section{Approach} In this section, we present the details of our proposed HCRP approach. The overall learning framework is illustrated in Figure~\ref{framework}. The inputs are $N$-way-$K$-shot tasks (sampled from the auxiliary dataset $\mathcal{D}_{base}$), where each task contains a support set $\mathcal{S}$ and a query set $\mathcal{Q}$. Meanwhile, we take the names and descriptions of these $N$ classes (i.e., relations) as inputs as well. {\color{black}HCRP consists of three components. The hybrid prototype learning module generates informative prototypes by capturing global and local features, which can better capture the subtle differences of relations. The relation-prototype contrastive learning component is then used to leverage the relation label information to further enhance the discriminative power of the prototype representations. Finally, a task adaptive focal loss is introduced to encourage the model to focus training on hard tasks.} \subsection{Hybrid Prototype Learning}\label{4.1} We employ BERT \cite{devlin-etal-2019-bert} as the encoder to obtain contextualized embeddings of query instances $\{\mathbf{Q}_j \in\mathbb{R}^{l_{q_j}\times d}; j=1, \dots , R\}$ and support instances $\{\mathbf{S}_k^i \in\mathbb{R}^{l_{s_k^i}\times d}; i=1, \dots , N, k=1, \dots , K\}$, {\color{black}where $l_{q_j}$ and $l_{s_k^i}$ are the sentence lengths of the $j$-th query instance and $k$-th support instance in class $i$ respectively}, and $d$ is the size of the resulting contextualized representations. For each relation, we concatenate the name and description and feed the sequence into the BERT encoder to obtain relation embeddings $\{\mathbf{R}^i \in\mathbb{R}^{l_{r^i}\times d}; i=1, \dots , N\}$, {\color{black}where $l_{r^i}$ is the length of relation description $i$}. \subsubsection*{Global Prototypes} For instances in $\mathcal{S}$ and $\mathcal{Q}$, the global features $\{\mathbf{s}_k^i \in\mathbb{R}^{2d}; i=1, \dots , N, k=1, \dots , K\}$ and $\{\mathbf{q}_j \in\mathbb{R}^{2d}; j=1, \dots , R\}$ are obtained by concatenating the hidden states corresponding to start tokens of two entity mentions following \citet{baldini-soares-etal-2019-matching}. The global features of relations $\{\mathbf{r}^i \in\mathbb{R}^{2d}; i=1, \dots , N\}$ are obtained by the hidden states corresponding to [\textit{CLS}] token (converted to $2d$ dimension with a transformation). For each relation $i$, we average the global features of the $K$ supporting instances {\color{black}following the work of \citet{DBLP:conf/nips/SnellSZ17}}, and further add the global feature of relation to form global prototype representation. \begin{equation} \mathbf{p}_g^i = \frac{1}{K}\sum_{k=1}^{K} \mathbf{s}_k^i + \mathbf{r}^i \in \mathbb{R}^{2d} \end{equation} \subsubsection*{Local Prototypes} {\color{black}While global prototypes are capable of capturing general data representations, such representations may not readily capture useful local information within specific RSRE tasks. To better handle the hard FSRE tasks with subtle differences among highly similar relations, we further propose local prototypes to highlight key tokens in an instance that are essential to {\color{black}characterize different relations}.} For relation $i$, we first calculate the local feature of the $k$-th support instance as: \begin{eqnarray} \hat{\mathbf{s}}_k^i &=& \sum_{n=1}^{l_{s_k^i}}\alpha^s_n {[\mathbf{S}_k^i]}_n \in \mathbb{R}^{d} \\ \alpha^s &=& {\rm softmax}({\rm sum}(\mathbf{S}_k^i{(\mathbf{R}^i)}^\mathsf{T})) \in \mathbb{R}^{l_{s_k^i}} \end{eqnarray} where ${[\cdot]}_n$ is the $n$-th row of a matrix, ${\rm sum}()$ is an operation that sums all elements for each row in a matrix. \begin{comment} {\color{purple}LW: need to add a few sentences to explain what's going on here. Also, explain why this can be interpreted as an attention mechanism, if you would like to call it that way (you used self-attention below).} \end{comment} {\color{black}Specifically, we allocate weights to different tokens according to their similarities with relation descriptions, and take the weighted sum to form such local features.} {\color{black} Similarly, we calculate the similarity between relation embedding $\mathbf{R}^i$ and each support instance embedding $\mathbf{S}_k^i$ of relation $i$ and obtain $K$ features $\{\hat{\mathbf{r}}_k^i; k=1, \dots , K\}$: \begin{eqnarray} \hat{\mathbf{r}}_k^i &=& \sum_{n=1}^{l_{r^i}}\alpha^r_n[\mathbf{R}^i]_{n} \in \mathbb{R}^{d} \\ \alpha^r &=& {\rm softmax}({\rm sum}(\mathbf{R}^i{(\mathbf{S}_k^n)}^\mathsf{T})) \in \mathbb{R}^{l_{r^i}} \end{eqnarray} The $K$ features are then averaged to arrive at the final local representation of relation $i$:} \begin{equation} \hat{\mathbf{r}}^i = \frac{1}{K}\sum_{k=1}^{K}\hat{\mathbf{r}}_k^i \in \mathbb{R}^{d} \end{equation} The local feature of a query instance is calculated by the following formulas. \begin{eqnarray} \hat{\mathbf{q}}_j &=& \sum_{n=1}^{l_{q_j}}\alpha^q_n {[\mathbf{Q}_j]}_n \in \mathbb{R}^{d} \\ \alpha^q &=& {\rm softmax}({\rm sum}(\mathbf{Q}_j\mathbf{Q}_j^\mathsf{T})) \in \mathbb{R}^{l_{q_j}} \end{eqnarray} Finally, we generate the local prototype by averaging the local features of the support set, plus the local feature of the relation. \begin{equation} \mathbf{p}_l^i = \frac{1}{K}\sum_{k=1}^{K} \hat{\mathbf{s}}_k^i + \hat{\mathbf{r}}^i \in \mathbb{R}^{d} \end{equation} \subsubsection*{Hybrid Prototypes} The model concatenates the global and local prototype to form hybrid prototype representations: \begin{equation} \mathbf{p}_h^i = [\mathbf{p}_g^i; \mathbf{p}_l^i]\in \mathbb{R}^{3d} \end{equation} where $[;]$ denotes column-wise concatenation. The hybrid representation of query instance is also obtained by concatenating the global and local features: \begin{equation} \mathbf{q}^j_h = [\mathbf{q}_j; \hat{\mathbf{q}}_j]\in \mathbb{R}^{3d} \end{equation} With the representation of query and prototypes of $N$ relations, the model computes the probability of the relations for the query instance $q_j$ as follows: \begin{equation} z(y=i|q_j) = \frac{\mathrm{exp}(\mathbf{q}^j_h \cdot \mathbf{p}_h^i)}{\sum_{n=1}^{N}\mathrm{exp}(\mathbf{q}^j_h \cdot \mathbf{p}_h^n)} \end{equation} \subsection{Relation-Prototype Contrastive Learning}\label{4.3} {\color{black}Hard tasks usually involve similar relations whose prototype representations are close, leading to increased challenges in classifying query instances.} To gain a more discriminative prototype representation, we design a novel Relation-Prototype Contrastive Learning (RPCL) method, which leverages the interpretable relation names and descriptions to calibrate the few-shot prototypes. Unlike conventional unsupervised or self-supervised contrastive learning, RPCL utilizes the labels of support instances in each task to {\color{black}perform supervised contrastive learning}. Concretely, taking a relation representation as an anchor, the prototype of the same class as positive and prototypes of different classes as negatives, RPCL aims to pull the positive closer with the anchor and pushes negatives away. For a specific relation $i$ with its hybrid representation, \begin{equation} \mathbf{r}^i_h = [\mathbf{r}^i;\hat{\mathbf{r}}^i]\in \mathbb{R}^{3d} \end{equation} the model collects positive prototype $\mathbf{p}_h^i$ and negative prototypes $\{\mathbf{p}_h^n; n=1, \dots ,N, n\neq i\}$. {\color{black}The goal is to distinguish the positive from the negatives}. We use dot product to measure the similarities between the relation anchor and selected prototypes. \begin{eqnarray} u^i_{pos} &=& \mathbf{p}_h^i \cdot \mathbf{r}^i_h \in \mathbb{R} \\ u^{i,n}_{neg} &=& \mathbf{p}_h^n \cdot \mathbf{r}^i_h \in \mathbb{R} \end{eqnarray} The contrastive loss is calculated by the following formula: \begin{comment} \begin{align} \mathcal{L}_C &= \sum_{i=1}^{N}\mathcal{L}_c^i \\ &=\sum_{i=1}^{N}-\mathrm{log} \frac{u^i_{pos}}{u^i_{pos} + {\rm sum}(u^i_{neg})} \end{align} \end{comment} \begin{align} \mathcal{L}_C &=\sum_{i=1}^{N}-\mathrm{log} \frac{u^i_{pos}}{u^i_{pos} + \sum_{n}u^{i,n}_{neg}} \end{align} \subsection{Task Adaptive Focal Loss}\label{4.4} We design a task adaptive focal loss to learn more from hard tasks, which is a modified cross entropy (CE) loss. The CE loss can be written as follows: \begin{equation} \mathcal{L}_{CE}=-\mathrm{log}(z_y) \end{equation} where $y$ is the class label, and $z_y$ is the estimated probability for the class $y$. The focal loss proposed by \citet{DBLP:conf/iccv/LinGGHD17} aims to solve the imbalance of hard examples and easy examples. \begin{equation} \mathcal{L}_{F}=-(1-z_y)^\gamma \mathrm{log}(z_y) \end{equation} where $\gamma \geq 0$ adjusts the rate at which easy examples are down-weighted. For an easy example, $z_y$ is almost 1, the factor goes to 0, and the loss for easy examples is down-weighted, which in turn increases the importance of correcting misclassified examples, {\color{black}which are potentially harder}. We employ focal loss instead of cross entropy loss to focus more on hard {query examples}. Moreover, to focus more on hard tasks, we design a novel {\em task adaptive focal loss}, which introduces the dynamic task-level weights. Specifically, for an $N$-way-$K$-shot task, the model calculates the class-wise similarity to estimate task difficulty. The higher the inter-class similarity, the harder the task. We first concatenate the hybrid features of prototype and relation to represent each class $\mathbf{c}^i=[\mathbf{r}^i_h;\mathbf{p}_h^i]$, \begin{comment} \begin{equation} \mathbf{c}^i=[\mathbf{r}^i_h;\mathbf{p}_h^i]\in \mathbb{R}^{6d} \end{equation} \end{comment} and then define the task similarity matrix $\mathbf{S}^{\tau}\in \mathbb{R}^{N\times N}$, for $i, j \in \{1, \dots , N\}$, \begin{equation} \mathbf{s}^{\tau}_{ij}=\frac{\mathbf{c}^i \cdot \mathbf{c}^j}{||\mathbf{c}^i|| \times ||\mathbf{c}^j||} \end{equation} where $||\cdot||$ is the Euclidean norm. The task similarity scalar is obtained by the following formula: \begin{equation} s^{\tau}=\frac{\mathrm{exp}(||\mathbf{S}^{\tau}||_\mathrm{F})}{\sum_{\tau^{'}=1}^{\mathcal{T}}\mathrm{exp}(||\mathbf{S}^{\tau^{'}}||_\mathrm{F})} \end{equation} where $||\cdot||_\mathrm{F}$ is the Frobenius norm, and $\mathcal{T}$ is the {\color{black}number of tasks} in a mini-batch. The scalar represents the degree of difficulty of the task. We add the task-level scalar to the focal loss, which not only focuses on the hard examples at the instance level, but also focuses more on the hard tasks at the task level. Formally, the task adaptive focal loss is defined as follows, \begin{equation} \mathcal{L}_{TF}=-s^{\tau}(1-z_y)^\gamma \mathrm{log}(z_y) \end{equation} The final objective function of our model is defined as $\mathcal{L}=\mathcal{L}_{TF} + \lambda\times\mathcal{L}_{C} $, where $\lambda$ is a hyper-parameter to balance the two terms. \section{Experiments} \subsection{Experimental Setup} \subsubsection{Datasets} We evaluate our model on FewRel 1.0 \cite{han-etal-2018-fewrel} and FewRel 2.0 \cite{gao-etal-2019-fewrel}. FewRel 1.0 and FewRel 2.0 are large-scale few-shot relation extraction datasets, consisting of 100 relations, each with 700 labeled instances. The average number of tokens in each sentence instance is 24.99, and there are 124,577 unique tokens in total. Our experiments follow the splits used in official benchmarks, which split the dataset into 64 base classes for training, 16 classes for validation, and 20 novel classes for testing. FewRel 1.0 is trained and tested on the same Wikipedia domain. In addition, the name and description of each relation are also given, providing additional interpretability for each relation. {\color{black}FewRel 2.0 with domain adaptation setting is trained on Wikipedia domain but tested on a different biomedical domain. Only the names of relation labels are given but descriptions are not available, which makes the task more challenging.} \begin{table}[t!] \centering \scalebox{0.8}{ \begin{tabular}{ccc} \toprule Component & Parameter & Value\\ \midrule \multirow{3}*{BERT} & type & base-uncased \\ &hidden size&$768$\\ &max length & $128$ \\ \midrule \multirow{3}*{Training} & learning rate & $2e-5$ \\ &batch size& $4$\\ &max iterations&$30,000$\\ \midrule \multirow{2}*{Loss} &$\lambda$&$1$ / $2.5$\\ &$\gamma$&1\\ \bottomrule \end{tabular} } \caption{\label{hyper-parameters}Hyper-parameters (FewRel 1.0 / 2.0) of our approach. } \end{table} \subsubsection{Evaluation}\label{5.1.2} Consistent with the official evaluation scripts, we evaluate our model by randomly sampling 10,000 tasks from validation data. The performance of the model is evaluated as the averaged accuracy on the query set of multiple $N$-way-$K$-shot tasks. According to the previous work \cite{han-etal-2018-fewrel, gao-etal-2019-fewrel}, we choose $N$ to be 5 and 10, and $K$ to be 1 and 5 to form 4 scenarios. {\color{black}We report the final test accuracy by submitting the prediction of our model to the FewRel leaderboard\footnote[2]{\url{https://thunlp.github.io/fewrel.html}}.} \subsubsection{Implementation Details} The approach is implemented with PyTorch \cite{DBLP:conf/nips/PaszkeGMLBCKLGA19} and trained on 1 Tesla P40 GPU. We adopt the Transformer library of Huggingface\footnote[3]{\url{https://github.com/huggingface/transformers}} \cite{wolf-etal-2020-transformers} and take the uncased model of BERT$_{base}$ as the encoder for fair comparison. The AdamW optimizer \cite{DBLP:conf/iclr/LoshchilovH19} is applied to minimize loss. {\color{black}We manually adjust the hyper-parameters based on the performance on the validation data, which are listed in Table~\ref{hyper-parameters}.} Specifically, we use the same hyper-parameter values for two datasets except for $\lambda$. For FewRel 1.0, we concatenate the name and description of each relation as inputs, and $\lambda$ is set to 1. For FewRel 2.0, we only input the relation names, and $\lambda$ is adjusted to 2.5. The number of parameters in our model is 110 million. The average runtime of training and evaluation under 10-way-1-shot setting is 13.35 hours and 1.25 hours, respectively. {\color{black}\subsection{Results and Discussion} \subsubsection{{\color{black}Comparison to Baselines}}\label{5.2.1}} \begin{table*}[th] \centering \scalebox{0.8}{ \begin{tabular}{clcccc} \toprule Encoder & Model&5-way-1-shot&5-way-5-shot&10-way-1-shot&10-way-5-shot\\ \midrule \multirow{3}*{\rotatebox{90}{CNN}} &Proto-CNN$^\clubsuit$ \citep{DBLP:conf/nips/SnellSZ17} &72.65 / 74.52 &86.15 / 88.40 &60.13 / 62.38 &76.20 / 80.45 \\ &Proto-HATT \citep{DBLP:conf/aaai/GaoH0S19} &75.01 / --- --- & 87.09 / 90.12 &62.48 / --- ---&77.50 / 83.05 \\ &MLMAN \cite{ye-ling-2019-multi} &79.01 / 82.98 & 88.86 / 92.66 &67.37 / 75.59&80.07 / 87.29 \\ \midrule \multirow{11}*{\rotatebox{90}{BERT}} &Proto-BERT$^\ast$ \citep{DBLP:conf/nips/SnellSZ17} &82.92 / 80.68 &91.32 / 89.60 &73.24 / 71.48 &83.68 / 82.89 \\ &MAML$^\ast$ \cite{DBLP:conf/icml/FinnAL17} &82.93 / 89.70 & 86.21 / 93.55 &73.20 / 83.17&76.06 / 88.51 \\ &GNN$^\ast$ \cite{DBLP:conf/iclr/SatorrasE18} &--- --- / 75.66 & --- --- / 89.06 &--- --- / 70.08&--- --- / 76.93 \\ &BERT-PAIR$^\clubsuit$ \cite{gao-etal-2019-fewrel} &85.66 / 88.32 & 89.48 / 93.22 &76.84 / 80.63&81.76 / 87.02 \\ &REGRAB \cite{DBLP:conf/icml/QuGXT20} & 87.95 / 90.30 & 92.54 / 94.25 &80.26 / 84.09&86.72 / 89.93 \\ &TD-Proto \cite{DBLP:conf/cikm/YangZDHHC20} & --- --- / 84.76 & --- --- / 92.38 &--- --- / 74.32& --- --- / 85.92 \\ &CTEG \cite{wang-etal-2020-learning} &84.72 / 88.11 & 92.52 / 95.25 &76.01 / 81.29&84.89 / 91.33 \\ &\textbf{HCRP (ours)} &\textbf{90.90} / \textbf{93.76} & \textbf{93.22} / \textbf{95.66} &\textbf{84.11} / \textbf{89.95} & \textbf{87.79} / \textbf{92.10} \\ \cline{2-6} &MTB$^\star$ \cite{baldini-soares-etal-2019-matching} &--- --- / 91.10 & --- --- / 95.40 &--- --- / 84.30&--- --- / 91.80 \\ &CP$^\star$ \cite{peng-etal-2020-learning}&--- --- / 95.10 & --- --- / 97.10 &--- --- / 91.20&--- --- / 94.70 \\ &\textbf{HCPR+CP} & \textbf{94.10} / \textbf{96.42} & \textbf{96.05} / \textbf{97.96}& \textbf{89.13} / \textbf{93.97} & \textbf{93.10} / \textbf{96.46} \\ \bottomrule \end{tabular} } \caption{Accuracy (\%) of few-shot classification on the FewRel 1.0 validation / test set. $\clubsuit$ are from FewRel public leaderboard\footnotemark[2], $\ast$ are reported by \citet{DBLP:conf/icml/QuGXT20}, and $\star$ are reported by \citet{peng-etal-2020-learning}. {\color{black}Our method introduces additional relation label name and description information, which is the same as TD-Proto. Other baseline methods also use different external knowledge. See Section~\ref{5.2.1} for details.}} \label{main-fewrel1} \end{table*} \begin{table} \centering \renewcommand\tabcolsep{3.6pt} \scalebox{0.8}{ \begin{tabular}{lcccc} \toprule \multirow{2}*{Model} &5-way&5-way&10-way& 10-way\\ &1-shot&5-shot&1-shot& 5-shot\\ \midrule Proto-CNN &35.09 &49.37 &22.98 &35.22 \\ Proto-BERT &40.12 & 51.50 &26.45 &36.93 \\ Proto-ADV & 42.21 & 58.71 &28.91&44.35 \\ BERT-PAIR &67.41 & 78.57&54.89&66.85 \\ HCRP (ours) & \textbf{76.34} &\textbf{83.03} & \textbf{63.77}&\textbf{72.94} \\ \bottomrule \end{tabular} } \caption{Accuracy (\%) of few-shot classification on the FewRel 2.0 domain adaptation test set. All results of baselines are quoted from FewRel leaderboard\footnotemark[2].} \label{main-fewrel2} \end{table} We compare our model with the following baseline methods: 1) \textbf{Proto} \cite{DBLP:conf/nips/SnellSZ17}, the algorithm of prototypical networks. We employ CNN and BERT as encoder separately (\textbf{Proto-CNN} and \textbf{Proto-BERT}), and combine adversarial training (\textbf{Proto-ADV}) for FewRel 2.0 domain adaptation. 2) \textbf{MAML} \cite{DBLP:conf/icml/FinnAL17}, the model-agnostic meta-learning algorithm. 3) \textbf{GNN} \cite{DBLP:conf/iclr/SatorrasE18}, a meta-learning approach using graph neural networks. 4) \textbf{Proto-HATT} \cite{DBLP:conf/aaai/GaoH0S19}, prototypical networks modified with hybrid attention to focus on the crucial instances and features. 5) \textbf{MLMAN} \cite{ye-ling-2019-multi}, a multi-level matching and aggregation prototypical network. 6) \textbf{BERT-PAIR} \cite{gao-etal-2019-fewrel}, a method that measures similarity of sentence pair. 7) \textbf{REGRAB} \cite{DBLP:conf/icml/QuGXT20}, a Bayesian meta-learning method with an external global relation graph. 8) \textbf{TD-Proto} \cite{DBLP:conf/cikm/YangZDHHC20}, enhancing prototypical network with both relation and entity descriptions. 9) \textbf{CTEG} \cite{wang-etal-2020-learning}, a model that learns to decouple high co-occurrence relations, where two external information are added. Moreover, we compare our model with two pre-trained RE methods: 10) \textbf{MTB} \cite{baldini-soares-etal-2019-matching}, pre-train with their proposed matching the blank task on top of an existing BERT model. {\color{black}11) \textbf{CP} \cite{peng-etal-2020-learning}, an entity-masked contrastive pre-training framework for RE. They first construct a large-scale dataset from Wikidata for pre-training, which contains 744 relations and 867,278 sentences. They then continue pre-training an existing BERT model on such a new dataset, and fine-tune on the FewRel data based on prototypical networks, achieving high accuracy.} Note we do not adopt the results in \citet{baldini-soares-etal-2019-matching} because of their BERT$_{large}$ backbone employed. Here we report the experimental results produced by the work of \citet{peng-etal-2020-learning} which is based on BERT$_{base}$ as the encoder for fair comparison. Table~\ref{main-fewrel1} presents the experimental results on FewRel 1.0 validation set and test set. As shown in the upper part of Table~\ref{main-fewrel1}, our method outperforms the strong baseline models by a large margin, especially in 1-shot scenarios. Specifically, we improve 5-way-1-shot and 10-way-1-shot tasks 3.46 points and 5.86 points in terms of accuracy respectively compared to the second best method, demonstrating the superior generalization ability. Our method also achieves the best performance on FewRel 2.0, as shown in Table~\ref{main-fewrel2}, which proves the stability and effectiveness of our model. The performance gain mainly comes from three aspects. (1) The hybrid prototypical networks capture rich and subtle features. (2) The relation-prototype contrastive learning leverages the relation text to further gain discriminative prototypes. (3) The task-adaptive focal loss forces model to learn more from hard few-shot tasks. In addition, we evaluate our approach based on the model CP, where the BERT encoder is initialized with their pre-trained parameters\footnote[4]{\url{https://github.com/thunlp/RE-Context-or-Names}}. The lower part of Table~\ref{main-fewrel1} shows that our approach achieves a consistent performance boost when using their pre-trained model, which demonstrates the effectiveness of our method, and also indicates the importance of good representations for few-shot tasks. \subsubsection{Performance on Hard Few-shot Tasks}\label{5.3} To further illustrate the effectiveness of the developed method, especially for hard FSRE tasks, we evaluate the models on FewRel 1.0 validation set with three different 3-way-1-shot settings, as shown in Table~\ref{fg-fewrel}. \textit{Random} is the general evaluation setting, which samples 10,000 test tasks randomly from validation relations, as detailed in section~\ref{5.1.2}. \textit{Easy} represents the evaluated tasks are easy. We fix the 3 relations in each task as 3 very different relations, which are ``\textit{crosses}'', ``\textit{constellation}'', and ``\textit{military rank}''. Different tasks own different instances but the same relations. Similarly, we pick 3 similar relations, which are ``\textit{mother}'', ``\textit{child}'', and ``\textit{spouse}'' respectively, and evaluate the performance of models under the \textit{Hard} setting. As we can see, the baselines achieve good performance under random and easy settings. However, the accuracy has dropped significantly under the hard setting, which illustrates that hard few-shot tasks are extremely challenging. HCRP gains the best accuracy, especially under the hard setting, proving that our model can effectively handle hard few-shot tasks. \subsubsection{Analysis of Hybrid Prototype Learning} \begin{table} \centering \renewcommand\tabcolsep{9pt} \scalebox{0.8}{ \begin{tabular}{lccc} \toprule Model &Random &Easy&Hard\\ \midrule Proto-HATT & 83.96 & 94.62& 35.54 \\ MLMAN & 86.37 & 97.30 & 34.45\\ Proto-BERT &87.37 & 98.51 &35.63\\ BERT-PAIR & 91.14 &99.76 & 38.21\\ HCRP (ours) & \textbf{93.86}&\textbf{99.93} &\textbf{62.40} \\ \bottomrule \end{tabular} } \caption{Accuracy (\%) of 3-way-1-shot scenarios on FewRel 1.0 validation set. Three different settings are designed to illustrate the performance under random, easy, and hard settings.} \label{fg-fewrel} \end{table} This section discusses the effect of hybrid prototype learning. As shown in the Table~\ref{ablation}, we conduct an ablation study to verify the effectiveness of hybrid prototypes. Removing local (Model 2) and global prototypes (Model 3) decreases the performance respectively, {\color{black}indicating that both prototypes are essential to represent relations.} Furthermore, we present a 3-way-1-shot task sampled from the FewRel 1.0 validation set, as shown in Table~\ref{case}. The task can be regarded as a hard task because the three relations are highly similar. Our model correctly classifies the query instance as ``\textit{mother}''. We visualize the similarity between the query instance and different relation prototypes, where different columns represent different models. Proto-BERT and HCRP without global prototypes tend to classify the query into the wrong relation ``\textit{child}''. {\color{black}HCRP without local prototypes can correctly predict the relation ``\textit{mother}''. HCRP further correctly predicts with a higher degree of confidence, which proves that hybrid prototypes can better model subtle inter-relation variations for hard tasks.} \subsubsection{Analysis of Relation-Prototype Contrastive Learning} \begin{table}[t!] \centering \scalebox{0.8}{ \begin{tabularx}{\columnwidth}{X} \toprule Support Set\\ \midrule \textit{\textbf{mother} | female parent of the subject} \\ He was the third son of Yang Jian and {\color{red} Dugu Qieluo}, after Yang Yong and {\color{blue} Yang Guang}.\\ \midrule \textit{\textbf{child} | subject has object as biological, foster, and/or adoptive child} \\ He was a son of {\color{blue} Margrethe Rode}, and a brother of writer {\color{red} Helge Rode}. \\ \midrule \textit{\textbf{spouse} | the subject has the object as their spouse (husband, wife, partner, etc.)}\\ He is the son of Canadian Olympic figure skaters {\color{blue} Don Fraser} and {\color{red} Candace Jones}. \\ \midrule Query Instance\\ \midrule He is the eldest son of actor and director Leo Penn and actress {\color{red} Eileen Ryan}, and the brother of actors Sean Penn and {\color{blue} Chris Penn}.\\ \multicolumn{1}{c}{$\includegraphics{attheatmap.pdf}$}\\ \bottomrule \end{tabularx} } \caption{A real example of 3-way-1-shot hard task. We list the detailed relation names and descriptions, as well as instances. The picture visualizes similarities between the query instance and different prototypes of relations, where different columns represent different models. Best viewed in color. A darker unit indicates a higher value.} \label{case} \end{table} To demonstrate the effectiveness of relation-prototype contrastive learning (RPCL), we first conduct the ablation study, shown in model 4 of Table~\ref{ablation}. It is clear that there is a severe decline in performance if removing the relation-prototype contrastive learning in 5-way-1-shot and 10-way-1-shot settings. {\color{black}As Figure~\ref{tsne} depicts, we visualize the learned embedding spaces with t-SNE \cite{maaten2008visualizing} to intuitively characterize the resulting representations for similar relations. }Specifically, we pick two similar relations ``\textit{mother}'' and ``\textit{child}'' from the FewRel 1.0 validation set, and randomly sample 100 instances for each relation. {\color{black}We can see that embeddings trained with RPCL are clearly separated, which makes classification easier, while those trained without RPCL are lumped together.} By using the relation-prototype contrastive learning, which regards the relation text as anchors and hybrid prototypes as positives and negatives, {\color{black}our model arrives at more discriminative representations, especially for hard tasks.} \subsubsection{Analysis of Task-Adaptive Focal Loss} \begin{comment} \begin{figure}[t!] \flushleft \includegraphics[width=\linewidth]{Figure/attheatmap.pdf} \caption{Similarity visualization between the query instance and different prototypes of relations, where different columns represent different models. The darker units have larger value. The detailed task is shown in Table~\ref{case}. } \label{attheatmap} \end{figure} \end{comment} \begin{table*}[t!] \centering \renewcommand\tabcolsep{5pt} \scalebox{0.8}{ \begin{tabular}{clcl} \toprule Tasks&Relations & \multicolumn{2}{c}{Weights} \\ \midrule task 1 &performer, director, characters, composer, publisher &0.29 & \multirow{4}*{$\includegraphics[width=0.03\linewidth, height=0.22\columnwidth]{taskweight.pdf}$}\\ task 2 &performer, has part, location, father, platform, religion &0.19 &\\ task 3 &located on terrain feature, location of formation, country, work location, location &0.30 & \\ task 4 &has part, instrument, operating system, military branch, successful candidate &0.22& \\ \bottomrule \end{tabular} } \caption{An example of a 4-task batch and the task-adaptive weights, where each task has 5 relations ($N$=5).} \label{task_weight} \end{table*} \begin{table}[t!] \centering \renewcommand\tabcolsep{3.6pt} \scalebox{0.8}{ \begin{tabular}{lccc} \toprule \multirow{2}*{Model} &\multirow{2}*{No.}&5-way&10-way\\ &&1-shot&1-shot\\ \midrule HCRP &1&\textbf{90.90} & \textbf{84.11} \\ \midrule w/o local prototype &2&88.37 &82.31 \\ w/o global prototype &3&86.42 & 77.86\\ \midrule w/o RPCL &4&87.85 & 79.76\\ \midrule CE loss &5&88.96 &82.75 \\ CE loss with task weights &6& 89.38 & 83.11\\ focal loss &7& 89.51 &83.54 \\ \bottomrule \end{tabular} } \caption{Ablation study on FewRel 1.0 validation set showing accuracy (\%).} \label{ablation} \end{table} As shown in Table~\ref{ablation}, we compare our designed task adaptive focal loss with cross entropy (CE) loss (Model 5), cross entropy loss with task weights (Model 6), and focal loss (Model 7). Comparing Model 5 and Model 7, we observe that focal loss achieves higher accuracy than CE loss, and adding the task adaptive weight (Model 1) further improves the performance. In addition, experiments show that the CE loss with task weights also improves performance compared to CE loss. Table~\ref{task_weight} depicts a case study to show the task-adaptive weights. Specifically, we give a sampled mini-batch of tasks from the FewRel 1.0 training set, where the batch size is 4. Each task has 5 relations, which are also listed. The model allocates weights for each task according to the similarity of support set. For example, the relations in task 1 are similar to each other, mainly describing the relations in the art field, so the model assigns a relatively higher task weight. However, the relations in task 2 are very different, so the model allocates a lower weight. The ablation experiments and case study prove that our proposed loss can pay more attention to hard tasks in the training process, thus improve the performance. \section{Conclusion} This paper focuses on hard few-shot relation extraction tasks and proposes a hybrid contrastive relation-prototype approach. \begin{figure}[t!] \flushleft \includegraphics{tsne.pdf} \caption{t-SNE plots of instance embeddings trained with or without (w/o) relation-prototype contrastive learning. Two easy-to-confuse relations (``{\em mother}'' and ``{\em child}'') with 100 samples are adopted. Best viewed in color. } \label{tsne} \end{figure} The method proposes a hybrid prototype learning method that generates informative prototypes to model small inter-relation variations. {\color{black}A relation-prototype contrastive learning approach is proposed. Using relation information as anchors, it pulls instances of the same relation class closer in the representation space while pushing dis-similar ones apart. This process further enables the model to acquire more discriminative representations.} In addition, we introduce a task adaptive focal loss to focus more on hard tasks during training to achieve better performance. Experiments have demonstrated the effectiveness of our proposed model. There are multiple avenues for future work. One possible direction is to design a better mechanism for selecting tasks in the training process rather than using random sampling. \section*{Acknowledgements} We would like to thank the anonymous reviewers for their thoughtful and constructive comments. The first author is a visiting student at the StatNLP group of SUTD. This work is supported by the National Key Research and Development Program of China under grant 2018YFB1003804, in part by the National Natural Science Foundation of China under grant 61972043, 61772479, the Fundamental Research Funds for the Central Universities under grant 2020XD-A07-1, the BUPT Excellent Ph.D. Students Foundation under grant CX2020102, and China Scholarship Council Foundation. This research is also supported by Ministry of Education, Singapore, under its Academic Research Fund (AcRF) Tier 2 Programme (MOE AcRF Tier 2 Award No: MOE2017-T2-1-156). Any opinions, findings and conclusions or recommendations expressed in this material are those of the authors and do not reflect the views the Ministry of Education, Singapore.
{'timestamp': '2021-10-26T02:18:31', 'yymm': '2109', 'arxiv_id': '2109.05473', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05473'}
arxiv
\section{Introduction} With the explosion of online information, the large quantities of news generated every day may overwhelm users and make them difficult to find the news they are interested in. To tackle this problem, many news recommendation methods \cite{an-etal-2019-neural, wang-etal-2020-fine, wu-etal-2019-neural-news-recommendation,qi-etal-2021-hierec} have been proposed to display news according to users' personalized interests. These methods are usually composed of two core modules, i.e., user model and news model. The user model is used to learn user representations from user historical click behaviors. For example,~\citet{wang2018dkn} use a candidate-aware attention network as the user model to help capture user interests in candidate news. The news model is used to learn news representations from news content. For example,~\citet{wu2019neural} apply multi-head self attention network to capture the interactions between words in news model. With the success of pre-trained language models (PLM) in NLP, a few PLM-empowered news recommendation methods have been proposed and achieve remarkable performance. For example,~\citet{wu2021empowering} apply pre-trained language models to enhance news modeling. However, these methods require centralized storage of user behaviors, which are highly privacy-sensitive~\cite{shin2018privacy}. Collecting private user data has raised many concerns~\cite{wu2019tamf}. Moreover, due to the adoption of some data protection regulations such as GDPR\footnote{https://gdpr-info.eu}, it might not be able to analyze centralized user data in the future. Federated learning~\cite{mcmahan2017communication} is a privacy-preserving method to train models on the private data decentralized on a large number of clients. In federated learning, each user keeps a local copy of model, and compute local model gradients with their local private data. A central server coordinates the clients and aggregates local gradients to update the global model. Recently,~\citet{qi-etal-2020-privacy} proposed a FedRec method to train news recommendation models using federated learning. However, the model sizes of many existing news recommendation methods are large, especially their news models. For example, PLM-NR~\cite{wu2021empowering} has 110.7M parameter in total, 110M of which are in the news model (BERT-Base version). Thus, the communication and computation costs of FedRec can be too high for clients with rather limited computation resource. In this paper, we propose an efficient federated learning framework for privacy-preserving news recommendation named Efficient-FedRec\footnote{https://github.com/yjw1029/Efficient-FedRec}. In our framework, we decompose the news recommendation model into a large news model and a light-weight user model. Instead of training and communicating the whole model, in our approach the clients only request the user model and the representations of news involved in their local behaviors from the server. The clients locally compute the gradients of the user model and news representations on their local data, and send them to the server for aggregation. The central server uses the aggregated user model gradients to update its maintained global user model, and update the news model based on the aggregated news representation gradients. The updated news model is further used to infer updated news representations. The above process is repeated for multiple rounds until the model gets converges. In order to protect user privacy in model training, we develop a secure aggregation protocol based on the multi-party computation framework for privacy-preserving gradient aggregation. We exchange the news representations in the union news set involved by a group of user behaviors to protect the click history of a specific user. We conduct plenty of experiments on two real-world datasets and the results show that our approach can effectively reduce the computation and communication cost on clients for federated news recommendation model training. The main contributions of this work include: \begin{itemize} \setlength\itemsep{0.1em} \item We propose an efficient federated learning framework for privacy-preserving news recommendation, which can effectively reduce the computation and communication cost on the user side. \item We develop an effective and efficient secure aggregation protocol to protect user privacy in model training. \item We conduct thorough experiments on two real-world datasets to verify the effectiveness and efficiency of our approach. \end{itemize} \section{Related Works} \subsection{Neural News Recommendation} Personalized news recommendation is an important technique to alleviate the information overloading problem and improve user reading experience. Many deep learning based recommendation methods have been proposed ~\cite{wu2019npa,okura2017embedding,zhu2019dan,qi-etal-2021-pp,10.1145/3404835.3462861}. They usually contain two core modules, i.e., user model and news model. For example, ~\citet{an-etal-2019-neural} propose to use a CNN to learn contextual word embedding and an attention layer to select informative words. They combine long-term interests and short-term interests of users by using user id embeddings and a GRU network in user model. These methods learn news representations based on shallow NLP models, which is hard to well capture the news semantic information. Recently, pre-trained language models (PLM) achieve great success in NLP~\cite{Devlin2019BERTPO,liu2019roberta,bao2020unilmv2}. A few PLM-empowered news recommendation methods have been proposed. For example, ~\citet{wu2021empowering} propose PLM-NR to empower news modeling by applying pre-trained language. They replace the news encoder in previous methods with pre-trained language models, and get stable improvement on news recommendation task. However, all the above methods train models based on centralized data, which is highly privacy-sensitive. Such kind of collections and analysis of private data have led to privacy concerns and risks~\cite{shin2018privacy}. Besides, the adoption of some data protection regulations, such as GDPR\footnote{https://gdpr-info.eu}, gives news platforms restrictions and high pressure of using user data to prevent user data leakage. Different from these methods, we do not use centralized storage for training in our framework, which can better preserve user privacy. \subsection{Federated Learning} Federated Learning~\cite{mcmahan2017communication} is an effective method for privacy-preserving model training. It enables several users to collaboratively train models without sharing their data to a central server. In federated learning, users first request the latest updated model from central server, and compute local gradients with their local private data. Central server aggregates the gradients to update the global model and distributes the updated global model to user local devices. Since the local gradients may leak some private information of users~\cite{bhowmick2018protection, melis2019exploiting}, several privacy protection methods are applied, such as secure multi-party computation (MPC)~\cite{crypten2020}, differential privacy (DP)~\cite{ren2018textsf}, and homomorphic encryption (HE)~\cite{aono2017privacy}. Recently, several works have proposed to leverage federated learning in recommendation scenario. ~\citet{Ammaduddin2019FederatedCF} propose federated collaborative filtering (FCF). In FCF, users use their private rate data to compute gradients of user embeddings and item embeddings. The user embeddings are updated locally by the gradients of user embeddings, and the gradients of item embeddings are aggregated to update global item embeddings. ~\citet{chai2020secure} propose secure federated matrix factorization (FMF). FMF is similar to FCF but updates user embeddings and item embeddings according to matrix factorization algorithm. However, FCF and FMF are not suitable for news recommendation scenarios, since they represent items with ID embeddings and there is much fresh news generated every day. ~\citet{qi-etal-2020-privacy} propose a privacy-preserving method for news recommendation model training. In FedRec, users use their local data to compute gradients of the model parameters. A group of randomly sampled users sends their local gradients to the central server to update the global model. However, the communication and computation cost of FedRec is unacceptable for user devices with limited resource due to the large size of news recommendation models, especially their news models. In this paper, we propose Efficient-FedRec to reduce the overhead on clients. We decompose the news recommendation model into a large news model maintained in server and a light-weight user model shared between clients and server. A small number of news representations and user model are communicated. \section{Methodology} In this section, we introduce our Efficient-FedRec method for privacy-preserving news recommendation. We first introduce the problem formulation and news recommendation framework. Then we introduce the details of our Efficient-FedRec framework. The details of secure aggregation are demonstrated in the last subsection. \subsection{Problem Formulation} ~\label{sec:problem} Denote $\mathcal{U}=\{u_1, u_2, ... u_P\}$ as user set, where $P$ is the user number. Given a user $u$, his private behaviors $\mathcal{B}_{u}$ are locally stored on his devices. In our approach, we denote all news in user behaviors of user $u$ as $\mathcal{N}_u$. The news recommendation model is decomposed into a news model with parameter set $\Theta_n$ and a user model with parameter set $\Theta_u$. The server maintains the news models and generates news representations with parameter set $\Theta_e$, and keeps a global user encoder. The goal is to collaboratively train an accurate news recommendation model without leaking users' private information. \subsection{News Recommendation Framework} \begin{figure}[!t] \centering \includegraphics[width=0.45\textwidth]{comm-newsrec.pdf} \caption{News recommendation framework.} \label{fig:comm-newsrec} \end{figure} In this subsection, we introduce the news recommendation framework, which is shown in Figure~\ref{fig:comm-newsrec}. It is composed of two core modules, i.e., news model and user model. \begin{figure*}[!t] \centering \includegraphics[width=0.98\textwidth]{EffFR-frame.pdf} \caption{ The framework of Efficient-FedRec.} \label{fig:eff-frame} \end{figure*} \paragraph{News Model} Given a news $n$, the news model is used to learn news representations $\textbf{n}$ from news contents. It can be implemented by various model structures. Several existing news recommendation methods use shallow NLP models. ~\citet{wu2019neural} use a combination of multi-head self attention network and additive attention network, ~\citet{an-etal-2019-neural} use a combination of CNN network and additive attention network. With the success of pre-trained language models (PLM) in NLP, a few methods start to apply pre-trained language models in news model. ~\citet{wu2021empowering} propose PLM-NR, which uses a combination of pre-trained language model and additive attention network as news model. In our Efficient-FedRec, we apply the news model of PLM-NR~\cite{wu2021empowering}. \paragraph{User Model} The user model is used to learn user representations from user historical clicked news. Denoting the news representations of user historical clicked news $[\textbf{n}_1, \textbf{n}_2, ... \textbf{n}_M]$ as input, the user model computes user representations $\textbf{u}$ as output. It can be implemented by several model structures. ~\citet{wang2018dkn} use candidate-aware attention, and ~\citet{an-etal-2019-neural} combines user id embeddings and GRU network. In our Efficient-FedRec, we apply the user model of NRMS~\cite{wu2019neural}, which uses a combination of multi-head self attention network and additive attention network. \subsection{Framework of Efficient-FedRec} \label{sec:framework} In this subsection, we introduce the framework of our Efficient-FedRec. Each user who participates in model training is called a client. In our framework, client behaviors are locally stored on their devices, which prevents the risks of data leakage. Since data of a single user is not enough to train an intelligent news recommendation model, our framework enables multiple clients to collaboratively train a news recommendation model. To lower the communication and computation overhead on the client side, we decompose the news recommendation model into a large news model maintained on server and a light-weight user model shared on both server and clients. At the $t$-th round, the model updating contains four steps, i.e., distributing user model and news representations, training local user model and news representations, gradient aggregation and global model updating. The framework of our Efficient-FedRec is shown in Figure~\ref{fig:eff-frame}. The first step is distributing user model and news representations. Since the news model is heavy and users only need the news representations to predict click scores, in our framework users request a small number of news representations in their behaviors and user model instead of the whole model from the central server. However, directly requesting the news representations of news in user behaviors $\mathcal{N}_u$ will leak user private information. In our work, we randomly sample a group of clients, who exchange the representations of union news set involved by a group of user behaviors through a secure aggregation protocol (introduced in Section~\ref{sec:mpc}). Denoting the group of clients as ~$\mathcal{U}_s = \{u_1, u_2 ... u_s\}$, the union news set is computed as $\mathcal{N}_s = \cup_{u_i\in\mathcal{U}_s}\mathcal{N}_i$. Thus the server only knows the news accessed by a group of clients. Finally, users keep a local copy of user model $\Theta_u^t$, and news representations of union news set $\Theta_{e_s}^t$. It is noted news representations of union news set is much smaller than the news model (analyzed in Section~\ref{sec:eff}), which alleviates the communication cost. The second step is training local user model and news representations. Given a client $u$, we use his historical clicked news representations to compute user representations $\textbf{u}$ through the local user encoder. For a candidate news $n_c$, we use the candidate news representation $\textbf{n}_c$ and the user representation $\textbf{u}$ to compute a click score $s$ through a click predictor, which is dot-product in our framework. Following the previous work~\cite{wu2019neural, an-etal-2019-neural,qi-etal-2020-privacy}, we utilize categorical cross-entropy loss for training. More specifically, for every clicked candidate news, we sample $K$ non-clicked news in the same impression. Denote the label of the $i$-th news and user $u$ is $y^i$ and the prediction score is $s^i$, the loss of a training sample is computed as follows: \begin{equation} \mathcal{L}_u^j = -\sum_{i=1}^{K+1}y^i\times log(\frac{exp(s^i)}{\sum_{k=1}^{K+1}exp(s^k)}). \label{eq:loss} \end{equation} The final loss is the average loss of all training samples in $\mathcal{B}_u$, which is computed as follows: \begin{equation} \mathcal{L}_u = -\frac{1}{|\mathcal{B}_u|}\sum_{j=1}^{|\mathcal{B}_u|}\mathcal{L}_u^j \label{eq:loss_all} \end{equation} Denote the local gradients of user encoder as $g_{vu}^t$ and the local gradients of news representations as $g_{e_su}^t$, which are computed as follows: \begin{equation} \begin{aligned} &g_{vu}^t = \frac{\partial\mathcal{L}_u}{\partial\Theta_u^t}, &g_{e_su}^t =\frac{ \partial\mathcal{L}_u}{\partial\Theta_{e_s}^t}. \end{aligned} \end{equation} In this step, since clients only compute the user model, the computation cost on clients is alleviated. The third step is gradient aggregation. The server needs to compute the weighted sum of gradients of user model, news representations, and the sample number from the randomly sampled user group $\mathcal{U}_s$. Since the local gradients may contain some private information~\cite{bhowmick2018protection, melis2019exploiting}, we apply the secure aggregation to compute the summations (introduced in Section~\ref{sec:mpc}). The aggregated gradients of user model and news representations are denoted as $\overline{g}_v^t$ and $\overline{g}_{e_s}^t$, which are formulated as follows: \begin{equation} \begin{aligned} &\overline{g}_v^t = \frac{1}{\sum_{u \in \mathcal{U}_s}|\mathcal{B}_u|} \sum_{u \in \mathcal{U}_s} |\mathcal{B}_u| \cdot g_{vu}^t, \\ &\overline{g}_{e_s}^t = \frac{1}{\sum_{u \in \mathcal{U}_s}|\mathcal{B}_u|} \sum_{u \in \mathcal{U}_s} |\mathcal{B}_u| \cdot g_{e_su}^t, \end{aligned} \label{eq:useragg} \end{equation} It is noted that each user only sends the gradients of news representations in the union news set $\mathcal{N}_s$, which is much smaller than the news model. Thus we alleviate the communication overhead. The final step is global model updating. The global user model and news model are updated separately. The global user model is directly updated by gradients of user model through FedAdam algorithm ~\cite{reddi2020adaptive} as follows: \begin{equation} \begin{aligned} &\Delta_u^t = \beta_1 \Delta_u^{t-1} + (1-\beta_1) \overline{g}_u^t, \\ &v_u^t = \beta_2 v_u^{t-1} + (1-\beta_2) {\Delta_u^t}^2, \\ &\Theta_u^{t+1} = \Theta_u^t + \eta \frac{\Delta_u^t}{\sqrt{v_u^t+\tau}}, \end{aligned} \label{eq:userupdate} \end{equation} where $\eta$ is the learning rate, $\beta_1$, $\beta_2$ and $\tau$ are parameters of FedAdam. The news model is updated through a backpropagation training process. For each news in the union news set $n_i\in \mathcal{N}_s$, the central server has its content and the gradients of its news representation $\overline{g}_{e_i}^{t}\in \overline{g}_{e_s}^{t}$. We use the news content as input and compute its news representation $\mathbf{n}_i$ through the news model. The gradients of news model $\overline{g}_n^t$ are computed as follows: \begin{equation} \overline{g}_n^t = \sum_{n_i\in \mathcal{N}_s}\overline{g}_{e_i}^t \cdot \frac{\partial\textbf{n}_i}{\partial\Theta_n^t}, \label{eq:newsgrad} \end{equation} where $\Theta_n^t$ is the parameters of news model at the $t$-th round. We use Adam optimizer to updated new model, which in computed as follows: \begin{equation} \begin{aligned} &\Delta_n^t = \beta_1 \Delta_n^{t-1} + (1-\beta_1) \overline{g}_n^t, \\ &v_n^t = \beta_2 v_n^{t-1} + (1-\beta_2) {\Delta_n^t}^2, \\ &\Theta_n^{t+1} = \Theta_n^t + \eta \frac{\Delta_n^t}{\sqrt{v_n^t+\tau}}, \end{aligned} \label{eq:newsupdate} \end{equation} where $\eta$ is the learning rate, $\beta_1$, $\beta_2$ and $\tau$ are hyper parameters of Adam. We further use the updated news model to infer news representations. Finally, the updated news representations and user encoder are distributed to all clients. \subsection{Secure Aggregation} ~\label{sec:mpc} In this subsection, we first introduce secure aggregation proposed by \citet{bonawitz2017practical}, and then introduce how we apply it to our framework for secure gradients aggregation and news representations distributing. The secure aggregation is mainly based on multi-party computation (MPC). It aims to let central server compute weighted sum of vectors without accessing the local vectors of each client in federated learning scenario. Denoted the local vectors of clients as $\{\textbf{v}_1, \textbf{v}_2, ... \textbf{v}_n\}$, the secure aggregation computes $\textbf{v}=\sum_{i=1}^n\textbf{v}_i$ in a privacy-preserving way. Meanwhile, it solves the user drop problem on mobile devices. As we introduce in Section~\ref{sec:framework}, we use the secure aggregation twice. The first time is to compute the union news set $\mathcal{N}_s$ of a group of users. Given a user $u_i$, we first transform his local news set $\mathcal{N}_i$ into a local vector $\textbf{h}_i$, of which dimension equals the number of all news. The $\textbf{h}_i$ is defined as follows: \begin{equation} \textbf{h}_i^j = \left\{ \begin{aligned} &random, &if\ n_j \in \mathcal{N}_i \\ &0, &otherwise\\ \end{aligned} \right. \label{eq:trans} \end{equation} where $\textbf{h}_i^j$ is the $j$-th dimension of $\textbf{h}_i$, and $n_j$ is the $j$-th news in the total news set. We apply secure aggregation to compute the sum of vectors $\textbf{h} = \sum_{u_i\in\mathcal{U}_s}\textbf{h}_i$. The inverse transformation of Eq~\ref{eq:trans} is used to compute the union news set $\mathcal{N}_s$ from $\textbf{h}$. The sampled group of users then request the news representations in the union news set $\mathcal{N}_s$ from central server. The second time is to securely aggregate gradients. Each user flattens their local weighted gradients of news representations $|\mathcal{B}_u|\cdot g_{e_su}^t$, local gradients of user model $|\mathcal{B}_u|\cdot g_{vu}^t$ and their sample number $|\mathcal{B}_u|$ to a vector, and applies secure aggregation to compute the summation. It is noted that only the news in the union news set has the gradients of news representations. \section{Experiments} In this section, we demonstrate the efficiency and effectiveness of our Efficient-FedRec. We conduct several experiments to answer the following research questions: \begin{itemize} \item \textbf{RQ1:} How does our method perform compared with baseline methods? \item \textbf{RQ2:} Are the communication and computation overhead significantly reduced compared with baseline methods? \item \textbf{RQ3:} How does the news model size influence the performance and overhead of our framework? \item \textbf{RQ4:} How does the user group size influence the risk of user information leakage and the effectiveness of our method? \item \textbf{RQ5:} How does the user number influence the performance of our framework? \end{itemize} \begin{table}[!t] \centering \scalebox{0.85}{ \begin{tabular}{c|cc} \Xhline{1.5pt} & MIND & Adressa \\ \hline \#news & 65,238 & 20,428 \\ \#users & 94,057 & 640,503 \\ \#impressions & 230,117 & - \\ \#positive samples & 347,727 & 3,101,991 \\ \#negative samples & 8,236,715 & - \\ \Xhline{1.5pt} \end{tabular} } \caption{Statistics of MIND and Adressa datasets.} \label{tab:stat} \end{table} \subsection{Dataset and Experimental Settings} We conduct thorough experiments on two public datasets, i.e., MIND\footnote{https://msnews.github.io/} and Adressa\footnote{http://reclab.idi.ntnu.no/dataset/}. MIND\footnote{We use the small version of MIND for fast experiments.} ~\cite{wu-etal-2020-mind} is a public dataset collected on Microsoft News website in six weeks. Adressa~\cite{10.1145/3106426.3109436} is publicly released by Adresseavisen, a local newspaper company in Norway. Following ~\cite{qi-etal-2020-privacy} and ~\cite{hu-etal-2020-graph}, we use the 6-th day's click to build training dataset and construct historical clicks from the first 5 days' samples. We randomly sample 20\% clicks from the last day's clicks for validation and the rest clicks for testing. The historical clicks of validation and testing dataset are constructed from the first 6 days' samples. Since Adressa does not contain negative samples, we randomly sample 20 news for each click for testing. The detailed dataset statistics are summarized in Table~\ref{tab:stat}. Following many previous news recommendation works ~\cite{wu-etal-2020-mind, an-etal-2019-neural,qi-etal-2020-privacy,ijcai2021-224,ijcai2020-418}, we use AUC, MRR, nDCG@5 and nDCG@10 as evaluation metrics. In our experiments, we apply BERT-Base~\cite{Devlin2019BERTPO} for MIND and nb-bert-base~\cite{kummervold-etal-2021-operationalizing} for Adressa to initialize the pre-trained language model in news encoder. The dimension of news representations is 400. To mitigate overfitting, we apply dropout in user model. The dropout rate is 0.2. The learning rate is 0.00005. The number of negative samples associated with each positive sample is 4. The user group size is 50 on both MIND and Adressa. All hyper-parameters are selected according to results on the validation set. We repeat each experiment 5 times independently, and report the average results with standard deviations. \subsection{Performance Evaluation (RQ1)} \begin{table*}[] \centering \scalebox{0.75}{ \begin{tabular}{c|cccc|cccc} \Xhline{1.5pt} \hline \multirow{2}{*}{Method} & \multicolumn{4}{c|}{MIND} & \multicolumn{4}{c}{Adressa} \\ \cline{2-9} & AUC & MRR & nDCG@5 & nDCG@10 & AUC & MRR & nDCG@5 & nDCG@10 \\ \hline DFM & 60.67$\pm$0.20& 28.08$\pm$0.13& 29.93$\pm$0.13& 35.68$\pm$0.13 & 59.90$\pm$1.20& 32.68$\pm$0.75& 29.69$\pm$0.93 & 36.43$\pm$1.11\\ \hline DKN & 64.72$\pm$0.19& 30.53$\pm$0.13& 33.01$\pm$0.15& 38.70$\pm$0.16 & 73.73$\pm$0.48& 39.52$\pm$1.34& 40.98$\pm$1.24 & 47.48$\pm$0.86\\ LSTUR & 66.90$\pm$0.08& 32.45$\pm$0.07& 35.11$\pm$0.07& 40.82$\pm$0.07 & 68.37$\pm$2.63& 38.76$\pm$2.14& 38.11$\pm$2.39 & 44.33$\pm$2.42\\ NAML & 66.10$\pm$0.25& 31.91$\pm$0.23& 34.52$\pm$0.26& 40.21$\pm$0.24 & 73.09$\pm$1.53& 44.27$\pm$1.53& 43.51$\pm$1.89 & 50.02$\pm$1.71\\ NRMS & 66.67$\pm$0.21& 32.25$\pm$0.09& 49.88$\pm$0.11& 40.74$\pm$0.11 & 75.31$\pm$0.94& 42.24$\pm$0.92& 44.66$\pm$1.50 & 48.46$\pm$1.19\\ CenRec & 66.92$\pm$0.17& 32.30$\pm$0.11& 35.05$\pm$0.13& 40.78$\pm$0.14 & 72.85$\pm$1.53& 40.82$\pm$1.73& 41.62$\pm$2.24 & 47.54$\pm$1.47\\ PLM-NR & 67.79$\pm$0.29& 33.16$\pm$0.18& 36.08$\pm$0.21& 41.81$\pm$0.21 & 78.20$\pm$1.28& 47.26$\pm$1.73& 48.41$\pm$2.10 & 54.60$\pm$1.64\\ \hline FCF & 50.02$\pm$0.24& 22.37$\pm$0.18& 22.77$\pm$0.17& 29.02$\pm$0.17 & 51.39$\pm$0.74& 18.98$\pm$1.57& 15.42$\pm$1.72 & 22.94$\pm$1.30\\ FedRec & 66.54$\pm$0.18& 31.96$\pm$0.07& 34.54$\pm$0.09& 40.30$\pm$0.09 & 71.73$\pm$1.72& 41.37$\pm$2.21& 41.81$\pm$2.35 & 47.18$\pm$2.09\\ FedRec(BERT) & 67.45$\pm$0.10& 32.80$\pm$0.10& 35.44$\pm$0.16& 41.35$\pm$0.14 & 78.60$\pm$1.82& 43.81$\pm$0.95& 45.76$\pm$0.89 & 52.64$\pm$1.68\\ \hline Efficient-FedRec & 67.44$\pm$0.20& 32.79$\pm$0.06& 35.62$\pm$0.06& 41.35$\pm$0.07 & 79.08$\pm$1.18& 45.09$\pm$1.87& 47.13$\pm$2.35 & 53.85$\pm$1.69\\ \Xhline{1.5pt} \end{tabular} } \caption{Results of different news recommendation methods.} \label{tab:performance} \end{table*} In this section, we compare our Efficient-FedRec framework for privacy-preserving news recommendation with several baseline methods, including news recommendation methods with centralized storage: (1) DFM~\cite{lian2018towards}, a multi-channel deep fusion model for news recommendation; (2) DKN~\cite{wang2018dkn}, a knowledge-aware news recommendation method; (3) LSTUR~\cite{an-etal-2019-neural}, using user id embedding to capture user long-term interests, and GRU network to capture short-term interests; (4) NAML ~\cite{wu-etal-2019-neural-news-recommendation}, learning news representations via multi-view learning; (5) NRMS ~\cite{wu2019neural}, using two self-attention networks for better news and user modeling; (6) CenRec ~\cite{qi-etal-2020-privacy}, a central version of FedRec; (7) PLM-NR ~\cite{wu2021empowering}, applying pre-trained language model to empower the performance of news recommendation. For fair comparison, we use the user model in NRMS. privacy-preserving news recommendation methods: (8) FCF ~\cite{Ammaduddin2019FederatedCF}, federated collaborative filtering for recommendation; (9) FedRec ~\cite{qi-etal-2020-privacy}, privacy-preserving method for news recommendation model training. For fair comparison, we do not add differential privacy; (10) FedRec(BERT), applying FedRec to train PLM-NR in a privacy-preserving way. our method: (11) Efficient-FedRec, using our Efficient-FedRec framework to train PLM-NR in a privacy-preserving and efficient way. The experimental results of all these methods are shown in Table~\ref{tab:performance}. We have several observations from Table~\ref{tab:performance}. First, comparing our Efficient-FedRec with SOTA news recommendation methods with centralized storage (DKN, NAML, NRMS, LSTUR and PLM-NR), our method achieves comparable performance. Moreover, our method does not need users to share their behavior data. Therefore, it validates our method can train accurate news recommendation models and meanwhile protect user privacy. Second, our method performs better than FCF. This is because FCF is not suitable for news recommendation, since there are severe cold-start problems in news recommendation scenario~\cite{qi-etal-2020-privacy, wu-etal-2020-mind}. Third, our Efficient-FedRec outperforms FedRec. This is because we use pre-trained language model in news model, which can help better understand the semantics of news contents. Forth, comparing our Efficient-FedRec with FedRec(BERT), our Efficient-FedRec achieves comparable performance. This is because our method has the same gradients as FedRec(BERT) if dropout and batch normalization are not applied in news model. Finally, FedRec(BERT) and Efficient-FedRec perform worse than PLM-NR, and FedRec performs worse than CenRec. This is probably because user behaviors are non-i.i.d, which may make it difficult for federated learning to achieve good results~\cite{mcmahan2017communication,wang2019adaptive}. \begin{table*}[!t] \centering \scalebox{0.9}{ \begin{tabular}{c|c|ccc|ccc} \Xhline{1.5pt} \multirow{3}{*}{BERT} & \multirow{3}{*}{AUC} & \multicolumn{3}{c|}{Efficient-FedRec} & \multicolumn{3}{c}{FedRec} \\ \cline{3-8} & & Comm. & Comp. & Comp. & Comm. & Comp. & Comp. \\ & & Cost & Cost & Cost & Cost & Cost & Cost \\ & & (client) & (client) & (server) & (client) & (client) & (server) \\ \hline Tiny & 64.21 & 2.18M & 0.02s & 2.05s & 10.01M & 0.69s & 0.01s \\ Mini & 65.55 & 2.18M & 0.02s & 3.20s & 23.74M & 2.44s & 0.01s \\ Small & 65.92 & 2.18M & 0.02s & 5.88s & 59.32M & 9.03s & 0.01s \\ Medium & 67.05 & 2.18M & 0.02s & 6.39s & 84.54M & 19.55s & 0.01s \\ Base & 67.44 & 2.18M & 0.02s & 6.74s & 221.29M & 51.92s & 0.02s \\ Large & 67.50 & 2.18M & 0.02s & 8.81s & 673.28M & 117.04s & 0.04s \\ \Xhline{1.5pt} \end{tabular} } \caption{Results of different news models on MIND.} \label{tab:news-model} \end{table*} \subsection{Efficiency Analysis (RQ2)} ~\label{sec:eff} \begin{figure}[!t] \centering \includegraphics[width=0.45\textwidth]{cost.pdf} \caption{The communication cost and computation cost of privacy-preserving methods on MIND.} \label{fig:cost} \end{figure} \begin{figure*} \centering \begin{subfigure}[b]{0.23\textwidth} \centering \includegraphics[width=\textwidth]{news-num.pdf} \caption{Union news set size.} \label{fig:union-news} \end{subfigure} \hfill \begin{subfigure}[b]{0.23\textwidth} \centering \includegraphics[width=\textwidth]{converge-round.pdf} \caption{Convergence round.} \label{fig:conv-round} \end{subfigure} \hfill \begin{subfigure}[b]{0.25\textwidth} \centering \includegraphics[width=\textwidth]{all-comm-cost.pdf} \caption{Overall comm. cost.} \label{fig:all-comm-cost} \end{subfigure} \begin{subfigure}[b]{0.23\textwidth} \centering \includegraphics[width=\textwidth]{sa-time.pdf} \caption{Secure aggregation time.} \label{fig:secure-agg} \end{subfigure} \caption{Impact of user group size on MIND.} \label{fig:user-group-size} \end{figure*} In this subsection, we analyze the communication and computation cost of our Efficient-FedRec on MIND. The average size of the union news set is 1,320 per round, the gradient and parameter size of which is 1.06M. We assume users leverage CPU for calculation. Figure~\ref{fig:cost} shows the average computation time and the communication overhead of each user per round of several privacy-preserving methods. From Figure~\ref{fig:cost}, we have several observations. First, the average computation time of Efficient-FedRec is lower than those of FedRec and FedRec(BERT). This is because in our framework users do not need to compute the news model, which lowers the computation overhead. Second, the communication overhead of Efficient-FedRec is much lower than the overhead of FedRec and FedRec(BERT). This is because in our framework users request and send the gradients and parameters of user model and a small number of news representations, which is much smaller than the gradients and parameters of the whole model. \subsection{The Influence of News Model Size (RQ3)} In this subsection, we apply different size of BERTs in news model to study the influence of the news model size on MIND. The computation cost of clients is tested on CPU, while the computation cost of server is tested on GPU, which is reasonable since clients are usually with limited computation resource. The result are shown in Table~\ref{tab:news-model}, where we have several observations. First, the recommendation performance increases with the news model size, which shows the effectiveness of applying large news model. Second, the communication and computation cost of our method on clients are lower than FedRec. This is because in Efficient-FedRec clients only compute the user model and request the user model and the representations of news involved in their local behaviors. Additionally, the gap of the overhead between Efficient-FedRec and FeRec becomes larger with larger news model, which demonstrates the superiority of our method in using large news models. Third, the computation overhead of our method on server is larger than FedRec. It is because in our framework the news model is trained on central server. However, the overall computation time of Efficient-FedRec is lower than FedRec. This is because the server can use powerful GPU clusters to update the news model. It is noted that we simulate client computation cost with 100\% CPU utilization. The computation time on real-time devices will be larger than the results reported in Table~\ref{tab:news-model}. \subsection{Influence of User Group Size (RQ4)} \label{sec:user-group-size} In this section, we study the influence of user group size on union news set size, convergence round, overall communication cost and secure aggregation time. The results are shown in Figure~\ref{fig:user-group-size}. As shown in Figure~\ref{fig:union-news}, with the increasing of user group size, the size of union news set increases. When user group size is 40, the average size of union news set is 1,115, which is 10 times larger than the average size of user local news set, i.e., 114. Therefore, when user group size is large enough, it is hard for server to recover interacted news of users. Then, we study the impact of user group size on communication cost. Since larger user group size leads to larger union news set size, the communication cost of per user increases. In Figure~\ref{fig:conv-round} we also find larger user sizes can make the model converge faster. The impact of user group size on overall communication cost is shown in Figure~\ref{fig:all-comm-cost}, which is influenced by group user size, communication cost per user and convergence round. It is shown the overall communication cost increases with larger user group size. Finally, we study the impact of user group size on secure aggregation time (per user). As shown in Figure~\ref{fig:secure-agg}, the computation cost of secure aggregation increases with larger user group size. The computation time of secure aggregation is 0.71s when user group size is 50. Considering privacy protection ability, communication cost and secure aggregation cost, we set user group size as 50 in our experiment on MIND. \subsection{Influence of User Number (RQ5)} In this subsection, we study the influence of the number of users who participate in model training. We randomly sample different numbers of users from MIND. The experimental results are shown in Figure~\ref{fig:user}. We can observe the performance increases with higher user numbers, which validates the idea of training news recommendation collaboratively with a large size of users. Moreover, it shows our Efficient-FedRec can effectively explore useful information from multiple user behaviors. \begin{figure}[!t] \centering \includegraphics[width=0.45\textwidth]{user.pdf} \caption{Results of different user numbers on MIND.} \label{fig:user} \end{figure} \section{Conclusion} In this paper, we propose an efficient federated learning framework for privacy-preserving news recommendation named Efficient-FedRec. We decompose the news recommendation model into a large news model maintained by server and a light-weight user model. Users request news representations and user model from the central server and compute gradients with user local data. The central server aggregates gradients to update the user model and news model. The updated news model is further used to infer news representation by server. In order to protect the private information in user local gradients, we apply secure aggregation to aggregate gradients. In order to protect user interacted news history, we exchange the news representations in the union news set involved by a group of user behaviors. Experiments on two real-world datasets validate our method can effectively reduce both communication and computation cost on user side while keep the model performance. \section*{Ethical Statements} \textbf{User Information Protection in Dataset} In this paper, we conduct experiments on two public datasets, i.e., MIND and Adressa. MIND dataset was released in~\cite{wu-etal-2020-mind}. It is a public English news recommendation dataset. In this dataset each user was de-linked from the production system when securely hashed into an anonymized ID using onetime salt mapping to protect user privacy. We have agreed with Microsoft Research License Terms\footnote{https://msnews.github.io/} before downloading this dataset and complied with these license terms when using this dataset. Adressa dataset was released in~\cite{10.1145/3106426.3109436}. It is a public Norwegian news recommendation dataset. The users in this dataset are anonymized to protect user privacy. We follow the dataset license\footnote{https://creativecommons.org/licenses/by-nc-sa/4.0/} when using this dataset. Thus, all the datasets used in our paper are public datasets where user privacy information is well protected. \textbf{Influence of User Group Size} The user groups consist of randomly sampled users in each round to update model according to our framework. We conduct experiments to analyze the influence of user group size, and the results are summarized in Section~\ref{sec:user-group-size}. The experimental results show that as long as the user group size is properly large, which is usually easy to satisfy in practical applications, the information of user interacted news can be well protected. \section*{Acknowledgments} This work is supported by Youth Innovation Promotion Association of CAS. We would like to thank Tao Qi and Hao Wang for their great comments and help on experiments
{'timestamp': '2021-09-17T02:23:05', 'yymm': '2109', 'arxiv_id': '2109.05446', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05446'}
arxiv
\section{Introduction} We present a method for generating diverse collections of neural cellular automata (NCA) level generators.~\footnote{Code is available at \href{https://github.com/smearle/control-pcgrl}{https://github.com/smearle/control-pcgrl}} NCAs were derived from cellular automata (CA) in artifical life research. CAs are inspired by morphogenesis, the process of forming complex multi-celled lifeforms originating from a single cell, through simple rules that govern changes in each cell's state by observing neighboring cell states. NCAs differ from CAs by representing these rules as a neural network which takes as input a grid of cell states and outputs the same grid of cells with a changed state. We draw attention to the similarity between the morphogenetic process and the incremental design process employed by game designers when authoring video game levels. \begin{figure}[!t] \centering \includegraphics[width=\linewidth]{diagrams/front-fig.pdf} \caption{An overview of training NCAs for level generation. We sample NCA weights from a multi-variate Gaussian. The NCA repeatedly modifies levels for a fixed number of iterations. The final level is evaluated, then we add the NCA to the archive following CMA-ME's archive update.} \label{fig:front} \end{figure} NCAs could theoretically be used to simulate a wide variety of incremental processes involving local interactions---see, for example, the diversity of complex structures that have been discovered in both classic CAs ~\citep{cisneros2019evolving} and their variants~\citep{chan2020lenia, reinke2019intrinsically}. But so far, NCAs have been trained via supervised learning to learn a process that incrementally develops an initial state into a specific final artifact (e.g. replicating target images, textures, and 3D structures). However, we are interested in NCAs that generate levels satisfying specific criteria rather than a specific layout. So rather than using NCAs as indirect encodings of target artifacts, we re-frame them as generators, that each produce a range of artifacts that all satisfy some global constraints. To illustrate our method, let's consider a simple maze game where a player must walk from their initial position to an exit. Each maze must satisfy a criterion that all walkable areas must be connected. We can formulate the criterion as an objective of minimizing the number of connected regions present in the final output level after the NCA design process is complete. Formulating NCA training in the above way results in a single-objective optimization problem. However, this objective can be satisfied by just two adjacent tiles containing the player and the exit with the remaining tiles filled with walls. To promote non-trivial solutions, we can also measure how far apart the player is from the exit or the number of empty tiles present in the final level. By including these measurable aspects as input to the optimization problem, we form a quality diversity optimization problem where we must find solutions that minimize the objective but are diverse with respect to the measurable criteria. \begin{figure*} \centering \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_0.png} \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_1.png} \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_3.png} \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_6.png} \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_11.png}\\ frame: 0 \hspace{0.18\linewidth}1 \hspace{0.18\linewidth}3 \hspace{0.18\linewidth}6 \hspace{0.18\linewidth}11 \caption{\textbf{The NCA level generation process.} Information from a fixed initial seed is propagated out from the center of the board until a stable configuration, corresponding to high path-length, is reached. In intermediary level-states, tiles of different types, such as enemies and keys, appear to be used as a form of external memory during the generation process.} \label{fig:cellular_level_gen} \end{figure*} By framing the level-generation process as a QD problem, we thus generate a collection of NCAs, each producing levels of different length (or levels differing along any other, computable metric of form or function). But we may also want a variety of mazes with each length, and we may not be concerned about \textit{how} each maze achieves a given length. To encourage additional diversity beyond what is encoded as measured criteria, we treat each NCA like a generator, evaluating its performance on a set of random initial states -- here acting as latent inputs -- and adding to its objective a simple measure of diversity, i.e., the mean, pairwise per-tile difference over the set of generated levels. This differs from previous approaches, which train NCAs on a single, fixed initial state. In an actual application, generating a set of level generators rather than just a set of levels has the considerable advantage that the trained level generator can output new levels many orders of magnitude faster than the search process which generates the generator~\cite{kerssemakers2012procedural}. Our work makes the following contributions. 1) We formulate the training of an NCA as a quality diversity problem; 2) We train collections of level generators for several 2D tile-based games: a maze game, \textit{Sokoban}, and \textit{Zelda}; 3) We present qualitative results for each game and quantitative results based on the stability of the NCA generators for seeds outside the training seeds; and 4) We compare the use of incremental NCAs against a generative method using Compositional Pattern Producing Networks (CPPNs) to map $x, y$ coordinates and a latent $z$ to tile-values. To our knowledge, this is also the first work to apply NCAs to the problem of level-generation, and to use a derivative-free method for searching the space of NCA weights. Overall, we reframe training NCAs from an incremental replication process to an incremental \textit{design} process, which designs novel video game levels that satisfy complex criteria specified by a human designer. Our proposed approach could eventually be used as a design aid to modify existing human-designed levels to satisfy human-specified criteria in a manner similar to~\citet{delarosa2021mixed}. \section{Background} Procedural Content Generation (PCG) can both render human designers more efficient, automating and abstracting away low-level tasks, and provide them with new tools for creative expression. The sub-field of PCG via Machine Learning (PCGML~\citealt{summerville2018procedural}) studies training generative models on human-generated datasets, then prompting these models to generate plausible, original content at design-time. One potential issue with PCGML is that models may be unlikely to extract functional constraints from data. One way of addressing this is to supplement the generative model with a specialized module tasked with satisfying functional constraints~\citep{zhang2020video}. Another is to forego data altogether, framing level design as a game in which the player is trained to meet these constraints~\cite{khalifa2020pcgrl}. Our work takes the latter approach, but uses a specialized neural architecture to instantiate the generator. Cellular Automata (CA) are systems involving localized, distributed computations, often over an unbounded 2D square grid. Simple CAs have occasionally been used in PCG research: generating caves~\citep{johnson2010cellular}, influence maps~\citep{sweetser2005combining}, and maze-like levels~\citep{adams2017procedural}. Many CAs are capable of producing complex, emergent dynamics over long time horizons~\citep{wolfram1984cellular, cisneros2019evolving}, making them a natural fit for content generation in spatial domains. Neural Cellular Automata (NCAs,~\citealt{mordvintsev2020growing}) are CAs where rules are implemented as convolutional neural networks. Conway's Game of Life, the canonical CA with complex dynamics, can be implemented in a very small NCA, though such an architecture is hard to train via gradient descent (unless over-parameterized)~\citep{springer2020s}. Recently, more complex NCAs have been trained with gradient descent to generate images~\citep{mordvintsev2020growing}, textures~\citep{niklasson2021self}, and 3D structures~\citep{sudhakaran2021growing}. These NCAs tend to be robust and capable of self-repair when faced with out-of-distribution perturbations. In this work, NCAs perform an incremental level design task and are rewarded for the quality of the resultant levels according to a set of user-defined constraints and heuristics. The NCA models replace the (at least $10\times$) larger neural networks that have previously been trained in this context using Reinforcement Learning (RL)~\cite{khalifa2020pcgrl}. The end goal of our system is also similar to that of the controllable generators that have trained large networks using RL with conditional input and reward shaping~\citep{earle2021learning}. Like the archives produced here, controllable generators are intended to be sampled by an end-user to produce levels with controllable features along measures of interest. However, our approach is to produce a diverse archive of specialists as opposed to a single jack-of-all-trades. To optimize these smaller models, we turn to derivative-free quality diversity (QD) optimization methods~\citep{pugh2016quality, chatzilygeroudis2020quality}. Like RL, QD's problem definition allows for a variety of solving techniques. QD algorithms have been proposed based on genetic algorithms~\citep{mouret2015illuminating, cully:nature15, lehman2011evolving}, evolution strategies~\citep{conti2018improving, fontaine2020covariance, colas2020scaling}, differential evolution~\citep{choi:gecco21}, Bayesian optimization~\citep{kent2020bop}, and gradient ascent~\citep{fontaine2021differentiable}. A quality diversity problem's definition includes an objective function to be maximized as well as a set of measure functions, which assign scalar values to each proposed solution. A QD algorithm will search for solutions which satisfy all output combinations of the measure functions and will break ties by maximizing the objective. We note that if measure functions are continuous, then an infinite number of solutions will exist. To resolve this issue, QD algorithms in the MAP-Elites~\citep{mouret2015illuminating, cully:nature15} family will pre-tesselate the space of the measure functions' outputs, which we refer to in this paper as a measurement space. The goal of the algorithm is then to find a solution to each cell of the tesselation, where ties are once again broken by the objective. In our NCA training problem, the objective and measure functions we propose are not easily differentiable. Therefore, we generate the collection of NCAs via a derivative-free QD algorithm based on evolution strategies. Training the NCAs via evolutionary QD algorithms may yield additional benefits. Prior work demonstrates that evolutionary approaches are less prone to deception than their gradient descent counterparts~\citep{morse2016simple}. They may succeed in finding good solutions even when limited to small networks, while gradient descent would require much deeper neural networks to smooth the objective function~\citep{frankle2018lottery, nye2018efficient}. \begin{figure} \centering \includegraphics[width=1.0\linewidth]{diagrams/decoder_arch.pdf} \caption{A decoder-like architecture maps random normal latent vector of size $16$ (tiled in 2D) to a game level in a single pass, with transposed strided convolutions. In the zelda domain, the architecture has $\approx 5,000$ parameters.} \label{fig:decoder_arch} \end{figure} \begin{figure} \centering \includegraphics[width=1.0\linewidth]{diagrams/nca_arch.pdf} \caption{An NCA architecture repeatedly transforms a one-hot-encoded level state into another, based on local interactions over $3\times 3$ grids. In the zelda domain, the NCA has $\approx 3,000$ parameters.} \label{fig:nca_arch} \end{figure} \section{Methods} We generate a diverse collection of NCA level-generators through \mbox{CMA-ME}~\citep{fontaine2020covariance}, a quality-diversity algorithm combining the adaptation mechanisms of \mbox{CMA-ES}~\citep{hansen2016cma,hansen2001completely} with the archiving mechanisms of \mbox{MAP-Elites}~\citep{mouret2015illuminating}. We choose \mbox{CMA-ME} as it specializes in continuous domains and has been shown to be significantly more sample efficient than other QD algorithms in this setting. We train each NCA via the Pyribs library~\citep{pyribs:2021}, a QD optimization library maintained by the authors of \mbox{CMA-ME}. The \textbf{NCA}s (Figure~\ref{fig:nca_arch}) have the same architecture as those of~\citet{springer2020s}, with 3 convolutional layers, ReLU and sigmoid activations, and $32$ hidden channels. The output of the NCA has the same width, height, and number of channels as its input, with $\argmax$ applied channel-wise to produce a discrete encoding of the next level state. To have an NCA generate a game level, we feed it a onehot-encoded initial random level (or ``latent seed''), then repeat the process with the output of the NCA until the level converges to some stable state or a maximum number of steps is reached. Once the model has generated a batch of levels, its objective value is computed along with any relevant measures, and this information is sent back to CMA-ME so that the algorithm may update the covariance matrix and add the model to the archive. Once we complete training, we evaluate the archive of NCA models on new latent seeds, observing the extent to which the models are capable of generalization. A variation of the NCA architecture (\textbf{AuxNCA}) adds $3$ additional, ``auxiliary'' channels to the onehot-encoded level, which are initialized with 0s and, at subsequent iterations of the generative process, can serve as further external memory for the generative network. These channels are effectively invisible, and are separate from the onehot-encoding of the level. We compare NCAs against Compositional Pattern-Producing Networks (\textbf{CPPN}s,~\citealt{stanley2007compositional}), which can generate spatial artifacts such as images~\citep{secretan2008picbreeder} by taking coordinate-pairs as input and outputting the multi-channel value at the corresponding pixel. CPPNs have previously been used to generate parts of game levels~\citep{team2021open}, and can naturally encode spatial patterns such as symmetry. We train CPPNs via MAP-Elites with the variation operations from the NEAT algorithm~\citep{stanley2002evolving}. MAP-Elites maintains an archive of diverse generators and mutates their architectures in search of new elites. We choose MAP-Elites over CMA-ME, since CMA-ME only works on fixed-length real-value vector representations and cannot easily be extended to augment network topology. Additionally, we implement a fixed-topology CPPN with two hidden layers and sinusoidal activation functions (\textbf{SinCPPN}) and optimize its weights. We follow the weight-initialization scheme derived in~\citep{sitzmann2020implicit}, where it is shown that fixed-topology networks with periodic activations are capable of capturing fine-grained detail over continuous spaces. Having a fixed topology allows us to naturally make use of CMA-ME to train the CPPN's weights. It is important to note that since both CPPN-based models take only $(x, y)$ coordinates as input, they correspond to indirect encodings of individual levels rather than level-generators. To address this discrepancy, we implement generative versions of these models (\textbf{GenCPPN} and \textbf{GenSinCPPN}, inspired by~\cite{ha2016abstract}) that additionally take as input a random standard normal vector, which is tiled in 2D and concatenated to the $(x, y)$ coordinates at each tile before being fed into the CPPN. Finally, we train networks comprising a series of transposed convolutions, mapping a small latent space to a one-hot level representation in a single pass (\textbf{Decoder}, Figure \ref{fig:decoder_arch}). These networks are inspired by the ``decoder'' subnetworks in Variational Auto-Encoders (VAEs) and in the generator networks of Generative Adversarial Network (GAN) training schemes for, e.g., image generation. As in the case of Generative CPPNs, the latent space involves a random standard normal vector, tiled in 2D and concatenated with $(x, y)$ coordinates, only this time over a smaller 2D grid (of $4\times 4$ tiles). \begin{figure*}[t!] \begin{subfigure}[t]{0.49\textwidth} \begin{footnotesize} \centering \includegraphics[width=1.0\textwidth]{eval/EvoPCGRL_binary_ctrl-cellular_Decoder_['symmetry', 'path-length']_10-batch_1-pass_fixLvls_fixElites_5/eval_levels_fixLvls_grid.png} \includegraphics[width=.49\linewidth,trim=0 0 20 0,clip]{eval/EvoPCGRL_binary_ctrl-cellular_Decoder_['symmetry', 'path-length']_10-batch_1-pass_fixLvls_fixElites_5/diversity_fixLvls.png} \includegraphics[width=.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_binary_ctrl-cellular_Decoder_['symmetry', 'path-length']_10-batch_1-pass_fixLvls_fixElites_5/reliability_fixLvls.png} \caption{\textbf{Decoder} generators.} \label{fig:binary_cppn} \end{footnotesize} \end{subfigure} \begin{subfigure}[t]{0.49\textwidth} \begin{footnotesize} \centering \includegraphics[width=1.0\textwidth]{eval/EvoPCGRL_binary_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/eval_levels_fixLvls_grid.png} \includegraphics[width=.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_binary_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/diversity_fixLvls.png} \includegraphics[width=0.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_binary_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/reliability_fixLvls.png} \caption{\textbf{NCA} generators.} \label{fig:binary_nca} \end{footnotesize} \end{subfigure} \caption{Decoder-style architectures use global information and map latent seeds to levels in a single pass, while NCAs produce global coherence by iterative local interactions. With symmetry and path-length as measures of interest, NCAs yield a more thorough exploration of level space, filling out more of the archive.} \label{fig:binary_levels} \end{figure*} \subsection{The objectives of level generators} We define an objective function $o$ for a given generator as a weighted sum of components corresponding to validity $v$, reliability $r$, and intra-generator diversity $d$ of a batch of levels $L$ produced by the generator for a given game. \subsubsection{Validity}\label{sec:validity_Only} The validity term captures how well the batch of generated levels conform to soft constraints required by the game and each game has different validity constraints. For example, in Sokoban and Zelda a desired constraint is the level forming one connected region. To encourage this constraint we count the number of connected components present in the level and penalize generators for each additional region formed. In Zelda, valid levels contain $[2,5]$ enemies. We penalize how far outside the range a generated level falls. We give a full description of all validity constraints and penalties in the supplementary material. Once we aggregate all validity penalties into a negative penalty term $v_l$ for a given level $l$ in batch $L$, we average all penalties to form the validity term $v$: \begin{equation}\label{eq:validity} \begin{split} v &= \frac{1}{|L|}\sum_{l\in L} v_l \end{split} \end{equation} A perfectly valid level will obtain $v_l = 0$, while invalid levels will have a negative $v_l$ term. \subsubsection{Reliability} The reliability term captures the precision a generator maintains in measurement space. The batch of levels $L$ produced by the generator may have different outputs for the measure functions. For example, in the maze domain the length of the maze solution is a measure function for the QD problem. In this case, reliability captures how consistently a generator can produce levels of a given length. For each measure $m_i \in M$, the reliability penalty $r_i$ is the standard deviation of the batch of levels $L$ along measure $m_i$. We then take the average reliability score over the set of measures to arrive at the generator's reliability penalty $r$: \begin{equation}\label{eq:reliability} r = - \frac{1}{|M|} \sum_i r_i \end{equation} \subsubsection{Diversity} Intra-generator diversity refers to the amount of variation among the batch of levels produced by a generator. The term discourages generators from collapsing to a single optimal level, ignoring latent seed inputs. The diversity bonus $d$ is the mean pairwise hamming distance over the batch of levels, normalized per-tile; or the frequency (as a ratio from 0--1) with which a given coordinate tile differs between any two levels: \begin{equation}\label{eq:diversity} d = \frac{1}{(h \cdot w \cdot |L|^2)-1} \sum_{i \in L} \sum_{j \in L} H(i,j) \end{equation} where \(w\) and $h$ are the width and height of the levels, respectively, and \(H(i,j)\) is the hamming distance between levels \(i\) and \(j\) (viz. the number of cells on the level-grid that are not occupied by the same type of tile on both levels). \subsubsection{Combining Terms}\label{sec:combo_obj} Finally, we combine all three terms into a weighted sum to form the objective function $o$: \begin{equation}\label{eq:objective} o = v + \text{max}(0, r + 10 d) \end{equation} To understand the weighting of the terms, first consider how reliability and diversity affect one another. The desired goal of a generator is to produce a distribution of valid levels with precise measure values. One issue is a generator can obtain trivial diversity by having low reliability. So unreliability should detract from the diversity bonus, but not the validity score. Note that the output range of reliability is approximately $[-50, 0]$ and the diversity output range is a ratio in the range $[0, 1]$. We weight diversity to be closer to the range of reliability and then take the maximum with 0. The term $\max(0, r + 10 d)$ ensures that the reliability penalty only contributes when diversity is high enough. Finally, we add the $\max(0, r + 10 d)$ term to the validity penalty term to form our final objective function to be maximized in the QD problem. \subsection{Game environments} We generate collections of NCA generators for several game environments. In the maze domain, we aim to construct mazes with variable path-length (i.e. the longest shortest path between any two empty tiles), and in which all empty tiles are reachable by any other. In Zelda, levels must contain one player, key, door, 2--5 enemies, and again, strictly reachable empty tiles. The length of the path from player to key to door should vary, and the nearest enemy should be at least 4 tiles away from the player. In Sokoban, where the player must push each crate onto a target in order to complete the level, there must be the same number (and at least one each) of crates and targets, and the length of the solution produced by a deterministic solver should be varied. \section{Results and discussion} All experiments are run on a single 48--CPU node. The experiments in Tables~\ref{tbl:cross_eval_models} and \ref{tbl:cross_eval} and Figures~\ref{fig:binary_levels}--\ref{fig:sokoban_levels} were run for $50,000$ iterations each, taking 3 days or less. In Tables~\ref{tbl:cross_eval_models} and~\ref{tbl:cross_eval}, each experiment is repeated 11 times, and we report means and standard deviations over these trials. \begin{figure}[ht] \begin{footnotesize} \centering \includegraphics[width=.495\textwidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/eval_levels_fixLvls_grid.png} \includegraphics[width=.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/diversity_fixLvls.png} \includegraphics[width=.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/reliability_fixLvls.png} \caption{\textbf{Zelda levels produced by NCA generators diverse along measures of symmetry and path-length.} The levels with the longest paths tend to be more symmetrical.} \label{fig:zelda_levels} \end{footnotesize} \end{figure} \input{tables/cross_eval_models} \subsection{Comparison of architectures} In Table \ref{tbl:cross_eval} (appendix), we present the results of several hyperparameter ablations. Given the vanilla NCA architecture, we evolve archives evaluated on 10 or 20 latent seeds or random initial level states (denoted as ``batch size''), either fixing or resampling these latents throughout evolution, and given level-generation episodes of either 50 or 100 iterations. In Table \ref{tbl:cross_eval_models}, we focus on the effect of model architectures. We fix other hyperparameters, using a batch size of 10, fixed latent seeds, and 50-step episodes in the case of NCAs. In both cases, we examine the performance of evolved archives of neural network-based level-generators, both on the same latent seeds that were seen during training, and on 20 new seeds sampled during evaluation. After training, we observe the size of each archive as well as its quality diversity score (the sum of all generators' non-negative objective score\footnote{Each elite's objective score from Equation \ref{eq:objective} minus the minimum possible objective/validity score})~\citep{pugh2015confronting}, and the mean intra-generator diversity score (\(d\), Equation \ref{eq:diversity}). We note that the QD scores are lower in evaluation, where we use new seeds, compared to using the same seeds as training. This is because during evaluation, generators are prompted with new latent inputs and re-inserted into a fresh archive. Typically, this causes archives that are adversely affected by new latents to produce less diverse measure scores. Elites fall back toward the center of the archive, where they often collide in the same cell, causing a reduction in the size of the archive and the archive's QD score. In Table~\ref{tbl:cross_eval_models}, we see that NCA models maintain the largest archive and highest QD score after evaluation on new latent seeds, suggesting that they are more robust generators when compared against other architectures. Generative CPPNs (\textbf{GenCPPN}s) perform next-best in these metrics during evaluation, followed by the \textbf{Decoder}, and finally fixed-topology sinusoidal CPPNs (\textbf{GenSinCPPN}s). \textbf{AuxNCA}s---NCAs with additional auxiliary channels---outperform vanilla \textbf{NCA}s. On the other hand, the former exhibit less intra-generator diversity, while vanilla NCAs are on par with Generative CPPNs in this regard. Although the Decoder architecture has the highest intra-generator diversity, it performs quite poorly in other metrics, and we note that for any given generator, producing diverse output becomes trivial as the generated levels decrease in quality and fail to meet the various constraints being imposed upon them. During training, NCAs result in archives with the highest QD scores. They also result in the largest archives among generative architectures. NCAs with auxiliary channels produce the largest archives among all methods, while vanilla NCAs result in archives whose size is roughly on par with those populated by (non-generative, indirect-encoding) CPPNs. This suggests that---even putting their generative abilities aside---NCA-based architectures are better suited for searching the space of high-quality and diverse levels (given some fixed set of latent seeds). The differences in archive size, QD score, and intra-generator diversity across model architectures during training and evaluation was statistically significant as determined by one-way ANOVA tests ($p < 0.001$). Tukey post hoc tests additionally revealed that the difference in each of these metrics at training and evaluation time between each pair of models was statistically significant ($p = 0.001$) in nearly all cases. In all cases, significance holds between the dominant model and all others in a given metric. Both NCA models significantly outperform all others in terms of both archive size and QD score at training and evaluation time, with the only exception being between the archive sizes resulting from the vanilla NCAs and the non-generative CPPNs during training. \input{tables/cross_eval} In Table~\ref{tbl:cross_eval}, we find that our experiments are robust to changes in these hyperparameters, with no statistically significant differences resulting from hyperparameter changes other than the model architecture itself. \begin{figure}[ht] \begin{footnotesize} \centering \includegraphics[width=.495\textwidth,]{eval/EvoPCGRL_sokoban_ctrl-cellular_NCA_['emptiness', 'sol-length']_10-batch_100-pass_fixElites_5/eval_levels_fixLvls_grid.png} \includegraphics[width=.495\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_sokoban_ctrl-cellular_NCA_['emptiness', 'sol-length']_10-batch_100-pass_fixElites_5/diversity_fixLvls.png} \includegraphics[width=.495\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_sokoban_ctrl-cellular_NCA_['emptiness', 'sol-length']_10-batch_100-pass_fixElites_5/reliability_fixLvls.png} \caption{\textbf{Sokoban levels, diverse along measures of emptiness and path-length.} Levels requiring the most lengthy solutions tend to be roughly half-empty, with obstacles arranged so as to demand significant back-tracking from the player.} \label{fig:sokoban_levels} \end{footnotesize} \end{figure} \subsection{Level quality \& diversity} In the maze domain, an archive of generators is optimized along measures of symmetry (horizontal and vertical) and path-length in the mazes they produce (Figure~\ref{fig:binary_levels}). After 50,000 generations, both \textbf{NCA} and \textbf{Decoder} architecutures, evolved with CMA-ME have filled out a considerable portion of the archive, and come close to maximum path-length zig-zags. These near-optimal levels tend to occur in a region of level-space with medium symmetry. But NCAs fill out more of the high-path-length extremeties of the archive, where generators tend to be less reliable along measures of interest, and often less diverse. These results suggest that generators building levels in an emergent manner through iterative local interactions are able to explore level-space more thoroughly than one-step generators with global information. Where Decoder and NCA archives overlap, NCAs produce levels with target metrics of interest more reliably, although limiting diversity in the process. In Zelda (Figure~\ref{fig:zelda_levels}), we search along measures of symmetry and path-length. The maximum path-length level is further out of reach of the archive of NCAs. However, CMA-ME has explored along an area of level-space with high symmetry, culminating in something like a two-lane version of the optimal zig-zag (top-right). In Sokoban (Figure \ref{fig:sokoban_levels}), an archive of generators is optimized to explore along measures of emptiness and solution length. Optimization first discovers small, valid corridors, then extends them to produce chambers of increasing complexity. Again, more complex generators tend to be more brittle. Intra-generator diversity among Zelda and Sokoban level-generators is considerably lower than among maze generators. This may be because designing Zelda levels involves more interrelated constraints than when designing mazes: moving a player, door or key will not just potentially affect symmetry, but also path-length. The reliability score may also be weighted too heavily. \section{Limitations and future work} In this work, the generators are optimized to produce levels with exactly the same values along measures of interest (Equation~\ref{eq:reliability}). This ensures that the resulting archive can produce levels whose features are controllable with high precision. But for the sake of the optimization process, it may also be desirable to treat this variance as a QD measure. Depending on the end-user's need for reliability, they could then select only sufficiently reliable generators from the final archive during actual level design. By instead treating reliability as an objective, we may be stifling search from discovering bridges to high-complexity areas of level space via unreliable but exploratory generators. As this work argues for the viability of NCAs as level generators, a direct comparison against other neural networks that have already been used to this end would be desirable. But the size of these latter networks makes covariance matrix adaptation of their weights computationally infeasible for methods like CMA-ME, as this matrix has size $n^2$, with $n$ equal to the number of parameters in the network. Future work might side-step this issue by using differentiable quality diversity (DQD)~\citep{fontaine2021differentiable}, which, given a differentiable genome, uses gradients to update a covariance matrix that instead only scales quadratically with the number of diversity measures. While the low parameter-count of NCAs is integral to the feasability of our approach, each NCA update only propagates local changes, leading to many steps needed to generate each level and the use of the intermediate levels as external memory. These dependencies, on episode length and the number of (one-hot) tile-types on the game-board, could in theory be foregone by applying the NCA's single $3\times 3$ convolutional layer repeatedly. In a similar vein, fractal neural networks with weight-sharing \citep{larsson2016fractalnet, earle2020using} incorporate stabilizing, structured skip connections, either without any new weights, or with new weights added logarithmically with respect to increases in the size of the model's perceptive field. In our experiments, we have compared NCAs with several neural network-based generator representations that were trained with versions of MAP-Elites. There are many other methods for generating 2D levels that we have not compared with, because they fundamentally solve a different problem, so that a fair comparison would not be possible. For example, we could have used MAP-Elites to evolve levels using a direct representation~\cite{alvarez2019empowering}, or in the latent space of a generator network~\cite{fontaine2021illuminating}, but this would have meant searching for levels instead of level generators. Conversely, one could learn level generators using for example Generative Adversarial Networks or WaveFunctionCollapse, but this would have required example levels to train on, and would not generate archives of multiple generators that differ along pre-specified measures. In fact, we are not aware of previous attempts at generating archives of \emph{generators} using QD algorithms. \section{Conclusion} We present a method for generating a diverse archive of level-generators represented as simple Neural Cellular Automata. The space of NCAs for growing levels is explored by CMA-ME along measures of interest (like symmetry or solution-length) in the levels they produce. Each generator in the archive is optimized to produce batches of valid levels with reliable features along these measures, with these batches of levels varying among themselves where possible. While NCAs are restricted to local computation, they propagate spatial information across the level while editing it sequentially to form patterns with global complexity. These NCAs are capable of satisfying high-level functional constraints and heuristics in mazes, and zelda and sokoban levels (producing, e.g. puzzles that require a certain number of steps for completion by an A* solver). Compared to models with global information (fixed-topology and mutable CPPNs, optimized with CMA-ME and MAP-Elites, respectively; and Decoders optimized with CMA-ME), NCAs facilitate a more thorough exploration of level space, and its individual generators have much more diverse outputs. The archive of level-generators produced by our method have potential as co-creative tools, in which the human user might select from a archive of generators with diverse aesthetic and functional tendencies, perturbing their design process to dynamically explore the space of playable levels. They could also work for Experience-Driven Procedural Content Generation, where generators are chosen from an archive to produce a target experience for a particular induced player profile~\cite{yannakakis2011experience}. They may also be used to generate automatic curricula of game levels for training player-agents. To this end, our method explicitly incentivizes both the reliability of the generator along measures of interest, and the generation of diverse levels at each point in level-space. This could help increase the precision of the generated curriculum, and prevent a learning agent from over-fitting to any one difficult portion of the curriculum in which it would be fated to spend much of its time. \bibliographystyle{ACM-Reference-Format} \section{Introduction} We present a method for generating diverse collections of neural cellular automata (NCA) level generators.~\footnote{Code is available at \href{https://github.com/smearle/control-pcgrl}{https://github.com/smearle/control-pcgrl}} NCAs were derived from cellular automata (CA) in artifical life research. CAs are inspired by morphogenesis, the process of forming complex multi-celled lifeforms originating from a single cell, through simple rules that govern changes in each cell's state by observing neighboring cell states. NCAs differ from CAs by representing these rules as a neural network which takes as input a grid of cell states and outputs the same grid of cells with a changed state. We draw attention to the similarity between the morphogenetic process and the incremental design process employed by game designers when authoring video game levels. \begin{figure}[!t] \centering \includegraphics[width=\linewidth]{diagrams/front-fig.pdf} \caption{An overview of training NCAs for level generation. We sample NCA weights from a multi-variate Gaussian. The NCA repeatedly modifies levels for a fixed number of iterations. The final level is evaluated, then we add the NCA to the archive following CMA-ME's archive update.} \label{fig:front} \end{figure} NCAs could theoretically be used to simulate a wide variety of incremental processes involving local interactions---see, for example, the diversity of complex structures that have been discovered in both classic CAs ~\citep{cisneros2019evolving} and their variants~\citep{chan2020lenia, reinke2019intrinsically}. But so far, NCAs have been trained via supervised learning to learn a process that incrementally develops an initial state into a specific final artifact (e.g. replicating target images, textures, and 3D structures). However, we are interested in NCAs that generate levels satisfying specific criteria rather than a specific layout. So rather than using NCAs as indirect encodings of target artifacts, we re-frame them as generators, that each produce a range of artifacts that all satisfy some global constraints. To illustrate our method, let's consider a simple maze game where a player must walk from their initial position to an exit. Each maze must satisfy a criterion that all walkable areas must be connected. We can formulate the criterion as an objective of minimizing the number of connected regions present in the final output level after the NCA design process is complete. Formulating NCA training in the above way results in a single-objective optimization problem. However, this objective can be satisfied by just two adjacent tiles containing the player and the exit with the remaining tiles filled with walls. To promote non-trivial solutions, we can also measure how far apart the player is from the exit or the number of empty tiles present in the final level. By including these measurable aspects as input to the optimization problem, we form a quality diversity optimization problem where we must find solutions that minimize the objective but are diverse with respect to the measurable criteria. \begin{figure*} \centering \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_0.png} \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_1.png} \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_3.png} \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_6.png} \includegraphics[width=0.19\linewidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['emptiness', 'path-length']_0-batch_100-pass_fixLvls_fixElites_0/renders/model_4_5/frame_11.png}\\ frame: 0 \hspace{0.18\linewidth}1 \hspace{0.18\linewidth}3 \hspace{0.18\linewidth}6 \hspace{0.18\linewidth}11 \caption{\textbf{The NCA level generation process.} Information from a fixed initial seed is propagated out from the center of the board until a stable configuration, corresponding to high path-length, is reached. In intermediary level-states, tiles of different types, such as enemies and keys, appear to be used as a form of external memory during the generation process.} \label{fig:cellular_level_gen} \end{figure*} By framing the level-generation process as a QD problem, we thus generate a collection of NCAs, each producing levels of different length (or levels differing along any other, computable metric of form or function). But we may also want a variety of mazes with each length, and we may not be concerned about \textit{how} each maze achieves a given length. To encourage additional diversity beyond what is encoded as measured criteria, we treat each NCA like a generator, evaluating its performance on a set of random initial states -- here acting as latent inputs -- and adding to its objective a simple measure of diversity, i.e., the mean, pairwise per-tile difference over the set of generated levels. This differs from previous approaches, which train NCAs on a single, fixed initial state. In an actual application, generating a set of level generators rather than just a set of levels has the considerable advantage that the trained level generator can output new levels many orders of magnitude faster than the search process which generates the generator~\cite{kerssemakers2012procedural}. Our work makes the following contributions. 1) We formulate the training of an NCA as a quality diversity problem; 2) We train collections of level generators for several 2D tile-based games: a maze game, \textit{Sokoban}, and \textit{Zelda}; 3) We present qualitative results for each game and quantitative results based on the stability of the NCA generators for seeds outside the training seeds; and 4) We compare the use of incremental NCAs against a generative method using Compositional Pattern Producing Networks (CPPNs) to map $x, y$ coordinates and a latent $z$ to tile-values. To our knowledge, this is also the first work to apply NCAs to the problem of level-generation, and to use a derivative-free method for searching the space of NCA weights. Overall, we reframe training NCAs from an incremental replication process to an incremental \textit{design} process, which designs novel video game levels that satisfy complex criteria specified by a human designer. Our proposed approach could eventually be used as a design aid to modify existing human-designed levels to satisfy human-specified criteria in a manner similar to~\citet{delarosa2021mixed}. \section{Background} Procedural Content Generation (PCG) can both render human designers more efficient, automating and abstracting away low-level tasks, and provide them with new tools for creative expression. The sub-field of PCG via Machine Learning (PCGML~\citealt{summerville2018procedural}) studies training generative models on human-generated datasets, then prompting these models to generate plausible, original content at design-time. One potential issue with PCGML is that models may be unlikely to extract functional constraints from data. One way of addressing this is to supplement the generative model with a specialized module tasked with satisfying functional constraints~\citep{zhang2020video}. Another is to forego data altogether, framing level design as a game in which the player is trained to meet these constraints~\cite{khalifa2020pcgrl}. Our work takes the latter approach, but uses a specialized neural architecture to instantiate the generator. Cellular Automata (CA) are systems involving localized, distributed computations, often over an unbounded 2D square grid. Simple CAs have occasionally been used in PCG research: generating caves~\citep{johnson2010cellular}, influence maps~\citep{sweetser2005combining}, and maze-like levels~\citep{adams2017procedural}. Many CAs are capable of producing complex, emergent dynamics over long time horizons~\citep{wolfram1984cellular, cisneros2019evolving}, making them a natural fit for content generation in spatial domains. Neural Cellular Automata (NCAs,~\citealt{mordvintsev2020growing}) are CAs where rules are implemented as convolutional neural networks. Conway's Game of Life, the canonical CA with complex dynamics, can be implemented in a very small NCA, though such an architecture is hard to train via gradient descent (unless over-parameterized)~\citep{springer2020s}. Recently, more complex NCAs have been trained with gradient descent to generate images~\citep{mordvintsev2020growing}, textures~\citep{niklasson2021self}, and 3D structures~\citep{sudhakaran2021growing}. These NCAs tend to be robust and capable of self-repair when faced with out-of-distribution perturbations. In this work, NCAs perform an incremental level design task and are rewarded for the quality of the resultant levels according to a set of user-defined constraints and heuristics. The NCA models replace the (at least $10\times$) larger neural networks that have previously been trained in this context using Reinforcement Learning (RL)~\cite{khalifa2020pcgrl}. The end goal of our system is also similar to that of the controllable generators that have trained large networks using RL with conditional input and reward shaping~\citep{earle2021learning}. Like the archives produced here, controllable generators are intended to be sampled by an end-user to produce levels with controllable features along measures of interest. However, our approach is to produce a diverse archive of specialists as opposed to a single jack-of-all-trades. To optimize these smaller models, we turn to derivative-free quality diversity (QD) optimization methods~\citep{pugh2016quality, chatzilygeroudis2020quality}. Like RL, QD's problem definition allows for a variety of solving techniques. QD algorithms have been proposed based on genetic algorithms~\citep{mouret2015illuminating, cully:nature15, lehman2011evolving}, evolution strategies~\citep{conti2018improving, fontaine2020covariance, colas2020scaling}, differential evolution~\citep{choi:gecco21}, Bayesian optimization~\citep{kent2020bop}, and gradient ascent~\citep{fontaine2021differentiable}. A quality diversity problem's definition includes an objective function to be maximized as well as a set of measure functions, which assign scalar values to each proposed solution. A QD algorithm will search for solutions which satisfy all output combinations of the measure functions and will break ties by maximizing the objective. We note that if measure functions are continuous, then an infinite number of solutions will exist. To resolve this issue, QD algorithms in the MAP-Elites~\citep{mouret2015illuminating, cully:nature15} family will pre-tesselate the space of the measure functions' outputs, which we refer to in this paper as a measurement space. The goal of the algorithm is then to find a solution to each cell of the tesselation, where ties are once again broken by the objective. In our NCA training problem, the objective and measure functions we propose are not easily differentiable. Therefore, we generate the collection of NCAs via a derivative-free QD algorithm based on evolution strategies. Training the NCAs via evolutionary QD algorithms may yield additional benefits. Prior work demonstrates that evolutionary approaches are less prone to deception than their gradient descent counterparts~\citep{morse2016simple}. They may succeed in finding good solutions even when limited to small networks, while gradient descent would require much deeper neural networks to smooth the objective function~\citep{frankle2018lottery, nye2018efficient}. \begin{figure} \centering \includegraphics[width=1.0\linewidth]{diagrams/decoder_arch.pdf} \caption{A decoder-like architecture maps random normal latent vector of size $16$ (tiled in 2D) to a game level in a single pass, with transposed strided convolutions. In the zelda domain, the architecture has $\approx 5,000$ parameters.} \label{fig:decoder_arch} \end{figure} \begin{figure} \centering \includegraphics[width=1.0\linewidth]{diagrams/nca_arch.pdf} \caption{An NCA architecture repeatedly transforms a one-hot-encoded level state into another, based on local interactions over $3\times 3$ grids. In the zelda domain, the NCA has $\approx 3,000$ parameters.} \label{fig:nca_arch} \end{figure} \section{Methods} We generate a diverse collection of NCA level-generators through \mbox{CMA-ME}~\citep{fontaine2020covariance}, a quality-diversity algorithm combining the adaptation mechanisms of \mbox{CMA-ES}~\citep{hansen2016cma,hansen2001completely} with the archiving mechanisms of \mbox{MAP-Elites}~\citep{mouret2015illuminating}. We choose \mbox{CMA-ME} as it specializes in continuous domains and has been shown to be significantly more sample efficient than other QD algorithms in this setting. We train each NCA via the Pyribs library~\citep{pyribs:2021}, a QD optimization library maintained by the authors of \mbox{CMA-ME}. The \textbf{NCA}s (Figure~\ref{fig:nca_arch}) have the same architecture as those of~\citet{springer2020s}, with 3 convolutional layers, ReLU and sigmoid activations, and $32$ hidden channels. The output of the NCA has the same width, height, and number of channels as its input, with $\argmax$ applied channel-wise to produce a discrete encoding of the next level state. To have an NCA generate a game level, we feed it a onehot-encoded initial random level (or ``latent seed''), then repeat the process with the output of the NCA until the level converges to some stable state or a maximum number of steps is reached. Once the model has generated a batch of levels, its objective value is computed along with any relevant measures, and this information is sent back to CMA-ME so that the algorithm may update the covariance matrix and add the model to the archive. Once we complete training, we evaluate the archive of NCA models on new latent seeds, observing the extent to which the models are capable of generalization. A variation of the NCA architecture (\textbf{AuxNCA}) adds $3$ additional, ``auxiliary'' channels to the onehot-encoded level, which are initialized with 0s and, at subsequent iterations of the generative process, can serve as further external memory for the generative network. These channels are effectively invisible, and are separate from the onehot-encoding of the level. We compare NCAs against Compositional Pattern-Producing Networks (\textbf{CPPN}s,~\citealt{stanley2007compositional}), which can generate spatial artifacts such as images~\citep{secretan2008picbreeder} by taking coordinate-pairs as input and outputting the multi-channel value at the corresponding pixel. CPPNs have previously been used to generate parts of game levels~\citep{team2021open}, and can naturally encode spatial patterns such as symmetry. We train CPPNs via MAP-Elites with the variation operations from the NEAT algorithm~\citep{stanley2002evolving}. MAP-Elites maintains an archive of diverse generators and mutates their architectures in search of new elites. We choose MAP-Elites over CMA-ME, since CMA-ME only works on fixed-length real-value vector representations and cannot easily be extended to augment network topology. Additionally, we implement a fixed-topology CPPN with two hidden layers and sinusoidal activation functions (\textbf{SinCPPN}) and optimize its weights. We follow the weight-initialization scheme derived in~\citep{sitzmann2020implicit}, where it is shown that fixed-topology networks with periodic activations are capable of capturing fine-grained detail over continuous spaces. Having a fixed topology allows us to naturally make use of CMA-ME to train the CPPN's weights. It is important to note that since both CPPN-based models take only $(x, y)$ coordinates as input, they correspond to indirect encodings of individual levels rather than level-generators. To address this discrepancy, we implement generative versions of these models (\textbf{GenCPPN} and \textbf{GenSinCPPN}, inspired by~\cite{ha2016abstract}) that additionally take as input a random standard normal vector, which is tiled in 2D and concatenated to the $(x, y)$ coordinates at each tile before being fed into the CPPN. Finally, we train networks comprising a series of transposed convolutions, mapping a small latent space to a one-hot level representation in a single pass (\textbf{Decoder}, Figure \ref{fig:decoder_arch}). These networks are inspired by the ``decoder'' subnetworks in Variational Auto-Encoders (VAEs) and in the generator networks of Generative Adversarial Network (GAN) training schemes for, e.g., image generation. As in the case of Generative CPPNs, the latent space involves a random standard normal vector, tiled in 2D and concatenated with $(x, y)$ coordinates, only this time over a smaller 2D grid (of $4\times 4$ tiles). \begin{figure*}[t!] \begin{subfigure}[t]{0.49\textwidth} \begin{footnotesize} \centering \includegraphics[width=1.0\textwidth]{eval/EvoPCGRL_binary_ctrl-cellular_Decoder_['symmetry', 'path-length']_10-batch_1-pass_fixLvls_fixElites_5/eval_levels_fixLvls_grid.png} \includegraphics[width=.49\linewidth,trim=0 0 20 0,clip]{eval/EvoPCGRL_binary_ctrl-cellular_Decoder_['symmetry', 'path-length']_10-batch_1-pass_fixLvls_fixElites_5/diversity_fixLvls.png} \includegraphics[width=.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_binary_ctrl-cellular_Decoder_['symmetry', 'path-length']_10-batch_1-pass_fixLvls_fixElites_5/reliability_fixLvls.png} \caption{\textbf{Decoder} generators.} \label{fig:binary_cppn} \end{footnotesize} \end{subfigure} \begin{subfigure}[t]{0.49\textwidth} \begin{footnotesize} \centering \includegraphics[width=1.0\textwidth]{eval/EvoPCGRL_binary_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/eval_levels_fixLvls_grid.png} \includegraphics[width=.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_binary_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/diversity_fixLvls.png} \includegraphics[width=0.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_binary_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/reliability_fixLvls.png} \caption{\textbf{NCA} generators.} \label{fig:binary_nca} \end{footnotesize} \end{subfigure} \caption{Decoder-style architectures use global information and map latent seeds to levels in a single pass, while NCAs produce global coherence by iterative local interactions. With symmetry and path-length as measures of interest, NCAs yield a more thorough exploration of level space, filling out more of the archive.} \label{fig:binary_levels} \end{figure*} \subsection{The objectives of level generators} We define an objective function $o$ for a given generator as a weighted sum of components corresponding to validity $v$, reliability $r$, and intra-generator diversity $d$ of a batch of levels $L$ produced by the generator for a given game. \subsubsection{Validity}\label{sec:validity_Only} The validity term captures how well the batch of generated levels conform to soft constraints required by the game and each game has different validity constraints. For example, in Sokoban and Zelda a desired constraint is the level forming one connected region. To encourage this constraint we count the number of connected components present in the level and penalize generators for each additional region formed. In Zelda, valid levels contain $[2,5]$ enemies. We penalize how far outside the range a generated level falls. We give a full description of all validity constraints and penalties in the supplementary material. Once we aggregate all validity penalties into a negative penalty term $v_l$ for a given level $l$ in batch $L$, we average all penalties to form the validity term $v$: \begin{equation}\label{eq:validity} \begin{split} v &= \frac{1}{|L|}\sum_{l\in L} v_l \end{split} \end{equation} A perfectly valid level will obtain $v_l = 0$, while invalid levels will have a negative $v_l$ term. \subsubsection{Reliability} The reliability term captures the precision a generator maintains in measurement space. The batch of levels $L$ produced by the generator may have different outputs for the measure functions. For example, in the maze domain the length of the maze solution is a measure function for the QD problem. In this case, reliability captures how consistently a generator can produce levels of a given length. For each measure $m_i \in M$, the reliability penalty $r_i$ is the standard deviation of the batch of levels $L$ along measure $m_i$. We then take the average reliability score over the set of measures to arrive at the generator's reliability penalty $r$: \begin{equation}\label{eq:reliability} r = - \frac{1}{|M|} \sum_i r_i \end{equation} \subsubsection{Diversity} Intra-generator diversity refers to the amount of variation among the batch of levels produced by a generator. The term discourages generators from collapsing to a single optimal level, ignoring latent seed inputs. The diversity bonus $d$ is the mean pairwise hamming distance over the batch of levels, normalized per-tile; or the frequency (as a ratio from 0--1) with which a given coordinate tile differs between any two levels: \begin{equation}\label{eq:diversity} d = \frac{1}{(h \cdot w \cdot |L|^2)-1} \sum_{i \in L} \sum_{j \in L} H(i,j) \end{equation} where \(w\) and $h$ are the width and height of the levels, respectively, and \(H(i,j)\) is the hamming distance between levels \(i\) and \(j\) (viz. the number of cells on the level-grid that are not occupied by the same type of tile on both levels). \subsubsection{Combining Terms}\label{sec:combo_obj} Finally, we combine all three terms into a weighted sum to form the objective function $o$: \begin{equation}\label{eq:objective} o = v + \text{max}(0, r + 10 d) \end{equation} To understand the weighting of the terms, first consider how reliability and diversity affect one another. The desired goal of a generator is to produce a distribution of valid levels with precise measure values. One issue is a generator can obtain trivial diversity by having low reliability. So unreliability should detract from the diversity bonus, but not the validity score. Note that the output range of reliability is approximately $[-50, 0]$ and the diversity output range is a ratio in the range $[0, 1]$. We weight diversity to be closer to the range of reliability and then take the maximum with 0. The term $\max(0, r + 10 d)$ ensures that the reliability penalty only contributes when diversity is high enough. Finally, we add the $\max(0, r + 10 d)$ term to the validity penalty term to form our final objective function to be maximized in the QD problem. \subsection{Game environments} We generate collections of NCA generators for several game environments. In the maze domain, we aim to construct mazes with variable path-length (i.e. the longest shortest path between any two empty tiles), and in which all empty tiles are reachable by any other. In Zelda, levels must contain one player, key, door, 2--5 enemies, and again, strictly reachable empty tiles. The length of the path from player to key to door should vary, and the nearest enemy should be at least 4 tiles away from the player. In Sokoban, where the player must push each crate onto a target in order to complete the level, there must be the same number (and at least one each) of crates and targets, and the length of the solution produced by a deterministic solver should be varied. \section{Results and discussion} All experiments are run on a single 48--CPU node. The experiments in Tables~\ref{tbl:cross_eval_models} and \ref{tbl:cross_eval} and Figures~\ref{fig:binary_levels}--\ref{fig:sokoban_levels} were run for $50,000$ iterations each, taking 3 days or less. In Tables~\ref{tbl:cross_eval_models} and~\ref{tbl:cross_eval}, each experiment is repeated 11 times, and we report means and standard deviations over these trials. \begin{figure}[ht] \begin{footnotesize} \centering \includegraphics[width=.495\textwidth]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/eval_levels_fixLvls_grid.png} \includegraphics[width=.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/diversity_fixLvls.png} \includegraphics[width=.49\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_zelda_ctrl-cellular_NCA_['symmetry', 'path-length']_20-batch_100-pass_fixLvls_fixElites_5/reliability_fixLvls.png} \caption{\textbf{Zelda levels produced by NCA generators diverse along measures of symmetry and path-length.} The levels with the longest paths tend to be more symmetrical.} \label{fig:zelda_levels} \end{footnotesize} \end{figure} \input{tables/cross_eval_models} \subsection{Comparison of architectures} In Table \ref{tbl:cross_eval} (appendix), we present the results of several hyperparameter ablations. Given the vanilla NCA architecture, we evolve archives evaluated on 10 or 20 latent seeds or random initial level states (denoted as ``batch size''), either fixing or resampling these latents throughout evolution, and given level-generation episodes of either 50 or 100 iterations. In Table \ref{tbl:cross_eval_models}, we focus on the effect of model architectures. We fix other hyperparameters, using a batch size of 10, fixed latent seeds, and 50-step episodes in the case of NCAs. In both cases, we examine the performance of evolved archives of neural network-based level-generators, both on the same latent seeds that were seen during training, and on 20 new seeds sampled during evaluation. After training, we observe the size of each archive as well as its quality diversity score (the sum of all generators' non-negative objective score\footnote{Each elite's objective score from Equation \ref{eq:objective} minus the minimum possible objective/validity score})~\citep{pugh2015confronting}, and the mean intra-generator diversity score (\(d\), Equation \ref{eq:diversity}). We note that the QD scores are lower in evaluation, where we use new seeds, compared to using the same seeds as training. This is because during evaluation, generators are prompted with new latent inputs and re-inserted into a fresh archive. Typically, this causes archives that are adversely affected by new latents to produce less diverse measure scores. Elites fall back toward the center of the archive, where they often collide in the same cell, causing a reduction in the size of the archive and the archive's QD score. In Table~\ref{tbl:cross_eval_models}, we see that NCA models maintain the largest archive and highest QD score after evaluation on new latent seeds, suggesting that they are more robust generators when compared against other architectures. Generative CPPNs (\textbf{GenCPPN}s) perform next-best in these metrics during evaluation, followed by the \textbf{Decoder}, and finally fixed-topology sinusoidal CPPNs (\textbf{GenSinCPPN}s). \textbf{AuxNCA}s---NCAs with additional auxiliary channels---outperform vanilla \textbf{NCA}s. On the other hand, the former exhibit less intra-generator diversity, while vanilla NCAs are on par with Generative CPPNs in this regard. Although the Decoder architecture has the highest intra-generator diversity, it performs quite poorly in other metrics, and we note that for any given generator, producing diverse output becomes trivial as the generated levels decrease in quality and fail to meet the various constraints being imposed upon them. During training, NCAs result in archives with the highest QD scores. They also result in the largest archives among generative architectures. NCAs with auxiliary channels produce the largest archives among all methods, while vanilla NCAs result in archives whose size is roughly on par with those populated by (non-generative, indirect-encoding) CPPNs. This suggests that---even putting their generative abilities aside---NCA-based architectures are better suited for searching the space of high-quality and diverse levels (given some fixed set of latent seeds). The differences in archive size, QD score, and intra-generator diversity across model architectures during training and evaluation was statistically significant as determined by one-way ANOVA tests ($p < 0.001$). Tukey post hoc tests additionally revealed that the difference in each of these metrics at training and evaluation time between each pair of models was statistically significant ($p = 0.001$) in nearly all cases. In all cases, significance holds between the dominant model and all others in a given metric. Both NCA models significantly outperform all others in terms of both archive size and QD score at training and evaluation time, with the only exception being between the archive sizes resulting from the vanilla NCAs and the non-generative CPPNs during training. \input{tables/cross_eval} In Table~\ref{tbl:cross_eval}, we find that our experiments are robust to changes in these hyperparameters, with no statistically significant differences resulting from hyperparameter changes other than the model architecture itself. \begin{figure}[ht] \begin{footnotesize} \centering \includegraphics[width=.495\textwidth,]{eval/EvoPCGRL_sokoban_ctrl-cellular_NCA_['emptiness', 'sol-length']_10-batch_100-pass_fixElites_5/eval_levels_fixLvls_grid.png} \includegraphics[width=.495\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_sokoban_ctrl-cellular_NCA_['emptiness', 'sol-length']_10-batch_100-pass_fixElites_5/diversity_fixLvls.png} \includegraphics[width=.495\linewidth,trim=0 0 30 0,clip]{eval/EvoPCGRL_sokoban_ctrl-cellular_NCA_['emptiness', 'sol-length']_10-batch_100-pass_fixElites_5/reliability_fixLvls.png} \caption{\textbf{Sokoban levels, diverse along measures of emptiness and path-length.} Levels requiring the most lengthy solutions tend to be roughly half-empty, with obstacles arranged so as to demand significant back-tracking from the player.} \label{fig:sokoban_levels} \end{footnotesize} \end{figure} \subsection{Level quality \& diversity} In the maze domain, an archive of generators is optimized along measures of symmetry (horizontal and vertical) and path-length in the mazes they produce (Figure~\ref{fig:binary_levels}). After 50,000 generations, both \textbf{NCA} and \textbf{Decoder} architecutures, evolved with CMA-ME have filled out a considerable portion of the archive, and come close to maximum path-length zig-zags. These near-optimal levels tend to occur in a region of level-space with medium symmetry. But NCAs fill out more of the high-path-length extremeties of the archive, where generators tend to be less reliable along measures of interest, and often less diverse. These results suggest that generators building levels in an emergent manner through iterative local interactions are able to explore level-space more thoroughly than one-step generators with global information. Where Decoder and NCA archives overlap, NCAs produce levels with target metrics of interest more reliably, although limiting diversity in the process. In Zelda (Figure~\ref{fig:zelda_levels}), we search along measures of symmetry and path-length. The maximum path-length level is further out of reach of the archive of NCAs. However, CMA-ME has explored along an area of level-space with high symmetry, culminating in something like a two-lane version of the optimal zig-zag (top-right). In Sokoban (Figure \ref{fig:sokoban_levels}), an archive of generators is optimized to explore along measures of emptiness and solution length. Optimization first discovers small, valid corridors, then extends them to produce chambers of increasing complexity. Again, more complex generators tend to be more brittle. Intra-generator diversity among Zelda and Sokoban level-generators is considerably lower than among maze generators. This may be because designing Zelda levels involves more interrelated constraints than when designing mazes: moving a player, door or key will not just potentially affect symmetry, but also path-length. The reliability score may also be weighted too heavily. \section{Limitations and future work} In this work, the generators are optimized to produce levels with exactly the same values along measures of interest (Equation~\ref{eq:reliability}). This ensures that the resulting archive can produce levels whose features are controllable with high precision. But for the sake of the optimization process, it may also be desirable to treat this variance as a QD measure. Depending on the end-user's need for reliability, they could then select only sufficiently reliable generators from the final archive during actual level design. By instead treating reliability as an objective, we may be stifling search from discovering bridges to high-complexity areas of level space via unreliable but exploratory generators. As this work argues for the viability of NCAs as level generators, a direct comparison against other neural networks that have already been used to this end would be desirable. But the size of these latter networks makes covariance matrix adaptation of their weights computationally infeasible for methods like CMA-ME, as this matrix has size $n^2$, with $n$ equal to the number of parameters in the network. Future work might side-step this issue by using differentiable quality diversity (DQD)~\citep{fontaine2021differentiable}, which, given a differentiable genome, uses gradients to update a covariance matrix that instead only scales quadratically with the number of diversity measures. While the low parameter-count of NCAs is integral to the feasability of our approach, each NCA update only propagates local changes, leading to many steps needed to generate each level and the use of the intermediate levels as external memory. These dependencies, on episode length and the number of (one-hot) tile-types on the game-board, could in theory be foregone by applying the NCA's single $3\times 3$ convolutional layer repeatedly. In a similar vein, fractal neural networks with weight-sharing \citep{larsson2016fractalnet, earle2020using} incorporate stabilizing, structured skip connections, either without any new weights, or with new weights added logarithmically with respect to increases in the size of the model's perceptive field. In our experiments, we have compared NCAs with several neural network-based generator representations that were trained with versions of MAP-Elites. There are many other methods for generating 2D levels that we have not compared with, because they fundamentally solve a different problem, so that a fair comparison would not be possible. For example, we could have used MAP-Elites to evolve levels using a direct representation~\cite{alvarez2019empowering}, or in the latent space of a generator network~\cite{fontaine2021illuminating}, but this would have meant searching for levels instead of level generators. Conversely, one could learn level generators using for example Generative Adversarial Networks or WaveFunctionCollapse, but this would have required example levels to train on, and would not generate archives of multiple generators that differ along pre-specified measures. In fact, we are not aware of previous attempts at generating archives of \emph{generators} using QD algorithms. \section{Conclusion} We present a method for generating a diverse archive of level-generators represented as simple Neural Cellular Automata. The space of NCAs for growing levels is explored by CMA-ME along measures of interest (like symmetry or solution-length) in the levels they produce. Each generator in the archive is optimized to produce batches of valid levels with reliable features along these measures, with these batches of levels varying among themselves where possible. While NCAs are restricted to local computation, they propagate spatial information across the level while editing it sequentially to form patterns with global complexity. These NCAs are capable of satisfying high-level functional constraints and heuristics in mazes, and zelda and sokoban levels (producing, e.g. puzzles that require a certain number of steps for completion by an A* solver). Compared to models with global information (fixed-topology and mutable CPPNs, optimized with CMA-ME and MAP-Elites, respectively; and Decoders optimized with CMA-ME), NCAs facilitate a more thorough exploration of level space, and its individual generators have much more diverse outputs. The archive of level-generators produced by our method have potential as co-creative tools, in which the human user might select from a archive of generators with diverse aesthetic and functional tendencies, perturbing their design process to dynamically explore the space of playable levels. They could also work for Experience-Driven Procedural Content Generation, where generators are chosen from an archive to produce a target experience for a particular induced player profile~\cite{yannakakis2011experience}. They may also be used to generate automatic curricula of game levels for training player-agents. To this end, our method explicitly incentivizes both the reliability of the generator along measures of interest, and the generation of diverse levels at each point in level-space. This could help increase the precision of the generated curriculum, and prevent a learning agent from over-fitting to any one difficult portion of the curriculum in which it would be fated to spend much of its time. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2022-02-21T02:06:35', 'yymm': '2109', 'arxiv_id': '2109.05489', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05489'}
arxiv
\section{Introduction} The Indy Autonomous Challenge (IAC) is an international competition, organized by Energy System Network (ESN), intended to promote the development of algorithms driving under challenging conditions. The IAC of 2020-2021 is the world first multi-vehicle, high speed, head-to-head autonomous race held on the Indianapolis Motor Speedway (IMS). Over 30 teams from universities around the globe participated in the challenge. \begin{figure}[ht]% \centering \subfloat[\centering ]{{\includegraphics[height=2.4cm]{"ims".jpg} }}% \subfloat[\centering ]{{\includegraphics[height=2.4cm]{"race_car".jpg} }}% \caption{(a) The Indianapolis Motor Speedway (b) the AV-12 autonomous race car.}% \label{fig:ims_race_car}% \end{figure} The competition is carried out in two stages: a simulation race, and a real race on IMS with the Dallara AV-21, which reaches speeds of up to $300$ km/h and is based on a race car of the Indy Lights series. The official simulator for the IAC is the Ansys VRXPERIENCE simulator \cite{ansys_sim}, which simulates the AV-21 dynamics and the IMS track (see Fig. \ref{fig:simulation_close_look}). Prior to the competition, all teams were required to demonstrate autonomous control of a real vehicle (see \cite{kia_demonstration} for the demonstration submitted by our team). During the development period, which lasted $16$ months, there were three testing events that gradually led to the final simulation race. The simulation race is composed of four parts: solo laps, in which all vehicles drive alone; safety tests that validate the ability of each vehicle to avoid collisions and obey the race rules; semi-finals, in which the place in the grid is set according to the solo lap times; and the final race. \begin{figure}[ht] \centering \includegraphics[width=0.7\linewidth]{"simulation".png} \caption{The VRXPERIENCE simulator used for the simulation race.} \label{fig:simulation_close_look} \end{figure} \subsection{Challenges of autonomous racing} Autonomous racing has unique challenges, emanating from the unique properties of the race vehicle, its extreme speeds, and the competitive nature of the driving. \paragraph{Extreme speeds} Racing speeds coupled with limited frequencies of the sensor readings lead to state updates at large distance intervals compared to the vehicle size and the distance between neighboring vehicles. Furthermore, driving near the vehicle's performance envelope at close proximity to neighboring vehicles leaves little room for correction and hence requires high fidelity prediction of the behavior of the opponent vehicles. \paragraph{Competitive driving} Competitive driving forces the competitors to race at close proximity to opponent vehicles and to often block other vehicles from passing. As a result, the time difference between the leading teams is in the order of a fraction of a second. This in turn forces all competitors to drive on the performance envelop of the vehicle and the driver, leaving little room for safety. Although the goal is to win the race, in our opinion, especially at the first time that such head-to-head race is taking place, safer behavior and larger safety margins should be preferred over pushing the performance to the limits. \paragraph{Aerodynamics forces} The aerodynamics of a race car has two main effects: a down-force that increases the tire grip and lets the car reach a lateral acceleration of over $2.5g$, which allows driving at maximal speeds along an oval track. The second effect is a slipstream, or draft, which reduces the drag on the following vehicle. This allows vehicles of identical dynamics to overtake each other. The racing rules \cite{INDY_rules} are derived from the rules used in human-driven races. An important principle is that an overtaking vehicle is responsible to avoid collision with a vehicle that is moving on its race line, while the overtaken vehicle is expected to maintain its own race line. In the simulated race, a vehicle is disqualified if it leaves the track. \subsection{Related Work} Unlike the IAC which is a head-to-head autonomous race, other autonomous racing competitions of full-size vehicles, traveling at high speeds, such as the formula student challenge \cite{formula_student} or Roborace \cite{roborace}, focus mainly on solo racing. In solo racing, since it is not required to attend to other vehicles, one must drive the vehicle along a time-optimal race line at time-optimal speeds. This was achieved using model predictive control (MPC) \cite{kabzan2020amz, liniger2015optimization} and reinforcement learning \cite{fuchs2021super,jaritz2018end}. Racing against multiple vehicles is more challenging than solo racing as it requires the online prediction of the trajectories of the neighboring vehicles, and the planning of a dynamically safe avoidance maneuver. A survey of early prediction methods is presented in \cite{lefevre2014survey}. An early approach to trajectory prediction uses Kalman filter assuming a constant velocity and acceleration \cite{ammoun2009real}. A more recent approach uses recurrent neural networks to predict multi modal distribution of future trajectories \cite{deo2018multi}. Two main approaches for driving in dynamic environments have emerged: one generates online control commands, whereas the other tracks a selected trajectory. Online control commands can be generated using MPC to repeatedly optimize a forward trajectory, while accounting for geometric constraints, moving opponent vehicles, and ego-vehicle dynamics. MPC was demonstrated in \cite{liniger2015optimization} to avoid static obstacles, and in \cite{liautonomous} to drive competitively in a head-to-head race with two vehicles. Another method to online generate control commands is based on the concept of Velocity Obstacles (VO), which maps static and dynamic obstacles (e.g. opponent vehicles) to the velocity space of the ego vehicle \cite{fiorini1998motion,shiller2001motion}. This allows an efficient selection of a collision free velocity that avoids an arbitrary number of vehicles. The second approach for driving in dynamic environments divides the driving task into two simpler sub-tasks: first plan a trajectory, then track this trajectory using a tracking controller. The trajectory planner can be simplified by using a simple dynamic model to compute a collision free trajectory. The tracking controller then tracks the trajectory without considering the obstacles. The trajectory can be computed using a graph search in a spatiotemporal lattice \cite{mcnaughton2011motion}, in a spatial lattice \cite{sun2020feedback}, or by an RRT* (Rapid Random Tree) search \cite{rrt_star}. Trajectory tracking can be accomplished using simple geometric controllers or more complex controllers that takes the vehicle dynamics directly into account \cite{snider2009automatic}. \subsection{This paper} The autonomous racing controller, developed by ``Ariel Team'', was developed under the underlying principle, which must guide all developers of autonomous vehicles, that emphasizes safety over performance. To this end, our controller attempted to avoid collisions, even if the race rules placed the responsibility to avoid the collision on the opponent vehicle. The racing controller is based on a repeated search for the locally best maneuver that avoids collisions with opponent vehicles, attempts to follow the globally optimal race line, and obeys the race rules. A set of local maneuvers are generated at $25Hz$, using a point mass model from the current state to a small set of discrete points along the track. At each step, the selected maneuver is tracked using pure-pursuit and a proportional velocity controller. Our approach resembles the approach used in \cite{urmson2008autonomous, li2015real} for urban driving. It is interesting to note that despite its simplicity, our controller demonstrated competitive driving while overtaking other vehicles, staying within a close range of the leading vehicle, and not being involved in any collision throughout the race. Furthermore, our vehicle maintained the 3\textsuperscript{rd} place for a major part of the semi-finals and the finals. We ended up getting off the track, with 3 laps to go, while avoiding a vehicle that entered our safety bound. This placed us 6\textsuperscript{th} in the final simulation race. \section{Software Architecture} \begin{figure}[ht] \centering \includegraphics[width=\linewidth]{"architecture".pdf} \caption{Software Architecture.} \label{fig:architecture} \end{figure} The software architecture is shown schematically in Fig \ref{fig:architecture}. For a given track map, we first compute an optimal race line, offline, which will serve us throughout the race. The data from the cameras and radars provide the position and velocity of the surrounding opponent vehicles, and additional simulated sensors provide the ego-vehicle state e.g., position and velocity. These data, together with the map and the optimal race line, are used by the prediction module to repeatedly predict future trajectories of the opponent vehicles. The same information is used by the trajectory planner to plan an optimal local maneuver for the ego-vehicle. This maneuver serves as an input to the trajectory-following controller, which computes the desired linear and angular velocities of the ego-vehicle. The linear and angular velocities are controlled by the velocity controller which outputs the steering, throttle and brake commands. \section{Computing the optimal race line} The optimal race line is a time optimal trajectory computed offline, based on the track geometry and vehicle dynamics. The IMS is an oval track, $2.5$ miles ($4,023$ m) long, as depicted in Fig. \ref{fig:map}. We computed the optimal race line using an open-source trajectory optimization software, \cite{TUMFTM}. The optimal race line, typically maximizes the radius of curvature by entering the corner on the outside boundary of the track, passing through the apex on the inner boundary, to the exit point on the outside boundary, as shown in Fig. \ref{fig:offline_trajectory}. \newcommand{4.3cm}{4.3cm} \begin{figure}[ht]% \centering \subfloat[\centering ]{{\includegraphics[height=4.3cm]{"map1".pdf} }\label{fig:map} }% \subfloat[\centering]{{\includegraphics[height=4.3cm]{"corner3".png} }\label{fig:corner}}% \caption{(a) The IMS track. (b) The optimal race line around a corner of the track.}% \label{fig:offline_trajectory}% \end{figure} \section{Online Trajectory Planning} \label{sec:trajectory_planning} The online trajectory planner computes a collision free trajectory at $25$ Hz with a planning horizon of $200$ m. It is used as a reference for the trajectory following controller (see Section \ref{sec:control}). The planner first generates $8$ dynamically feasible maneuver candidates, then selects the best candidate that maximizes progress along the path and avoids collision with the opponent vehicles. Since the planning horizon of is limited to $200$ m, and the typical driving speed is over $80$ m/s, the time horizon is less than $3$ seconds. The small number of maneuver candidates, generated at $25Hz$, and the short time horizon, sufficiently span the set of options of possible feasible maneuvers, as demonstrated in the simulation runs presented later in Section \ref{sec:Experiments}. \subsection{Coordinate system} An ego-vehicle- and road-aligned coordinate system is used for planning, such that $x$ axis is tangent to the left track boundary and the $y$ axis is normal to track. The position of the ego-vehicle is denoted as $(x_e,y_e)$; since the coordinate system is aligned with the ego-vehicle, the ego-vehicle is always located at $x_e = 0$. $y_e$ represents the ego-vehicle's normal shift from the left boundary. (see Fig. \ref{fig:coordinates}). \begin{figure}[H] \centering \includegraphics[width=0.5\linewidth]{"coordinates".png} \caption{Road-aligned coordinate system.} \label{fig:coordinates} \end{figure} In our coordinate system for every point $(x_i,y_i)$, $|x_i|$ represents the distance from the ego-vehicle along the track (a negative $x_i$ represents a point behind the ego-vehicle), and $y_i$ represents the shift from the boundary regardless of the track shape and the ego-vehicle's location. \subsection{Computing a trajectory between two point \label{maneuver_planning} In this section, we explain how two trajectory points (a start point and a goal point) are connected to form a trajectory based on the time-optimal motion of a point-mass model. This method is used for opponent vehicles trajectories predictions and planning maneuver candidates for the ego-vehicle. Let $p_s = \{x_0,y_0,\dot{x}_0,\dot{y}_0\}$ be the start point, and let $p_g = \{x_g,y_g,\dot{x}_g,\dot{y}_g\}$ be the goal point. We plan a trajectory $C(t) = \{x(t),y(t),\dot{x}(t),\dot{y}(t)\}, \ t\in[0,T]$ that connects the start point with the goal point, i.e, $C(0)=p_s$ and $C(T)=p_g$. For composing the trajectory we first assume that $\dot{x}_s=\dot{x}_g$, i.e, the starting velocity (in the $x$ axis) equals the goal velocity, and later re-adjust the velocity. Therefore, the final time $T$ is: \[T = \frac{x_g - x_0}{\dot{x}_0}.\] $C$ is created by applying a bang-bang lateral force with a single switch point on a point mass $m$, similar to \cite{shiller1998emergency}. Let $F_y$ be a force, such that: \[F_y = \frac{-\sqrt {2A}-T(\dot{y}_g + \dot{y}_0)+2(y_g - y_0)}{T^2m}\] where, $A = (T^2 (\dot{y}_0^2 + \dot{y}_g^2) -2T(y_g - y_0)(\dot{y}_g + \dot{y}_0)+2{(y_g - y_0)}^2)$. The bang-bang lateral force is applied in one direction until a switching time, $T_s$, and then the force is applied in the opposite direction, i.e., $F_y$ is applied for $t=[0,T_s]$ and $-F_y$ is applied for $t=(T_s,T]$. \[T_{s} = \frac{ m(\dot{y}_g - \dot{y}_0) +F_yT}{2F_y} \] Finally, $C(t)$ is computed for $t \in[0,T]$ by: \begin{align*} x(t) &= \dot{x}_0 t \\ y(t) &= \left\{ \begin{matrix} \dot{y}_t + \frac{1}{2}\frac{F_y}{m}t^2 \\ \\ \dot{y}_0t - \frac{1}{2}\frac{F_y}{m}t^2 \\ \end{matrix}\begin{matrix} \ \ \ t < T_{s} \\ \\ \ \ \ t > T_{s} \\ \end{matrix} \right. \\ \dot{x}(t) &= \dot{x}_0 \\ \dot{y}(t) &= \left\{ \begin{matrix} \dot{y}_0 + \frac{F_y}{m}t \\ \\ \dot{y}_0 + \frac{F_y}{m}(2T_{s} - t) \\ \end{matrix}\begin{matrix} \ \ \ t < T_{s} \\ \\ \ \ \ t > T_{s} \\ \end{matrix} \right. \end{align*} \newcommand{2.4cm}{2.4cm} \begin{figure}[h]% \centering \subfloat[\centering ]{{\includegraphics[height=2.0cm]{"path_with_points".png} }}% \qquad \subfloat[\centering ]{{\includegraphics[height=2.65cm]{"F".png} }}% \subfloat[\centering ]{{\includegraphics[height=2.4cm]{"vel".png} }}% \qquad \caption{A trajectory between given start and goal points. (a) Force $F_y$ is applied on mass $m$ to create a continuous trajectory between the points. (b) The lateral force $F_y$ profile and (c) the lateral velocity $\dot{y}(t)$.}% \label{fig:point_mass_trajectory}% \end{figure} Fig. \ref{fig:point_mass_trajectory} illustrates an example of a trajectory that connects two points. \subsection{Opponents vehicles' trajectory prediction} An important part of motion planning in a dynamic environment and especially in racing is to predict the future positions and velocities of all the other vehicles surrounding the ego-vehicle. Therefore, we develop a prediction module, which given opponent vehicle state $s$ that contains position $x_o,y_o$, velocity $\dot{x}_o,\dot{y}_o$ and angular velocity $\omega_o$, predicts the future trajectory $J(t) = \{x(t),y(t), \dot{x}(t),\dot{y}(t) \}$ up to a predefined time horizon $T_{max}$, which we set to $3$ seconds. Our prediction module first predicts other vehicles future trajectory by assuming that they retain their current steering and then updates its prediction according to the track boundaries. Namely, for a given opponent vehicle, we first predict a future trajectory, $\hat{J}$, that keeps a constant curvature $\kappa$, which we approximate by: $\kappa = \frac{\omega_o } {||\dot{x}_o+\dot{y}_o||}$. However, it is expected that the opponent vehicle will consider the track boundaries and will avoid exceeding them. Therefore, our prediction module also takes the track boundaries into account and uses the following method. Let $(\hat{x},\hat{y})$ be the first position on $\hat{J}$ in which the opponent vehicle approaches one of the boundaries and is only a distance of $d_{min}$ from it. We define three trajectory points, $p_0$, $p_1$ and $p_2$ as described hereunder, where each trajectory point is composed of $p_i=\{x_{p_i},y_{p_i},\dot{x}_{p_i}, \dot{y}_{p_i}\}$; the prediction module connects them by a point mass maneuver as explained in Section \ref{maneuver_planning}. The first trajectory point, $p_0$ is derived from the opponent vehicle's current state $s$, such that $x_{p_0} = x_o$ ,$y_{p_0} = y_o$, $\dot{x}_{p_0} = \dot{x}_o$, and $\dot{y}_{p_0} = \dot{y}_o$. The second trajectory point, $p_1$, is based on $(\hat{x},\hat{y})$, but we assume that the opponent vehicle will not increase its curvature; therefore, we assume that $\hat{y}$ will be reached later on, by a predefined factor, $k$. That is, $x_{p_1} = (\hat{x}-x_o) k, y_{p_1} = \hat{y}, \dot{x}_{p_1} = \dot{x}_o, \dot{y}_{p_1} = 0\}$. The third trajectory point, $p_2$ retains the lane parallel to the boundary up to $T_{max}$, i.e., $x_{p_2} = \dot{x}_o T_{max}$, $y_{p_2} = \hat{y}$, $\dot{x}_{p_2} = \dot{x}_o$, and $\dot{y}_{p_2} = 0\}$. Examples of predicted trajectories are shown in Fig. \ref{fig:prediction}. \begin{figure}[ht] \centering \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.6\linewidth]{"prediction_with_points".png} \caption{} \label{fig:prediction_change_lane} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.6\linewidth]{"prediction_follow_curve".png} \caption{} \label{fig:prediction_follow_curve} \end{subfigure} \caption{Predicted trajectories of an opponent vehicle (marked as an orange bounding box). Black indicates constant curvature trajectory $\hat{J}$, and yellow indicates $J$, which considers the track boundaries. In (a) $\hat{J}$ exceeds track boundaries; therefore, a lane-changing trajectory is predicted by $J$; in (b) although the vehicle drives on a straight line, a lane-keeping trajectory is predicted by $J$.} \label{fig:prediction} \end{figure} We note that our method for trajectory prediction assumes that other vehicles follow a smooth motion profile. The justification for this assumption relies on the fact that in time horizon, when traveling at high velocity, and since the racing rules prohibit sudden changes of racing lines, other vehicles are likely to continue their motion profiles. \subsection{Creating maneuver candidates} The online trajectory planner plans a set of dynamically feasible maneuver candidates and selects one of them according to multiple criteria, as follows. \subsubsection{Lane change maneuver} \label{sec:lane_changing_maneuver} Given ego-vehicle's state $s_e=\{x_e,y_e,\dot{x}_e,\dot{y}_e\}$ and a lateral target $\hat{y}$, which defines the target lane, the planner module creates a lane change maneuver, $C^{\hat{y}}$, by connecting the following three trajectory points, $q_i=\{x_{q_i},y_{q_i},\dot{x}_{q_i}, \dot{y}_{q_i}\}$, where $i\in \{0,1,2\}$, as described in Section \ref{fig:maneuver_planning}. $q_0$ is derived from ego vehicle's current state $s_e$, such that $q_0 = s_e$. The second point defines the lateral distance of the desired lane $\hat{y}$ and the longitudinal lane-changing distance that depends linearly on the lateral changing distance $(\hat{y} - y_e)$ by a predefined factor $b$ and predefined constant $c$. That is, $x_{q_1} = \{(\hat{y} - y_e) b + c, y_{q_1} = \hat{y}, \dot{x}_{q_1} = \dot{x}_e, \dot{y}_{q_1} = 0\}$. The third trajectory point, $q_2$ retains the lane parallel to the boundary up to a maximal longitudinal distance $x_{max}$, i.e., $x_{q_2} = x_{max}$, $y_{q_2} = \hat{y}$, $\dot{x}_{q_2} = \dot{x_e}$, and $\dot{y}_{q_2} = 0\}$. Fig. \ref{fig:change_lane} illustrates a lane change maneuver. \begin{figure}[ht] \centering \begin{subfigure}{0.5\linewidth} \centering \includegraphics[width=\linewidth]{"lane_change".png} \caption{} \label{fig:change_lane} \end{subfigure}% \begin{subfigure}{0.5\linewidth} \centering \includegraphics[width=\linewidth]{"maneuver_to_optimal".png} \caption{} \label{fig:to_optimal} \end{subfigure} \caption{Illustration of the maneuver candidates planning: (a) lane change maneuver and (b) a maneuver to the optimal race line. } \label{fig:maneuver_planning} \end{figure} We define $N$ equally spaced lanes, with zero width, which represent potential $\hat{y}$ values. The first and last lane are far enough from the boundaries to allow a vehicle to follow them safely. Our planner generates $N$ lane change maneuvers, one for each defined lane. Let $\mathbf{M'}$ be the set of all lane change maneuvers. More formally, \[\mathbf{M'} = \bigcup\limits_{i=0}^{N-1} C^{{\hat{y}}_i}, \ \hat{y}_i = d_{min}+\frac{w - 2d_{min}}{N-1}i\] where $d_{min}$ is the minimal distance to keep from track boundaries. The width of the track in most segments is $14$ m; we set $N = 7$ to achieve a distance between lanes, that is close to the vehicles width ($2$ m). \subsubsection{Maneuver to the the optimal race line} In addition to these lane-changing maneuvers, we plan a maneuver ${C}^{J_{opt}}$, which smoothly merges with the optimal race line $J_{opt}$. We define the following three trajectory points $\tilde{q}_i=\{x_{\tilde{q}_i},y_{\tilde{q}_i},\dot{x}_{\tilde{q}_i}, \dot{y}_{\tilde{q}_i}\}$, where $i\in \{0,1,2\}$. The first trajectory point $\tilde{q}_0 = s_e$; the second, $\tilde{q}_1\in J_{opt}$ such that $\{(y_{\tilde{q}_1} - y_e) \tilde{b} + \tilde{c} = x_{\tilde{q}_1}$, where $\tilde{b}$ and $\tilde{c}$ are predefined constants. Finally, $\tilde{q}_2\in J_{opt}$ such that $x_{\tilde{q}_2} = x_{max}$. See Fig. \ref{fig:to_optimal}). The full set of the maneuver candidates is $\mathbf{M} = \mathbf{M'} \cup C^{J_{opt}}$, as shown in Fig. \ref{fig:optional_trajectories}. \begin{figure}[ht] \centering \includegraphics[width=\linewidth]{"optional_maneuvers_short_all".png} \caption{Example of 7 lane-changing maneuvers (green) and a maneuver that merges with the optimal race line (blue). } \label{fig:optional_trajectories} \end{figure} \subsection{Velocity re-planning} Although the maneuver candidates $\mathbf{M}$ and the predicted trajectories of the opponent vehicle include velocities in addition to positions, these velocities were only used to define the direction of the paths and to estimate the lateral forces on the vehicle. Therefore, the velocity profiles are re-planed to more accurately represent the future motion, by assuming that the vehicles accelerate along the trajectories until reaching the maximal velocity. This is possible since our planned trajectories approximate the vehicle dynamics and thus, allow maintaining maximal velocity---without losing control---when following them. \subsection{Collision} To avoid a collision, due to the uncertainly inherent to our problem, we define a safety bound around the vehicle. We attempt not only to avoid a collision with another vehicle but also to avoid any overlap between the safety bounds around both vehicles. We use a rectangular safety distance; we define the longitudinal safety bound as $0.3$ of the vehicle length both front and rear, and the lateral safety distance as $0.5$ of the vehicle width, right and left. This results in keeping a longitudinal safety bound of $0.6$ of a vehicle and a lateral safety bound of an entire width of a vehicle. We note that, while a circular safety bound is more convenient because the yaw angles of the vehicles are indifferent, since the length of the race car is more than double its width, a circular safety bound would not fit well to the vehicle's shape. Since the slip angles are small, the yaw angles, of the vehicles is approximated by the angle of vehicle's velocity vector. Two trajectories $C_1$ and $C_2$ describe a collision if there exists some $t$ that the safety bounds of both associated vehicles at time $t$ overlap. See Fig. \ref{fig:future_collision} for an illustration. A maneuver candidate is considered \emph{free} if it does not collide with a predicted trajectory of any opponent vehicle. However, if an opponent vehicle is directly behind the ego-vehicle, and the ego-vehicle blocks it, our controller ignores it, since it is the opponent vehicle's clear responsibility to avoid a collision. \begin{figure}[ht] \centering \begin{subfigure}{0.5\linewidth} \centering \includegraphics[width=\linewidth]{"future_collision3".png} \caption{} \label{fig:future_collision1} \end{subfigure}% \begin{subfigure}{0.5\linewidth} \centering \includegraphics[width=\linewidth]{"future_collision4".png} \caption{} \label{fig:future_collision2} \end{subfigure} \caption{Two trajectories describing the location of each vehicle and its safety bounds. In (a) the vehicles collide at time $t_6$; in (b) the vehicles do not collide since the overlap of their safety bounds is at different times.} \label{fig:future_collision} \end{figure} \subsection{Maneuver selection} Our planner considers all maneuver candidates that are free. Nevertheless, maneuver candidates that anticipated collision with a vehicle when proceeding at maximal velocity, are updated and their velocity is controlled so they do not collide, if possible (See Fig. \ref{fig:updated_velocity}). \begin{figure}[ht] \centering \includegraphics[width=0.9\linewidth]{"updated_velocity1".png} \caption{Updating a maneuver candidate to become free by decelerating toward a blocking vehicle that drives at a velocity of $v_2$ (green), instead of accelerating to the maximal velocity, $v_{max}$ (red), and causing a collision.} \label{fig:updated_velocity} \end{figure} If more than one maneuver is free, each maneuver is associated with a cost based on the following criteria; the maneuver with the lowest cost is selected. \subsubsection{Maneuver expected time} The time each maneuver is expected to take until reaching the planning horizon. For maneuver $C$, we use $\mathcal{T}(C)$ to denote this time. For example, consider two maneuvers, $C$ and $C'$, where $C$ is shorter than $C'$, possibly because $C'$ contains lane changing. If the velocity along $C$ and $C'$ is equal, then $\mathcal{T}(C) < \mathcal{T}(C')$. However, if $C$ is blocked by another vehicle which requires decelerating along that path to avoid the collision, it might be that $\mathcal{T}(C) > \mathcal{T}(C')$. \subsubsection{Closest maneuver to the optimal trajectory} The maneuver with the lowest expected time is only locally optimal since the short-horizon maneuver candidates are compared, but the global optimality is not considered. Incorporating global optimality into the maneuver candidates would require predicting and planning to an extended range, which would require extensive computing power and would raise uncertainty. To partially account for global optimality, the planner prefers maneuvers that come close to the optimal race line, which is global optimal---without considering other vehicles. To encourage the selection of a maneuver that is the closest, among the free candidates, to the optimal race line, that maneuver obtains a reward $R_{o}$, which controls the trade-off between local time optimality and following the optimal race line. That is, for a maneuver $C$, let $\mathcal{O}(C)$ be $R_{o}$ if $C$ is closest, among the free candidates, to the optimal race line, and $0$ otherwise. \subsubsection{Minimum change from the current trajectory} The selected maneuver can change significantly at every time step when the optimality of two maneuver candidates is similar. To stabilize the planning, it is preferred, when possible, to keep the same maneuver, unless another maneuver is conspicuously better. Clearly, switching to a new maneuver is more severe if a switch has just occurred, but once some time has passed since the last switch, the controller should be more lenient towards another switch. For a maneuver $C$, let $\mathcal{K}(C)$ be $R_{k}$ if $C$ is the same maneuver as the maneuver that the vehicle currently drives on, and $0$ otherwise. $R_{k}$ drops with a linear decay rate $R_{d}$ as long as the maneuver is followed, and is reset to its initial value $R_{{k}_0}$ if the maneuver is switched. Finally, the cost associated with each free maneuver $C\in \mathbf{M}$ is $\mathcal{T}(C)-\mathcal{O}opt(C)-\mathcal{K}(C)$. The maneuver with the minimal cost is selected. Fig. \ref{fig:trajectory_choice} a,b,c show examples of selected maneuvers. \begin{figure}[ht] \centering \begin{subfigure}{\linewidth} \centering \includegraphics[width=\linewidth]{"min_time_overtake_short".png} \caption{} \label{fig:min_time_overtake_short} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=\linewidth]{"from_left_to_optimal".png} \caption{} \label{fig:from_left_to_optimal} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=\linewidth]{"closest_to_optimal".png} \caption{} \label{fig:closest_to_optimal} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=\linewidth]{"all_blocked".png} \caption{} \label{fig:all_blocked} \end{subfigure} \caption{Maneuver selection examples, green: free maneuvers, red: blocked maneuvers, blue: chosen maneuver. (a) The planner selects a minimum-time lane-changing maneuver because the current lane is blocked by another vehicle. (b) The planner prefers the longer maneuver because it returns to the optimal race line (shown in light-blue). (c) The planner selects a free maneuver that is the closest to the optimal race line . (d) None of the maneuver candidates are free, therefore the safest maneuver is chosen.} \label{fig:trajectory_choice} \end{figure} \subsection{Behavior when no maneuver is free} Situations in which none of the Maneuvers are free are unavoidable due to the unpredictable behavior of other vehicles and inaccurately modeled ego-vehicle dynamics. If none of the Maneuvers are free, the optimality criteria are not relevant and the only selection criterion is safety. To find the safest maneuver the planner finds the closest collision and selects a maneuver that is as far as possible from that collision (see an example at Fig. \ref{fig:all_blocked}). \section{Control} \label{sec:control} The control module outputs throttle, brake, and steering commands that drive the vehicle as close as possible to the selected maneuver. \subsection{Lateral control} The pure pursuit algorithm \cite{pure_pursuit} is used to compute the desired angular velocity based on the current ego-vehicle's state and the selected maneuver, which is mapped to Cartesian coordinates. The pure pursuit algorithm pursuits a target on the selected maneuver $C$. Let $\mathbf{v}$ be the vector representing the ego-vehicle's velocity. The distance to the target is defined to be proportional to the vehicle's speed $v = |\mathbf{v}|$ that is, $l_d = vk_t$, where $k_t$ is a predefined constant. The angle between the velocity vector $\mathbf{v}$ to the vehicle-target vector is denoted as $\alpha$ (see Fig. \ref{fig:pure_pursuit}). The desired angular velocity of the vehicle $\omega_d$ is $\frac{2v\sin{\alpha}}{l_d}$. \begin{figure}[t] \centering \includegraphics[width=0.35\linewidth]{"pure_pursuit".png} \caption{Pure pursuit geometry.} \label{fig:pure_pursuit} \end{figure} The desired angular velocity $\omega_d$ is used as a reference for a proportional angular velocity controller that computes the steering command: $\delta = (\omega_d - \omega)k_{\omega}$ where, $\omega$ is the current angular velocity of the vehicle, and $k_{\omega}$ is a proportional gain. \subsection{Longitudinal control} The desired speed $v_d$ is provided by the selected maneuver, which is usually used as a reference for the longitudinal controller. However, when closely following a vehicle, we modify the desired speed to be: $v_d = v_f - (L_d - L)k_f$, where $v_f$ is the speed of the leading vehicle, $L$ is the distance to the leading vehicle, $L_d$ is the desired distance to keep, and $k_f$ is a proportional gain. This modification allows smooth driving and keeping a constant distance from the leading vehicle. Fig. \ref{fig:following} illustrates a following scenario. \begin{figure}[ht] \centering \includegraphics[width=0.5\linewidth]{"following_controller".png} \caption{Following a vehicle. The distance between the ego-vehicle and the vehicle ahead, $L$, is less than the predefined following distance, $L_d$; therefore, the ego-vehicle will slow down, to increase $L$. } \label{fig:following} \end{figure} Finally, the throttle and brake command $u$ is computed by a proportional speed controller: $u = (v_d - v)k_v$ where, $k_{v}$ is a proportional gain. \section{Experiments} \label{sec:Experiments} \subsection{Simulation environment} The VRXPERIENCE simulator enables multi-vehicle head-to-head competitions, in which every vehicle is controlled by a separate controller. The sensors are simulated at $25$ Hz and the ego-vehicle's state at $100$ Hz, in simulator time. Each controller receives the ego-vehicle's state and the sensor data from the simulator, and sends back throttle, brake, and steering commands. We used the pre-processed cameras and radars data from the simulator to obtain the position and linear and angular velocity of all vehicles in the sensors range. We based our controller on Autoware.auto \cite{Autoware} which is an open-source autonomous driving framework that uses ROS2 as middleware. The computation time of our algorithm is $20$ milliseconds, on average, on an Intel Core i7 $2.90$ GHz CPU, which enables our algorithm to run in real-time. We note that running in real time was not a requirement for the simulation race, and therefore, it might be that other teams' algorithms required longer computation time. A video demonstrating our controller is available at \cite{summary_video}. \subsection{Simulation results} We tested our controller by competing between multiple instances of our controller. Clearly, every controller instance has information only from its vehicle sensors and operates independently from the other controllers. % During our testings, all vehicles, which were using our controller, drove safely and respected the race rules; a collision or loss of control were never experienced. However, since different controllers can drive more aggressively and keep a smaller safety area, which is not observed when all controllers prioritize safety and drive more conservatively, testing with identical controllers does not ensure safe driving when competing against different controllers. Fig. \ref{fig:6_ego} shows an example of the black vehicle's planner in a crowded 6-vehicle environment. Since following vehicles can exploit the slipstream, it is possible for them to overtake their leading vehicles. Indeed, this phenomenon happened during our testing, despite all vehicles using the same controller. Fig. \ref{fig:takeover_trail} demonstrates an overtake maneuver with $3$ vehicles, all using our controller. At every corner, the black vehicle gains a small advantage over the blue vehicle until it successfully completes the overtaking maneuver. \newcommand{3.5cm}{3.5cm} \begin{figure}[ht]% \centering \subfloat[\centering ]{{\includegraphics[height=3.5cm ]{"6_ego_a".png} }}% \subfloat[\centering ]{{\includegraphics[height=3.5cm ]{"6_ego_b".png} }}% \caption{Snapshots of planning in a crowded scenario with $5$ opponent vehicles.}% \label{fig:6_ego}% \end{figure} \newcommand{4.4cm}{4.4cm} \newcommand{4.0cm}{4.0cm} \begin{figure}[ht]% \centering \subfloat[\centering ]{{\includegraphics[width=4.4cm]{"takeover_trail/trail_1".png} }}% \subfloat[\centering ]{{\includegraphics[width=4.0cm]{"takeover_trail/trail_2".png} }}% \subfloat[\centering ]{{\includegraphics[width=4.4cm]{"takeover_trail/trail_3".png} }}% \subfloat[\centering ]{{\includegraphics[width=4.0cm]{"takeover_trail/trail_4".png} }}% \subfloat[\centering ]{{\includegraphics[width=4.4cm]{"takeover_trail/trail_5".png} }}% \subfloat[\centering ]{{\includegraphics[width=4.0cm]{"takeover_trail/trail_6".png} }}% \caption{An example of an overtake maneuver during a race; the trails represent the last $0.8$ seconds. (a) The black vehicle initiates an overtake. (b) The black vehicle drives parallel to the blue and red vehicles. (c) The black vehicle prevents the blue vehicle from continuing on the optimal race line, i.e., reaching the apex. (d) The black vehicle gains a small advantage at the corner. (e) At the next corner, the blue vehicle is overtaken because it is forced to stay on the outside of the corner. (f) The black vehicle returns to the optimal race line.}% \label{fig:takeover_trail}% \end{figure} \subsection{Results of the IAC simulation race} Only $16$ teams reached the simulation race, as some of the teams were disqualified and some teams joined together. Our solo lap time, $51.968$ seconds, placed us in 7\textsuperscript{th} place; the first place finished only a $0.12$ of a second ($0.23\%$) before us. The average result was $53.041$ seconds, placing us much closer to the first place than to the average. This result indicates the performance of the controller on the optimal race line. Only $10$ teams passed the safety tests and were qualified to proceed to the semi-finals. The semi-finals consist of a multi-ego, $10$-lap competition. The remaining teams were split into two heats, $5$ vehicles on each. We started in 3\textsuperscript{rd} place on our heat, based on the solo lap times. All vehicles finished without collisions or penalties, our vehicle finished in the 3\textsuperscript{rd} place, $0.44$ seconds ($0.0871\%$) after the winner, which finished in $504.988$ seconds. The average time was $506.7112$ seconds since the remaining teams finished more than $3$ seconds later. On the second heat, $3$ of the $5$ teams lost control or crashed, remaining with $7$ teams for the finals, in total. In the finals, our vehicle started in 5\textsuperscript{th} place, and overtook $2$ vehicles on the first lap. One team was disqualified due to crashing into another vehicle and the race was restarted with the $9$ remaining laps. Our controller demonstrated collision-free and competitive driving capabilities and was able to keep 3\textsuperscript{rd} place for a major part of the final race. $3$ laps before the race ended, a vehicle tried to overtake our vehicle and entered our safety area. Our collision avoidance action exerted a high braking force, in the course of a corner, which caused our vehicle to deviate from the track. Therefore, we completed the race in the 6\textsuperscript{th} place. The recording of the simulation race event is available at \cite{race_recording}. \section{Conclusions} In this paper, we described our controller for the Indy autonomous challenge simulation race. Our main principles guiding our design were safety and conservative collision free navigation, while remaining competitive and efficient. The online planner plans a set of simple, dynamically feasible, maneuver candidates based on the point mass model exerted with a lateral bang-bang force. Each maneuver candidate is checked for collisions with the predicted future trajectories of the opponent vehicles, and the fastest maneuver is selected. The maneuver selection algorithm also takes into account the optimal race line and prevents fluctuation. The trajectory following controller consists of a lateral and a longitudinal controller. The desired angular velocity is computed by the pure-pursuit algorithm; a proportional controller corrects the angular velocity by steering. The longitudinal proportional speed controller controls the desired velocity, which is computed based on the selected maneuver and blocking vehicles. Our controller demonstrated effective and collision free driving in the IAC simulation race. Our controller also demonstrated competitive driving by finishing only $0.44$ seconds after the winner which finished in $504.988$ seconds on the semi-finals and maintaining 3\textsuperscript{rd} place for a major part of the final race. We note that very few vehicles did not collide with any other vehicle; this emphasises the challenges of autonomous racing and the urgent need for additional research in complex autonomous driving. \bibliographystyle{IEEEtran.bst}
{'timestamp': '2021-09-14T02:20:16', 'yymm': '2109', 'arxiv_id': '2109.05455', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05455'}
arxiv
\section{Introduction} GPUs have been increasingly used in data-intensive workloads, such as databases~\cite{omniscidb} and graph processing~\cite{gunrock}. Therefore, enabling efficient GPU access to files and storage devices has become an important optimization goal. GPUfs~\cite{Silberstein-gpufs} is the recently introduced system infrastructure which allows GPU threads to access files directly from GPU kernels. GPUfs provides standard POSIX-like APIs (e.g., ({\tt read()}/{\tt write()}) for \emph{GPU threads} to perform file I/O, thus reducing the programming complexity, it implements a local page cache in the GPU memory, allows access to very large datasets and enables applications to perform data-driven, e.g., indexed-based, data accesses efficiently. GPUfs passes the I/O requests to the CPU, yet these remain invisible to the programmer, who only uses a standard and convenient I/O abstraction from GPU kernels. While prior works show impressive performance of GPUfs on a range of GPU workloads, we find that GPUfs is not as efficient for simple and most common I/O pattern -- streaming-like file access, where the whole file is streamed into the processing unit and sequentially processed chunk-by-chunk. We call this access \emph{sequential}, because this is how it would be implemented in CPU-only processing. Sequential pattern is among the most common. For example, it is employed in deep neural networks~\cite{cudnn} inference and training when reading the input dataset \cite{medium}. Such sequential access to data is very popular in high performance computing. In addition, I/O benchmark suites for manycore/multi-node architectures~\cite{ior} consider sequential access as one of the most popular in data-intensive applications. Unfortunately, using GPUfs for sequential accesses results in low I/O performance. Here, GPUfs API dictates that every GPU threadblock reads one file stride at a time in a data parallel manner, and then processes that stride in the threadblock. This access is similar to the one observed in multi-core and multi-node workloads~\cite{ior}, but results in hundreds of concurrent I/O accesses to the disk. Our analysis reveals a number of non-trivial performance problems emerging due to intricate interplay between the GPU I/O access pattern, the performance characteristics of the PCIe bus for CPU-GPU transfers, and the CPU OS readahead prefetching mechanism. In this work we show that these limitations are not inherent in GPUfs design, and demonstrate how to achieve high performance that is singificantly faster than the original design, and even exceeds the throughput of a commonly-used traditional CUDA-based \cite{cuda} baseline where files are accessed from the CPU code. The key to our optimization is \emph{a GPU-side I/O readahead prefetcher and page cache replacement mechanism}. Together they alleviate the GPUfs performance limitations, by adjusting the GPU I/O layer to match the characteristics of the operating system I/O mechanisms and PCIe. We integrate the prefetcher into GPUfs, and evaluate it using microbenchmarks and 14 applications derived from the RODINIA \cite{rodinia}, PARBOIL \cite{parboil} and POLYBENCH \cite{polybench} benchmark suites. We use an NVIDIA K40c GPU with an Intel P3700 SSD. With the integration of the readahead prefetcher, GPUfs achieves a $4\times$ (geometric mean) performance than the default GPUfs. End-to-end, the new GPUfs with readahead prefetcher achieves significant speedups for these applications, e.g. 82\% performance improvement on average (geometric mean) of the GPU I/O sequential read bandwidth compared to CPU I/O. The main contributions of this paper are as follows. \begin{itemize} \item Analysis and evaluation of the performance bottlenecks of the CPU-GPU heterogeneous I/O system stack. \item Integration of a readahead prefetcher mechanism into GPUfs. \item A new cache replacement mechanism for the GPU page cache which enables efficient operation of our GPU readahead prefetcher for files that are bigger than the available page cache size. \item Detailed evaluation on microbenchmarks and 14 standard benchmarks from the popular GPU benchmark suites, which show the performance gains of our GPU readahead prefetcher over the default GPUfs and the standard CPU I/O. \end{itemize} \section{Background} \label{sec:background} \subsection{System architecture} We consider a heterogeneous system with a CPU (or a host), a discrete GPU (or a device) and a fast NVMe SSD, all connected together through the PCIe bus. The CPU is connected with the host memory, and the discrete GPU is connected with its own physically separate device memory. \subsection{GPUfs} GPUfs is a software layer that provides native support for GPU file I/O. The GPU threads are able to access host files. GPUfs provides a POSIX-like API that is familiar to the programmers and abstracts away the low-level details of the hardware infrastructure. Figure \ref{fig:back:gpufs} illustrates a high-level view of GPUfs. \begin{figure}[h] \centering \centerline{\includegraphics[width=1\columnwidth, keepaspectratio]{images/gpufs.png}} \caption{\label{fig:back:gpufs}The GPUfs file I/O library and its execution flow} \end{figure} Each threadblock may issue an I/O request (read or write) by invoking a file I/O call from all its threads. The request may be served from three locations: from the SSD (e.g, via peer-to-peer DMA into GPU), the CPU page cache or in the GPU page cache. For clarity below we discuss only reads, and do not explain the peer-to-peer I/O because it is beyond the scope of our current work. See SPIN~\cite{spin} for more details. When a threadblock issues an I/O request, GPUfs divides the request into \emph{pages} stored in the GPU page cache. For every page, the GPU page cache is checked and if there is a hit, the data of the page are copied to the GPU application buffer. In case there is a miss, the threadblock submits a request to the shared CPU-GPU request queue (RPC in figure \ref{fig:back:gpufs}) and waits for the CPU thread to read the data from disk or the CPU OS page cache. Once the CPU completes the read, it sends the data to the GPU and signals the threadblock that the request has been served and the data is ready for use. After the threadblock receives the signal it copies the data to the page in the GPU page cache and to the user-level buffer. On the CPU, the host CPU threads poll the shared CPU-GPU request queue, which is logically divided between them. When a thread finds the request in the queue, it issues the corresponding {\tt pread()} OS call, one GPUfs page at a time. When the {\tt pread} completes, the host threads place the data in their staging buffers, and transfer them to the GPU, batching, opportunistically, multiple chunks together. \subsection{Linux Readahead Prefetcher} A common technique for optimizing I/O performance in sequential accesses is readahead prefetching. Linux implements a read-ahead prefetching mechanism that is capable of optimizing strided sequential accesses in multithreaded programs. The two main features that the Linux Readahead Prefetcher employs are the support of multiple streams per file descriptor and the asynchronous prefetching operation. For every file descriptor, there is an allocated readahead data structure which contains the basic information needed in order to determine the sequentiality of the read accesses and the prefetch size. The prefetcher works as follows. For a given file I/O request it first attempts to guess whether the application I/O access pattern is sequential, using a few heuristics. If it is, then the prefetcher issues an asynchronous I/O call of a larger size than the one requested by the user. In general, the size of the I/O request is doubled every time the access is considered sequential, until the size reaches a certain maximum read-ahead threshold. \textit{Support of multiple strides per file descriptor} A common I/O access scenario is when multiple threads access the same file in a strided manner. Thus, the Linux Readahead Prefetcher applies several heuristics in order to detect the sequential access pattern of all the running threads and maintain the efficiency of the readahead prefetcher, even when the threads use the same file descriptor. \section{Motivation} \label{sec:motivation} We run a simple experiment to evaluate the sequential I/O performance of GPUfs by using it to move 960MB file into GPU memory. The goal is to compare the effective I/O bandwidth that GPUfs can achieve with the bandwidth of reading the same file from the CPU (no data transfer to GPU). We expect that GPUfs would provide full pipe-lining and therefore achieve similar bandwidth. We run the GPU with 120 threadblocks, each 512 threads. Each threadblock reads 8MB stride using GPUfs. This configuration fully utilizes the GPU compute capacity, and represents the preferred way to read data into GPUs using GPUfs, as explored in prior work~\cite{Silberstein-gpufs}. GPUfs is configured with 4KB page size and 4 CPU threads for file system accesses. The CPU baseline also uses 4 threads to match the number of CPU threads in GPUfs. We observe that the CPU I/O bandwidth is almost 4x higher than the GPU I/O, and reaches 1.6GB/s. We thoroughly analyse the reasons for this discrepancy in the next sections. The goal of our analysis is two fold: (a) find the root causes of poor GPUfs performance (b) identify the opportunities for improvements. \subsection{Effect of GPUfs page size} \label{sec:motivation:putting} \paragraph{Sequential accesses} One important factor that significantly affects the system performance is the size of pages in the GPU page cache. That is because GPUfs page size dictates the size of accessing files, minimal block transferred over the PCIe, as well as GPUfs page cache management overheads. Thus, we seek to find the best GPUfs page size that would enable efficient sequential access. Figure \ref{fig:motiv:totalIO} shows that 64KB pages perform the best, and even exceeding the CPU I/O performance. \paragraph{Random accesses} On the other hand, increasing the page cache page size has negative impact on the performance of applications with non-sequential accesses that have been shown to be also important use-cases for GPUfs. To evaluate the performance impact of the page size in such applications, we run the Mosaic benchmark~\cite{activep} which creates an image collage from multiple tiny images fetched at input-dependent location from a large database (19GB). Each tiny image is 4KB. We run the application with GPUfs configured to use 4KB and 64KB pages. We observe that smaller pages result in \emph{45\% higher performance} compared to 64KB. This is a significant degradation that we seek to avoid. Note that some applications may exhibit mixed access pattern, whereas some files are accessed sequentially, and some are not. For example, in the collage application, the original picture used as the basis for the collage is read sequentially, whereas the tiny images are accessed in a complex data-dependent manner. Thus, our analysis below aims to understand the reasons for performance degradation with 4KB pages, and the rest of the paper relies on this analysis to overcome this limitation. \begin{figure}[t] \centering \includegraphics[width=0.45\textwidth, keepaspectratio]{images/totalIO.pdf} \caption{\label{fig:motiv:totalIO}The GPUfs sequential I/O performance for different GPU page sizes } \end{figure} \subsection{GPU I/O pattern and the OS I/O layer} \label{sec:motivation:io} We first focus on the interaction of GPU-generated I/O pattern with the file I/O layer on the CPU. Therefore, in this experiment we generate the I/O requests from the GPU kernel and send them to the CPU, however disable GPU data transfers and GPU page cache handling. Thus, we exercise the same GPU access pattern but without moving the data to the GPU. Therefore, the only difference between the CPU I/O baseline and the GPU I/O is the access pattern to storage. \begin{figure}[t] \centering \centerline{\includegraphics[width=1\columnwidth, keepaspectratio]{images/GPUvsCPU_onlyIO.png}} \caption{\label{fig:motiv:GPUvsCPU_onlyIO}GPU vs. CPU I/O bandwidth with PCIe transfers disabled.} \end{figure} Figure~\ref{fig:motiv:GPUvsCPU_onlyIO} shows the results. For requests smaller than 128KB the GPU I/O performance is 24\% better than the CPU I/O, however for requests above 128KB the CPU I/O bandwidth performance is on average 61\% higher, and 160\% higher for 128KB request size. Figure \ref{fig:motiv:gpuCPUWorkMap} illustrates the I/O request mapping from GPU threadblocks to the GPUfs host threads. We observe that the host threads serving GPUfs requests observe a random file access pattern. This is because the GPU threadblocks are invoked in a non-deterministic order, and thus place their I/O requests in the shared CPU-GPU request queue in some order that looks random to the CPU threads. When the I/O size is below 128KB, the Linux readahead prefetcher manages to recognize the sequentiality of the GPU I/O accesses and engages the readahead logic that causes larger reads from the storage. Moreover, for smaller reads the GPU I/O pattern enables more efficient use of the prefetched data. When a CPU thread issues sequential read requests as in Figure~\ref{fig:motiv:gpuCPUWorkMap}, certain requests collide with the request of the prefetcher, therefore they end up waiting for data to arrive. For example, consider the case in which a CPU thread reads 4KB data from offset 0. The prefetcher will issue a read I/O request that will fetch 16KB of data. The thread will be blocked for the first page (4KB) and the rest of the data will be fetched asynchronously. If the thread immediately reads additional 4KB (from offset 4K), the previous asynchronous I/O request by the prefetcher has not yet completed, thus the thread will block. With the I/O pattern of the GPU execution, the access to different file portions are interleaved. This interleaving enables the prefetcher to issue asynchronous I/O requests early enough such that by the time the data is accessed it is already in the page cache. On the other hand, for the accesses above or equal to 128KB, the GPU performance is much worse. However it cannot be explained by the interaction with the prefetcher, because 128KB is the maximum size of the read blocks issued by the prefetcher in the default Linux configuration. Therefore, if the poor performance were due to the prefetcher, it would remain low for accesses above 128KB, but it is not the case. \begin{figure}[t] \centering \centerline{\includegraphics[width=.7\columnwidth, keepaspectratio]{images/gpuCPUaddrMap.png}} \caption{\label{fig:motiv:gpuCPUWorkMap}The GPU I/O request mapping to the GPUfs host threads.} \end{figure} \subsection{GPU-CPU interaction} \begin{figure}[t] \centering \centerline{\includegraphics[width=\columnwidth, keepaspectratio]{images/GPUvsCPU_GPUioPatt.pdf}} \caption{\label{fig:motiv:GPUvsCPU_onlyIO_GPUpatt}GPU vs. CPU I/O bandwidth performance without PCIe data transfers included. CPU is accessing the file with the GPU I/O access pattern which was observed from the execution of the GPUfs host threads.} \end{figure} To isolate the influence of the file access pattern from the GPU-CPU interaction, we record the GPU I/O trace, and then replay it on the CPU without using the GPU. Namely, the CPU accesses the same file offsets as were accessed by the GPUfs host threads during GPU I/O. Figure \ref{fig:motiv:GPUvsCPU_onlyIO_GPUpatt} shows the difference between the GPU I/O bandwidth and the CPU I/O when the latter performs the same I/O pattern. As expected, the performance is nearly the same for accesses below 128KB. However, for the requests of 128KB and more, we observe that the performance of the GPU-initiated accesses is much worse. The main reason lies in the CPU-GPU interaction through the shared I/O queue. The four CPU threads serving GPU I/O requests periodically scan their own portions of the queue, but it turns out that some of them remain \emph{idle} because of the poor load balancing, and this idling occurs only for requests equal or grater than 128KB. Figure \ref{fig:motiv:spins} shows the waiting time (in millions of polling attempts) that each GPUfs host thread spends before it starts servicing its first request. We observe that threads 0 and 1 are busy (their bars are invisible), whereas threads 2 and 3 are idle for larger pages. The reason lies in the way GPUfs GPU threads assign work requests. When a threadblock issues an I/O request, it assigns the request to the slot of the shared queue based on its CUDA threadblock ID, to avoid contention for the queue slots. The shared queue has 128 slots, where each CPU thread polls its set of contiguous 32 slots. When the GPU is invoked with 120 threadblocks in our experiments, only 60 threadblocks fit the GPU at the same time (15SMs, maximum 2048 threads per SM). Therefore, in the beginning of the run the GPU I/O requests are served only by two CPU threads. The phenomenon affects more the requests with size equal or greater than 128KB. The reason lies in the I/O performance of the corresponding requests. For 64KB or less, the requests are executed faster and thus, the waiting time of the idle threads is less compared to the bigger requests. \begin{figure}[t] \centering \includegraphics[width=1\columnwidth, keepaspectratio]{images/spins.pdf} \caption{\label{fig:motiv:spins}The number of spins the GPUfs host threads make before they start servicing their first I/O requests} \end{figure} \subsection{PCIe data transfers} \label{sec:motivation:pci} To isolate the impact of PCIe data transfers from the file I/O, we perform the same experiment as above while the data is stored in memory in RAMfs \cite{ramfs}. Figure \ref{fig:motiv:pcie} shows, as expected, that larger page sizes perform much better than the small ones. This is in conflict with earlier observations that smaller pages benefit the system performance. \begin{figure}[h] \centering \includegraphics[width=\columnwidth, keepaspectratio]{images/pcie.pdf} \caption{\label{fig:motiv:pcie}The PCIe bandwidth performance of for the GPU microbenchmark} \end{figure} \subsection{Conclusions.} We seek to improve GPUfs performance with 4KB pages, and observe that the main bottleneck is the PCIe bus. Thus, the main optimization opportunity is to increase the size of PCIe transfers by \emph{prefetching} the data in advance into the GPU page cache in larger chunks. \section{The GPU I/O Readahead Prefetcher} \label{sec:GPUIO_design} \label{sec:design_considerations} \paragraph{GPU I/O readahead prefetcher in the CPU?} The location of the prefetch logic is an important design question. One option is to place the prefetcher on the CPU side. Thus, for every GPU I/O request, the CPU might move larger blocks to the CPU. This design, however, requires the CPU to be aware of the internal memory allocation in the GPU file system layer and the page cache, and is hard to implement without having PCIe support for atomic operations. Our design uses GPUfs itself to request larger chunks from the CPU, thereby allowing the on-GPU GPUfs logic to allocate memory, and ensure consistent access to data. This design is also similar to the way the OS prefetcher is implemented in the CPU. \paragraph{Asynchronous operation.} Performing prefetching asynchronously is a natural design choice. However, it is hard to combine it with the GPUfs PCIe transfer layer. In GPUfs, when the CPU completes the GPU read request, it transfers the data into a staging buffer in the GPU memory, and each threadblock retrieves the page that fulfills its own request as part of the GPU I/O call. The purpose of the GPU prefetcher is to move data to the GPU in larger chunks which include more pages in addition to the one in the request. Thus, by the time the GPU threadblock retrieves the requested page, the prefetched data is already in the GPU, hence the benefits of asynchronous prefetching are diminished. Thus, our design uses synchronous prefetching. \subsection{Design} Figure \ref{fig:design:gpuIOsystem} shows the main components of the GPU I/O system stack. The GPU I/O readahead prefetcher is part of GPUfs and it is primarily located in the GPU. In this section we illustrate the interaction of the GPU I/O readahead prefetcher with {\tt gread()} call in GPUfs. \begin{figure}[h] \centering \includegraphics[width=0.4\columnwidth, keepaspectratio]{images/gpuIOsystemStack.png} \caption{\label{fig:design:gpuIOsystem}The GPU file I/O system stack} \end{figure} \subsubsection{GPU-side mechanism} \begin{enumerate} \item Every threadblock has its own private buffer for holding the prefetched data. \item When a threadblock performs a gread(), it accesses the GPU page cache. \item If the data is there, it is used to fulfill the read request and the GPU execution continues. \item If there is a page cache miss, the threadblock allocates a new page and searches if the data is available in its private buffer. \item If the data is in its private buffer, it updates the page cache, returns the data to the user-level buffer and continues execution. \item If the data is not found in the private buffer, then the threadblock issues a read request to the CPU with size equal to GPUfs PAGE\_SIZE + PREFETCH\_SIZE (PREFETCH\_SIZE is static and is defined before execution). \item When the data is transferred back from the CPU, the threadblock updates the page cache with the 4KB page that is currently requested and the rest of the pages are placed in its private buffer. \end{enumerate} The CPU modifications required for the integration are mainly to enable the CPU handle the management of the multiple GPUfs page cache pages. When the corresponding pread finishes its execution, it returns the actual size of the data that has been loaded. The CPU thread, therefore, will examine how many GPUfs pages will be delivered to the GPU. The main operations are setting their metadata (e.g. size, offset per page) and placing the data in the staging buffer. \noindent{\bf Why per-threadblock private buffers?} The original version of GPUfs enables file accesses at threadblock-level granularity. Therefore per-threadblock private buffers made the design, implementation and integration of the GPU I/O readahead prefetcher more efficient. Additionally, the private buffer is a reasonable solution because it is quite likely that the same threadblock will access the prefetched pages. Last, having a private buffer eliminates the page cache contention among the threadblocks, thereby reducing the overhead of dealing with prefetching. In fact, our original design used the page cache as a prefetcher target instead of the private buffers, but it suffered from significant synchronization overheads. \noindent{\bf Lack of a global prefetching scheme.} The GPU I/O readahead prefetcher does not implement any synchronization mechanisms between the threadblocks for coordinated prefetching. Therefore, there is a possibility that different threadblocks may prefetch the same page if the access pattern is not sequential. However, coordinating the access among the threadblocks would incur significant performance penalty, as it would require synchronization between the threadblocks accessing the same page. Therefore, the user could disable in such cases the GPU I/O readahead prefetcher by using runtime hints like {\tt posix\_fadvise()}~\cite{fadvise} that is used for the CPU I/O readahead prefetcher. \noindent{\bf Warp-level prefetching.} The newest version of GPUfs \cite{data-driv-gpufs} enables the GPU threads to perform disk I/O at warp-level granularity. In that case, the GPU I/O readahead prefetcher design would have been modified. Warps should synchronize in order to access the shared per-threadblock private buffers or assign in each warp its own private buffer. Furthermore, a warp-level granularity prefetcher should be designed by taking into consideration that there would be needed less aggressive prefetching because the rate of concurrent I/O requests is higher. We do not address warp-level I/O in this work. \noindent{\bf Page cache coherency.} The prefetcher mechanism that relies on private buffers works correctly for read-only workloads. However, when the file is modified, this solution might result in a stale copy of the page in the private buffer. Specifically, if a given page is retrieved by multiple threadblocks at the same time (thus multiple copies reside in the private buffers of each accessing threadblock), then modified in the page cache by one of the threadblocks, and then evicted from the page cache, the copy still remaining in the private buffer of some threadblock will be wrong. One way to solve this problem is to maintain a global bit map of dirty pages in each file, updating it when pages get modified by the GPU. The respective bit is checked before accessing the private buffer in stage (5), discarding the locally-cached version if the page was modified. Our current implementation does not include this additional mechanism, however, because the vast majority of GPU workloads are read-only. Therefore, we enable prefetching for files opened in read-only mode, and disable it for writable files, allowing to optimize performance for the most common cases. We defer the complete implementation for future work. \section{Large files} Sequential access to files that exceed the (configurable) size of the GPUfs page cache results in severe thrashing of the GPU page cache and dramatic performance degradation (See the baseline performance in Figure~\ref{fig:eval:bigFiles}). Note that the use of 4KB pages amplifies the effects of the thrashing significantly, and cannot enjoy the benefits of prefetching. The straightforward solution of increasing the GPU page cache is not efficient due to the limited size of the GPU memory. Thus, it would not be a scalable solution that could be applicable for every case. \subsection{A new page cache replacement mechanism} Our new page cache replacement mechanism is optimized to avoid page cache management overheads for large files that are read sequentially. Our main idea is that each threadblock keeps its \emph{own} set of active pages. Assuming that when the data is accessed sequentially it will be used only once, each threadblock effectively performs local replacement mechanism. More specifically, each threadblock keeps its own Least Recently Allocated (LRA) queue of pages it allocates in the GPU page cache when reading a file. The queue is of a fixed size which is determined as the total size of the page cache divided by the number of actively concurrently running threadblocks (i.e., the number of threadblocks that reach maximum GPU occupancy.) Whenever the threadblock allocates a new page in the page cache, it adds the page to its list. When it runs out of pages, it evicts the least recently allocated page in its private list, and places there a new page, while remapping the page as necessary in the page table and re-inserting it into the head of the Least Recently Allocated queue. This mechanism entirely eliminates the synchronization overheads incurred in managing a global LRA queue shared among all the threadblocks, and does not require a page to be de-allocated and allocated again -- which is how it is implemented in the original GPUfs implementation. \section{Evaluation} \begin{table*}[t] \begin{center} \begin{tabular}{|l|l|l|} \hline \bf BENCHMARK & \bf NUMBER OF INPUT FILES AND SIZES & \bf I/O KERNEL CONFIGURATION \\ \hline HOTSPOT & 2 files, 1 GB each & 128 tblocks, 512 threads \\ \hline LUD & 1 file, 256 MB & 128 tblocks, 512 threads \\ \hline BACKPROP & total data read 3.25 GB & 128 tblocks, 512 threads \\ \hline BFS & 1 file, 1.1 GB & 128 tblocks, 512 threads \\ \hline DWT2D & 1 file, 768 MB & 128 tblocks, 512 threads \\ \hline NW & 2 files, almost 1 GB each & 100 tblocks, 512 threads \\ \hline PATHFINDER & 2 files, almost 1 MB and 952 MB & 100 tblocks, 512 threads \\ \hline STENCIL & 1 file, 1 GB & 128 tblocks, 512 threads \\ \hline 2DCONV & 1 file, 1 GB & 128 tblocks, 512 threads \\ \hline 3DCONV & 1 file, 512 MB & 128 tblocks, 512 threads \\ \hline GESUMMV & 1 files, almost 1 GB & 128 tblocks, 512 threads \\ \hline MVT & 1 file, almost 1 GB & 128 tblocks, 512 threads \\ \hline BICG & 1 file, almost 1 GB & 128 tblocks, 512 threads \\ \hline ATAX & 1 file, almost 1 GB & 128 tblocks, 512 threads \\ \hline \end{tabular} \end{center} \caption{\label{tbl:eval:benches}The benchmarks which are used for the evaluation of the GPU I/O readahead prefetcher and the new GPU page cache replacement mechanism (tblocks is an abbreviation for threadblocks).} \end{table*} We implement our design into GPUfs and evaluate it on NVIDIA Tesla K40C GPUs, Intel Xeon E5-2620v2 CPU with 64GB DDR4 DRAM, and Intel NVMe SSD DC P3700 with 2.8GB/s read bandwidth. We evaluate it on Ubuntu 15.04 with Linux kernel 3.19.0-47 and ext4 on SSD. We use CUDA 6.5 for GPUfs, the GPU programs and the GPU microbenchmarks. Finally, we run every experiment 10 times and we calculate the average value (arithmetic mean). We flush the contents of the CPU page cache before every experiment. \begin{figure}[h!] \centering \centerline{\includegraphics[width=.8\columnwidth, keepaspectratio]{images/totalPerf.pdf}} \caption{\label{fig:eval:totalPerf}The GPU I/O performance when GPUfs uses the GPU I/O readahead prefetcher with 4KB pages, vs. the original version of GPUfs with large pages} \end{figure} \begin{figure}[h!] \centering \centerline{\includegraphics[width=.9\columnwidth, keepaspectratio]{images/bigFiles.png}} \caption{\label{fig:eval:bigFiles}The GPU I/O performance of the microbenchmark for files that do not fit in the GPU page cache. We compare GPUfs with the new page cache replacement mechanism and the prefetcher vs. the GPUfs with the prefetcher only vs. GPUfs original version} \end{figure} \subsection{Microbenchmarks} The microbenchmark we use for our evaluation is a GPU application configured with 120 threadblocks, 512 threads per threadblock. The application reads 1 GB from a 10GB file. Every threadblock issues the same number of sequential I/O read requests into its own strides of the file in a data-parallel manner. \paragraph{The performance of the GPU I/O readahead prefetcher} We compare the benefits of the GPU prefetcher over the original GPUfs as follows. We vary the page size from 4KB to 4MB in the original GPUfs. In the new version that uses the prefetcher we vary the \emph{prefetch} size accordingly, but keep the GPUfs page size 4K. In this experiment we expect that the new GPU prefetcher will help recover the GPUfs performance with large pages, but without actually modifying the size of the GPUfs page. Figure \ref{fig:eval:totalPerf} shows that the prefetcher achieves significant improvement, within 20\% of the best performance of GPUfs with 64KB pages. This is about $2\times$ better than the original GPUfs. \paragraph{Big files.} We evaluate our new page cache replacement mechanism by executing the same microbenchmark but now reading 4GB (twice the size of the page cache) vs. 1GB in the previous experiment. Figure \ref{fig:eval:bigFiles} shows that the use of the new replacement mechanism is significantly better compared to the use of 4KB pages without it (blue baseline). \subsection{Benchmark applications} \label{par:GPUIO15} We evaluate the GPUfs with the new readahead prefetcher and page cache replacement mechanism on 14 benchmarks derived from the RODINIA, PARBOIL and POLYBENCH benchmark suites. We follow the methodology used in prior works to evaluate GPU I/O performance~\cite{nvmmu} as follows. The input for the GPU kernel in the original benchmarks is first stored in a file, and then the benchmarks are invoked when the data is read from the file into GPU memory. The benchmark time measurement has been modified to include the time to read the file, copy it to GPU memory, and run the GPU kernel. We scale up the file sizes either by using the tools provided with the benchmark, or by generating large files ourselves. Table \ref{tbl:eval:benches} presents the benchmarks and their I/O configuration. The reason for configuring the execution of NW and PATHFINDER at 100 threadblocks is because of the file size that these specific benchmarks process. Thus, we set the number at 100 so that the threadblocks process equally-sized portions of the file. In the experiments we compare three implementations: (1) CPU I/O -- standard CPU I/O (1 CPU thread) that reads the whole file at once with cudaMemcpy to transfer data to the GPU; (2) GPUfs with 64KB pages to show the upper bound on the performance as it results in the best performance; (3) GPUfs with 4KB pages and the prefetcher configured to 64KB. (4) The original GPUfs with 4KB pages without the prefetcher. GPUfs is configured with 2GB page cache in all of the cases. \paragraph{File size smaller than the page cache size} In this experiment we evaluate the performance when the page cache is large enough to store the entire input. Figure \ref{fig:eval:totalExecRatio15} shows the end-to-end speedup for the benchmarks over the unmodified GPUfs with 4KB pages. \begin{figure*}[t] \centering \centerline{\includegraphics[width=1\textwidth, keepaspectratio]{images/totalExecRatio_gpufs4KB.png}} \caption{\label{fig:eval:totalExecRatio15} End-to-end speedup over original GPUfs with 4KB GPUfs pages: GPUfs-prefetcher -- this work with 4KB GPUfs pages, CPU -- CPU-only (original benchmark), GPUfs-64KB -- GPUfs with 64KB pages. Files are smaller than the page cache.} \end{figure*} The use of GPUfs prefetcher improves the performance of the original GPUfs by $3\times$ on average (geometric mean), compared to the default version of GPUfs, and by over $1.5\times$ on average (geometric mean) compared to the CPU I/O. To show that this speedup stems from the improved I/O performance, Figure \ref{fig:eval:IOband15} shows the I/O bandwidth for each benchmark. \begin{figure*}[t] \centering \centerline{\includegraphics[width=1\textwidth, keepaspectratio]{images/IOband_15graphs.png}} \caption{\label{fig:eval:IOband15} I/O performance of: original GPUfs with 4KB pages, GPUfs-prefetcher -- this work with 4KB GPUfs pages, CPU -- CPU-only (original benchmark), GPUfs-64KB -- GPUfs with 64KB pages. Files are smaller than the page cache.} \end{figure*} The results indicate that the speedup indeed originates from the efficient I/O. More specifically, the I/O bandwidth with the prefetcher is on average (geometric mean) almost $4\times$ higher than with the original GPUfs version and $2\times$ higher than with the CPU I/O. \begin{figure*}[t] \centering \centerline{\includegraphics[width=1\textwidth, keepaspectratio]{images/totalExecRatio_gpufs4KB_bigFiles.png}} \caption{\label{fig:eval:totalExecRatio9_big} End-to-end speedup over original GPUfs with 4KB pages: GPUfs-prefetcher -- this work with 4KB GPUfs pages without the new replacement policy, GPUfs-64KB -- GPUfs with 64KB pages, GPUfs-new replacement -- this work with the new replacement policy. Files are \emph{larger} than the page cache.} \end{figure*} \begin{figure*}[t] \centering \centerline{\includegraphics[width=1\textwidth, keepaspectratio]{images/IOband_9graphs_bigFiles.pdf}} \caption{\label{fig:eval:IOband9_big} I/O performance of: GPUfs-prefetcher -- this work with 4KB GPUfs pages without the new replacement policy, GPUfs-regular -- original GPUfs with 4KB pages, GPUfs-64KB -- GPUfs with 64KB pages, GPUfs-new replacement -- this work with the new replacement policy. Files are \emph{larger} than the page cache. } \end{figure*} \paragraph{File size larger than the page cache size} We perform the same experiments, but this time we configure the GPU page cache to be smaller than the total input size. Specifically, we configure it to be 500MB (except for setting the page cache size to 256MB for 3DCONV because the input data size is 512MB). We compare three versions: GPUfs with 4KB pages with the enabled GPU prefetcher with 64K and new replacement mechanism, original GPUfs with 64KB pages (best performing configuration for GPUfs) and GPUfs with the prefetcher but without the new replacement mechanism. Figure~\ref{fig:eval:totalExecRatio9_big} shows the end-to-end speedup over GPUfs with 4KB pages. The average speedup (geomean) due to the new replacement mechanism is almost $5\times$. Figure~\ref{fig:eval:IOband9_big} shows the performance improvement to the I/O bandwidth, when GPUfs uses the prefetcher along with the new page cache replacement mechanism. It is almost $6\times$ more on average (geometric mean) than the version of GPUfs that uses only the prefetcher and $8\times$ (geometric mean) higher against the default version of GPUfs. \paragraph{GPU I/O prefetcher vs bigger GPU page cache page sizes} All the new mechanisms introduced in this paper enable faster operation of GPUfs for 4KB pages in case of sequential accesses. However, we observe that configuring GPUfs with 64KB pages achieves higher performance. This is expected, as the use of 4KB pages in GPUfs incurs higher page cache management overheads compared to managing 64KB pages, and this paper does not deal with optimizing the page cache data structures. \section{Related work} \label{sec:related} Data prefetching has been extensively studied and used for many cases. To the best of our knowledge, it is the first time that a system-level, I/O readahead prefetcher is proposed and integrated with the GPU I/O system stack. In this section we present a subset of the related work that exists in bibliography. \textbf{Hardware prefetchers.} Many hardware prefetching schemes have been proposed by prior work such as \cite{stateless}\cite{tlb-pref}\cite{data-pref}. \cite{apogee} is a mechanism which dynamically detects and adapts to the graphics and scientific applications memory access patterns. \cite{graph-gpu} introduces a prefetching technique that boosts the performance of graph applications which have been implemented in GPU. \cite{compass} introduces a prefetching mechanism for CPUs that takes advantage of the idle shaders of the integrated GPUs and improves the single-threaded performance. \cite{many-thread-gpgpu} consists of a hardware and software prefetcher tailored to GPGPU systems but focus mainly on enhancing the performance of the memory accesses. On the contrary, our GPU I/O readahead prefetcher aims to improve the performance of the GPU I/O sequential reads, regardless of the application type, is a software component and is integrated with the GPU I/O system stack. \textbf{I/O prefechers.} \cite{pref-cache-opt} introduces a new algorithm that makes the minimum number of I/O instructions to service the I/O requests. \cite{mpi-parall-pref} proposes an I/O signature-based prefetcher which mainly targets to detect the I/O pattern of an application and issues the requests as early as possible. \cite{aggr-pref} raises the issue of performing more aggressive I/O prefetching in terms of speculation and data size. Our work follows this direction but also considers other factors as well, like the PCIe data transfers, because of the complexity of a heterogeneous CPU-discrete GPU system. \cite{hide-IO} pre-executes a fragment of code, via a pre-execution thread that runs at the same time as the main thread, in order to prefetch I/O requests. This solution cannot be efficiently applied for GPUs because it would require code divergence and would raise performance issues. \textbf{System level I/O prefetchers.} \cite{advOS} is a system level I/O readahead prefetcher, which is integrated with the Linux OS and enhances the I/O performance of the programs which perform sequential I/O read accesses. As our study showed, the Linux Readahead Prefetcher is not sufficient to enhance the I/O performance of the GPUs because of the diverse architectural characteristics of a heterogeneous CPU-discrete GPU system. The GPU I/O readahead prefetcher operates synergistically with the Linux Readahead Prefetcher in order to improve the GPU I/O performance. \textbf{GPU system abstractions.} \cite{Silberstein-gpufs} and \cite{gpunet} provide file access and networking abstractions to GPU programs in order to be able to issue I/O and networking instructions without the intervention of the CPU. The current work is complementary to GPUfs as it is integrated into it and enhances the performance of the GPU applications with I/O sequential read access pattern. \section{Conclusion} \label{sec:conclusion} We introduce a GPU I/O readahead prefetcher which enhances the performance of the applications that perform per-threadblock sequential I/O read accesses in discrete portions of a file. We make a thorough analysis of the GPU I/O system stack components in order to identify the bottlenecks and examine the I/O characteristics of the GPU applications that could potentially harm or improve their performance. We show that the I/O access pattern does not affect the performance for request sizes greater than or equal to 128KB and for smaller request sizes, it actually boosts their performance because the address interleaving offers efficient overlapping for the asynchronous I/O prefetch requests, which are issued by the Linux Readahead Prefetcher. We observe and conclude that the GPUfs workload scheduler, which maps the GPU I/O requests to the host threads, creates a detrimental effect on the GPU I/O performance, for request sizes greater than or equal to 128KB. Furthermore, the GPU memory limitations also cause performance degradation for applications that operate on files that do not fit in the GPU page cache and thus, we introduce a new page cache replacement mechanism that reduces significantly the number of allocations/deallocations of pages and therefore, the data structure handling overheads. The new computing paradigm dictates the need for OS support for the heterogeneous systems \cite{omnix} and the expansion of the legacy OS abstractions in order to provide greater flexibility and convenience to the heterogeneous system programmers. The GPU I/O readahead prefetcher is a step towards this direction as it expands the efficiency of the Linux Readahead Prefetcher for GPU I/O. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-09-14T02:16:46', 'yymm': '2109', 'arxiv_id': '2109.05366', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05366'}
arxiv
\section{Introduction} \label{sec:intro} Despite massive efforts to improve the security of computer systems, security breaches are only becoming more frequent and damaging, as more sensitive data is processed in the cloud~\cite{malekos-smith:csis20:hidden-costs-cybercrime,ibm20:breach-cost-report}. Current encryption technology is of limited help, because servers must decrypt data before processing it. Once data is decrypted, it is vulnerable to breaches. Fully Homomorphic Encryption (FHE) is a class of encryption schemes that address this problem by enabling \emph{generic computation on encrypted data}. \autoref{fig:overview} shows how FHE enables secure offloading of computation. The client wants to compute an expensive function $f$ (e.g., a deep learning inference) on some private data $x$. To do this, the client encrypts $x$ and sends it to an untrusted server, which computes $f$ on this encrypted data \emph{directly} using FHE, and returns the encrypted result to the client. FHE provides ideal security properties: even if the server is compromised, attackers cannot learn anything about the data, as it remains encrypted throughout. \figOverview FHE is a young but quickly developing technology. First realized in 2009~\cite{gentry09}, early FHE schemes were about 10$^9$ times slower than performing computations on unencrypted data. Since then, improved FHE schemes have greatly reduced these overheads and broadened its applicability~\cite{albrecht:hesg18:standard,peikert2016decade}. FHE has inherent limitations---for example, data-dependent branching is impossible, since data is encrypted---so it won't subsume all computations. Nonetheless, important classes of computations, like deep learning inference~\cite{cheon:ictaci17:homomorphic,dathathri:pldi19:chet,dathathri:pldi20:eva}, linear algebra, and other inference and learning tasks~\cite{han:aaai19:logistic} are a good fit for FHE. This has sparked significant industry and government investments~\cite{ibm,intel,dprive} to widely deploy FHE. Unfortunately, FHE still carries substantial performance overheads: despite recent advances~\cite{dathathri:pldi19:chet, dathathri:pldi20:eva, roy:hpca19:fpga-he, brutzkus:icml19:low, polyakov:17:palisade}, FHE is still 10,000$\times$ to 100,000$\times$ slower than unencrypted computation when executed in carefully optimized software. Though this slowdown is large, it can be addressed with hardware acceleration: \emph{if a special- ized FHE accelerator provides large speedups over software execution, it can bridge most of this performance gap and enable new use cases.} For an FHE accelerator to be broadly useful, it should be programmable, i.e., capable of executing arbitrary FHE computations. While prior work has proposed several FHE accelerators, they do not meet this goal. Prior FHE accelerators~\cite{cousins:hpec14:fpga-he,cousins:tetc17:fpga-he,doroz:tc15:accelerating-fhe,roy:hpca19:fpga-he,riazi:asplos20:heax,turan:tc20:heaws} target individual FHE operations, and miss important ones that they leave to software. These designs are FPGA-based, so they are small and miss the data movement issues facing an FHE ASIC accelerator. These designs also overspecialize their functional units to specific parameters, and cannot efficiently handle the range of parameters needed within a program or across programs. In this paper we present F1\xspace, the first programmable FHE accelerator. F1\xspace builds on an in-depth architectural analysis of the \mbox{characteristics} of FHE computations, which exposes the main challenges and reveals the design principles a programmable FHE architecture should exploit. \paragraph{Harnessing opportunities and challenges in FHE:} F1\xspace is tailored to the three defining characteristics of FHE: \noindent \textbf{\emph{(1) Complex operations on long vectors:}} FHE encodes information using very large vectors, several thousand elements long, and processes them using modular arithmetic. F1\xspace employs \emph{vector processing} with \emph{wide functional units} tailored to FHE operations to achieve large speedups. The challenge is that two key operations on these vectors, the Number-Theoretic Transform (NTT) and automorphisms, are not element-wise and require complex dataflows that are hard to implement as vector operations. To tackle these challenges, F1\xspace features specialized NTT units and the first vector implementation of an automorphism functional unit. \noindent \textbf{\emph{(2) Regular computation:}} FHE programs are dataflow graphs of arithmetic operations on vectors. All operations and their dependences are known ahead of time (since data is encrypted, branches or dependences determined by runtime values are impossible). F1\xspace exploits this by adopting \emph{static scheduling}: in the style of Very Long Instruction Word (VLIW) processors, all components have fixed latencies and the compiler is in charge of scheduling operations and data movement across components, with no hardware mechanisms to handle hazards (i.e., no stall logic). Thanks to this design, F1\xspace can issue many operations per cycle with minimal control overheads; combined with vector processing, F1\xspace can issue tens of thousands of scalar operations per cycle. % \noindent \textbf{\emph{(3) Challenging data movement:}} In FHE, encrypting data increases its size (typically by at least 50$\times$); data is grouped in long vectors; and some operations require large amounts (tens of MBs) of auxiliary data. Thus, we find that data movement is \emph{the key challenge} for FHE acceleration: despite requiring complex functional units, in current technology, limited on-chip storage and memory bandwidth are the bottleneck for most FHE programs. Therefore, F1\xspace is primarily designed to minimize data movement. First, F1\xspace features an explicitly managed on-chip memory hierarchy, with a heavily banked scratchpad and distributed register files. Second, F1\xspace uses mechanisms to decouple data movement and hide access latencies by loading data far ahead of its use. Third, F1\xspace uses new, FHE-tailored scheduling algorithms that maximize reuse and make the best out of limited memory bandwidth. Fourth, F1\xspace uses relatively \emph{few functional units with extremely high throughput}, rather than lower-throughput functional units as in prior work. This \emph{reduces the amount of data that must reside on-chip simultaneously}, allowing higher reuse. In summary, F1\xspace brings decades of research in architecture to bear, including vector processing and static scheduling, and combines them with new specialized functional units (\autoref{sec:FUs}) and scheduling algorithms (\autoref{sec:scheduler}) to design a programmable FHE accelerator. We implement the main components of F1\xspace in RTL and synthesize them in a commercial 14nm/12nm process. With a modest area budget of 151\,mm$^2$, our F1\xspace implementation provides 36 tera-ops/second of 32-bit modular arithmetic, 64\,MB of on-chip storage, and a 1\,TB/s high-bandwidth memory. We evaluate F1\xspace using cycle-accurate simulation running complete FHE applications, and demonstrate speedups of 1,200$\times$--17,000$\times$ over state-of-the-art software implementations. These dramatic speedups counter most of FHE's overheads and enable new applications. For example, F1\xspace executes a deep learning inference that used to take 20 minutes in 240 milliseconds, enabling secure real-time deep learning in the cloud. \section{Background}\label{sec:background} Fully Homomorphic Encryption allows performing arbitrary arithmetic on encrypted plaintext values, via appropriate operations on their ciphertexts. Decrypting the resulting ciphertext yields the same result as if the operations were performed on the plaintext values ``in the clear.'' Over the last decade, prior work has proposed multiple \emph{FHE schemes}, each with somewhat different capabilities and performance tradeoffs. BGV~\cite{brakerski:toct14:leveled}, B/FV~\cite{brakerski:crypto12:fully,fan:iacr12:somewhat}, GSW~\cite{gentry:crypto13:homomorphic}, and CKKS~\cite{cheon:ictaci17:homomorphic} are popular FHE schemes.\footnote{These scheme names are acronyms of their authors' last names. For instance, BGV is Brakerski-Gentry-Vaikuntanathan.}~Though these schemes differ in how they encrypt plaintexts, they all use the same data type for ciphertexts: polynomials where each coefficient is an integer modulo $Q$. This commonality makes it possible to build a single accelerator that supports multiple FHE schemes; F1\xspace supports BGV, GSW, and CKKS. We describe FHE in a layered fashion: \autoref{sec:fhe_mapping} introduces FHE's programming model and operations, i.e., FHE's \emph{interface}; \autoref{sec:fhe_operation} describes how FHE operations are \emph{implemented}; \autoref{sec:fhe_optimizations} presents implementation \emph{optimizations}; and \autoref{sec:fhe_analysis} performs an \emph{architectural analysis} of~a~representative FHE kernel to reveal acceleration opportunities. For concreteness, we \emph{introduce FHE using the BGV scheme}, and briefly discuss other FHE schemes in \autoref{sec:fhe_others}. \subsection{FHE programming model and operations} \label{sec:fhe_mapping} FHE programs are \emph{dataflow graphs}: directed acyclic graphs where nodes are operations and edges represent data values. Data values are inputs, outputs, or intermediate values consumed by one or more operations. All operations and dependences are known in advance, and data-dependent branching is impossible. In FHE, unencrypted (plaintext) data values are always \emph{vectors}; in BGV~\cite{brakerski:toct14:leveled}, each vector consists of $N$ integers modulo an integer $t$. BGV provides three operations on these vectors: element-wise \emph{addition} (mod $t$), element-wise \emph{multiplication} (mod $t$), and a small set of particular vector \emph{permutations}. We stress that this is BGV's \emph{interface}, not its implementation: it describes \emph{unencrypted} data, and the homomorphic operations that BGV implements on that data in its encrypted form. In \autoref{sec:fhe_operation} we describe how BGV represents encrypted data and how each operation is implemented. At a high level, FHE provides a vector programming model with restricted operations where individual vector elements cannot be directly accessed. This causes some overheads in certain algorithms. For example, summing up the elements of a vector is non-trivial, and requires a sequence of permutations and additions. Despite these limitations, prior work has devised reasonably efficient implementations of key algorithms, including linear algebra~\cite{halevi:crypto14:algorithms}, neural network inference~\cite{brutzkus:icml19:low, gilad:icml16:cryptonets}, logistic regression~\cite{han:iacr18:efficient}, and genome processing~\cite{blatt:nas20:secure}. These implementations are often coded by hand, but recent work has proposed FHE compilers to automate this translation for particular domains, like deep learning~\cite{dathathri:pldi19:chet,dathathri:pldi20:eva}. Finally, note that not all data must be encrypted: BGV provides versions of addition and multiplication where one of the operands is unencrypted. Multiplying by unencrypted data is cheaper, so algorithms can trade privacy for performance. For example, a deep learning inference can use encrypted weights and inputs to keep the model private, or use unencrypted weights, which does not protect the model but keeps inputs and inferences private~\cite{brutzkus:icml19:low}. \subsection{BGV implementation overview} \label{sec:fhe_operation} We now describe how BGV represents and processes encrypted data (ciphertexts). The implementation of each computation on ciphertext data is called a \emph{homomorphic operation}. For example, the \emph{homomorphic multiplication} of two ciphertexts yields another ciphertext that, when decrypted, is the element-wise multiplication of the encrypted plaintexts. \paragraph{Data types:} BGV encodes each plaintext vector as a polynomial with~$N$ coefficients mod~$t$. We denote the plaintext space as~$R_t$, so \[\mathfrak{a} = a_0 + a_1x + ... + a_{N-1}x^{N-1} \in R_t\] is a plaintext. Each plaintext is encrypted into a ciphertext consisting of two polynomials of~$N$ integer coefficients modulo some $Q \gg t$. Each ciphertext polynomial is a member of~$R_Q$. \paragraph{Encryption and decryption:} Though encryption and decryption are performed by the client (so F1\xspace need not accelerate~them), they are useful to understand. In BGV, the \textit{secret key} is a polynomial $\mathfrak{s} \in R_Q$. To encrypt a plaintext $\mathfrak{m} \in R_t$, one samples a uniformly random $\mathfrak{a} \in R_Q$, an \emph{error} (or \emph{noise}) $\mathfrak{e} \in R_Q$ with small entries, and computes the ciphertext $ct$ as \begin{equation*} ct = (\mathfrak{a}, \mathfrak{b} = \mathfrak{a}\mathfrak{s} + t \mathfrak{e} + \mathfrak{m}). \end{equation*} Ciphertext $ct = (\mathfrak{a}, \mathfrak{b})$ is decrypted by recovering $\mathfrak{e}' = t\mathfrak{e} + \mathfrak{m} = \mathfrak{b} - \mathfrak{a} \mathfrak{s} \bmod{Q}$, and then recovering $\mathfrak{m} = \mathfrak{e}' \bmod t$. Decryption is correct as long as~$\mathfrak{e}'$ does not ``wrap around'' modulo~$Q$, i.e., its coefficients have magnitude less than~$Q/2$. The security of any encryption scheme relies on the ciphertexts not revealing anything about the value of the plaintext (or the secret key). Without adding the noise term $\mathfrak{e}$, the original message $\mathfrak{m}$ would be recoverable from $ct$ via simple Gaussian elimination. Including the noise term entirely hides the plaintext (under cryptographic assumptions)~\cite{lyubashevsky:tact10:ideal}. As we will see, homomorphic operations on ciphertexts increase their noise, so we can only perform a limited number of operations before the resulting noise becomes too large % and makes decryption fail. We later describe \emph{noise management strategies} (Sec. \ref{noisemgmt}) % to keep this noise bounded and thereby allow unlimited operations. \subsubsection{Homomorphic operations} \paragraph{\\Homomorphic addition} of ciphertexts $ct_0 = (\mathfrak{a}_{0}, \mathfrak{b}_{0})$ and $ct_1 = (\mathfrak{a}_{1}, \mathfrak{b}_{1})$ is done simply by adding their corresponding polynomials: $ct_{\text{add}} = ct_0 + ct_1 = (\mathfrak{a}_0 + \mathfrak{a}_1, \mathfrak{b}_0 + \mathfrak{b}_1)$. \paragraph{Homomorphic multiplication} requires two steps. First, the four input polynomials are multiplied and assembled: \begin{equation*} ct_{\times} = (\mathfrak{l}_2, \mathfrak{l}_1, \mathfrak{l}_0) = (\mathfrak{a}_0\mathfrak{a}_1, \mathfrak{a}_0\mathfrak{b}_1 + \mathfrak{a}_1 \mathfrak{b}_0, \mathfrak{b}_0\mathfrak{b}_1) . \end{equation*} This $ct_{\times}$ can be seen as a special intermediate ciphertext encrypted under a different secret key. The second step performs a \emph{key-switch\-ing op\-era\-tion} to produce a ciphertext encrypted under the original secret key~$\mathfrak{s}$. More specifically, $\mathfrak{l}_2$ undergoes this key-switching process to produce two polynomials $(\mathfrak{u}_1, \mathfrak{u}_0) = \textrm{KeySwitch}(\mathfrak{l}_2)$. The final output ciphertext is $ct_{\text{mul}} = (\mathfrak{l}_1 + \mathfrak{u}_1, \mathfrak{l}_0 + \mathfrak{u}_0)$. As we will see later (\autoref{sec:fhe_analysis}), key-switching is an expensive operation that dominates the cost of a multiplication. \paragraph{Homomorphic permutations} permute the~$N$ plaintext values (coefficients) that are encrypted in a ciphertext. Homomorphic permutations are implemented using \emph{automorphisms}, which are special permutations of the coefficients of the ciphertext polynomials. There are~$N$ automorphisms, denoted $\sigma_k(\mathfrak{a})$ and $\sigma_{-k}(\mathfrak{a})$ for all positive odd $k<N$. Specifically, % \begin{equation*} \sigma_k(\mathfrak{a}): a_i \rightarrow (-1)^{s} a_{ik \textrm{ mod } N} \text{ for } i=0,...,N-1, \end{equation*} where $s=0$ if $ik \textrm{ mod } 2N < N$, and $s=1$ otherwise. For example, $\sigma_{5}(\mathfrak{a})$ permutes $\mathfrak{a}$'s coefficients so that $a_0$ stays at position 0, $a_1$ goes from position 1 to position 5, and so on (these wrap around, e.g., with $N=1024$, $a_{205}$ goes to position~1, since $205\cdot5 \textrm{ mod } 1024 = 1$). To perform a homomorphic permutation, we first compute an automorphism on the ciphertext polynomials: $ct_{\sigma} = (\sigma_k(\mathfrak{a}), \sigma_k(\mathfrak{b}))$. Just as in homomorphic multiplication, $ct_{\sigma}$ is encrypted under a different secret key, requiring an expensive key-switch to produce the final output $ct_{\text{perm}} = (\mathfrak{u}_1, \sigma_{k}(\mathfrak{b}) + \mathfrak{u}_0)$, where $(\mathfrak{u}_1, \mathfrak{u}_0) = \text{KeySwitch}(\sigma_k (\mathfrak{a}))$. We stress that the permutation applied to the ciphertext \emph{does not} induce the same permutation on the underlying plaintext vector. For example, using a single automorphism and careful indexing, it is possible to homomorphically \emph{rotate} the vector of the $N$ encrypted plaintext values. \subsubsection{Noise growth and management}\label{noisemgmt} \textrm{\\Recall} that ciphertexts have noise, which limits the number of operations that they can undergo before decryption gives an incorrect result. Different operations induce different noise growth: addition and permutations cause little growth, but multiplication incurs much more significant growth. So, to a first order, the amount of noise is determined by \emph{multiplicative depth}, i.e., the longest chain of homomorphic multiplications in the computation. Noise forces the use of a large ciphertext modulus $Q$. For example, an FHE program with multiplicative depth of 16 needs $Q$ to be about 512 bits. The noise budget, and thus the tolerable multiplicative depth, grow linearly with~$\log Q$. FHE uses two noise management techniques in tandem: \emph{bootstrapping} and \emph{modulus switching}. \paragraph {Bootstrapping}~\cite{gentry09} enables FHE computations of \emph{unbounded} depth. Essentially, it removes noise from a ciphertext without access to the secret key. This is accomplished by evaluating the decryption function homomorphically. Bootstrapping is an expensive procedure that consists of many (typically tens to hundreds) ho\-mo\-mor\-phic op\-era\-tions. FHE programs with a large multiplicative depth can be divided into regions of limited depth, separated by bootstrapping operations. Even with bootstrapping, FHE schemes need a large noise budget (i.e., a large~$Q$) because \emph{(1)}~bootstrapping is computationally expensive, and a higher noise budget enables less-frequent bootstrapping, and \emph{(2)}~bootstrapping itself consumes a certain noise budget (this is similar to why pipelining circuits hits a performance ceiling: registers themselves add area and latency). \paragraph{Modulus switching} rescales ciphertexts from modulus~$Q$ to a modulus~$Q'$, which reduces the noise proportionately. Modulus switching is usually applied before each homomorphic multiplication, to reduce its noise blowup. For example, to execute an FHE program of multiplicative depth 16, we would start with a 512-bit modulus~$Q$. Right before each multiplication, we would switch to a modulus that is 32 bits shorter. So, for example, operations at depth 8 use a 256-bit modulus. Thus, beyond reducing noise, modulus switching reduces ciphertext sizes, and thus computation cost. \subsubsection{Security and parameters} \textrm{\\The} dimension~$N$ and modulus~$Q$ cannot be chosen independently; $N/\log Q$ must be above a certain level for sufficient security. In practice, this means that using a wide modulus to support deep programs also requires a large $N$. For example, with 512-bit $Q$, $N=16K$ is required to provide an acceptable level of security, resulting in very large ciphertexts. \subsection{Algorithmic insights and optimizations}\label{sec:algoInsights} \label{sec:fhe_optimizations} F1\xspace leverages two optimizations developed in prior work: \paragraph{Fast polynomial multiplication via NTTs:} Multiplying two polynomials requires convolving their coefficients, an expensive (naively $O(N^2)$) operation. Just like convolutions can be made faster with the Fast Fourier Transform, polynomial multiplication can be made faster with the Number-Theoretic Transform (NTT)~\cite{moenck1976practical}, % a variant of the discrete Fourier transform for modular arithmetic. The NTT takes an $N$\hyp{}coefficient polynomial as input and returns an $N$\hyp{}element vector representing the input in the \textit{NTT domain}. Polynomial multiplication can be performed as element-wise multiplication in the NTT domain. Specifically, \begin{equation*} NTT(\mathfrak{a}\mathfrak{b}) = NTT(\mathfrak{a}) \odot NTT(\mathfrak{b}), \end{equation*} where $\odot$ denotes component-wise multiplication. (For this relation to hold with $N$\hyp{}point NTTs, a \emph{negacyclic} NTT~\cite{lyubashevsky:tact10:ideal} must be used (\autoref{sec:fourStepNTT}).) Because an NTT requires only $O(N \log N)$ modular operations, multiplication can be performed in $O(N \log N)$ operations by using two forward NTTs, element-wise multiplication, and an inverse NTT. And in fact, optimized FHE implementations often store polynomials in the NTT domain rather than in their coefficient form \emph{across operations}, further reducing the number of NTTs. This is possible because the NTT is a linear transformation, so additions and automorphisms can also be performed in the NTT domain: \vspace{-0.05in} % \begin{align*} NTT(\sigma_k(\mathfrak{a})) &= \sigma_k(NTT(\mathfrak{a})) \\ NTT(\mathfrak{a} + \mathfrak{b}) &= NTT(\mathfrak{a}) + NTT(\mathfrak{b}) \end{align*} \vspace{-0.2in} \paragraph{Avoiding wide arithmetic via Residue Number System (RNS) representation:} FHE requires wide ciphertext coefficients (e.g., 512 bits), but wide arithmetic is expensive: the cost of a modular multiplier (which takes most of the compute) grows quadratically with bit width in our range of interest. Moreover, \mbox{we need to efficiently} % support a broad range of widths (e.g., 64 to 512 bits in 32-bit increments), both because programs need different widths, and because modulus switching progressively reduces coefficient widths. RNS representation \cite{garner1959residue} % enables representing a single polynomial with wide coefficients as multiple polynomials with narrower coefficients, called \emph{residue polynomials}. To achieve this, the modulus~$Q$ is chosen to be the product of $L$ smaller distinct primes, $Q = q_1q_2\cdots\ q_L$. Then, a polynomial in $R_Q$ can be represented as $L$ polynomials in $R_{q_1}, \ldots, R_{q_L}$, where the coefficients in the $i$-th polynomial are simply the wide coefficients modulo $q_i$. For example, with $W = 32$-bit words, a ciphertext polynomial with $512$-bit modulus~$Q$ is represented as $L = \log Q/W = 16$ polynomials with $32$-bit coefficients. All FHE operations can be carried out under RNS representation, and have either better or equivalent bit-complexity than operating on one wide-coefficient polynomial. % \subsection{Architectural analysis of FHE} \label{sec:fhe_analysis} We now analyze a key FHE kernel in depth to understand how we can (and cannot) accelerate it. Specifically, we consider the key-switching operation, which is expensive and takes the majority of work in all of our benchmarks. \autoref{listing:keyswitch} shows an implementation of key-switching. Key\hyp{}switching takes three inputs: a polynomial \texttt{x}, and two \emph{key-switch hint matrices} \texttt{ksh0} and \texttt{ksh1}. \texttt{x} is stored in RNS form as $L$ residue polynomials (\texttt{RVec}). Each residue polynomial \texttt{x[i]} is a vector of $N$ 32-bit integers modulo $q_i$. Inputs and outputs are in the NTT domain; only the \texttt{y[i]} polynomials (line 3) are in coefficient form. \begin{figure} \begin{center} \begin{lstlisting}[caption={Key-switch implementation. \texttt{RVec} is an $N$-element vector of 32-bit values, storing a single RNS polynomial in either the coefficient or the NTT domain. % % }, mathescape=true, style=custompython, label=listing:keyswitch] def keySwitch(x: RVec[L], ksh0: RVec[L][L], ksh1: RVec[L][L]): y = [INTT(x[i],$q_i$) for i in range(L)] u0: RVec[L] = [0, ...] u1: RVec[L] = [0, ...] for i in range(L): for j in range(L): xqj = (i == j) ? x[i] : NTT(y[i], $q_j$) u0[j] += xqj * ksh0[i,j] mod $q_j$ u1[j] += xqj * ksh1[i,j] mod $q_j$ return (u0, u1) \end{lstlisting} \end{center} \vspace{0.25cm} \end{figure} \paragraph{Computation vs.\ data movement:} A single key-switch requires $L^2$ NTTs, $2L^2$ multiplications, and $2L^2$ additions of $N$-element \mbox{vectors}. In RNS form, the rest of a homomorphic multiplication (excluding key-switching) is $4L$ multiplications and $3L$ additions (\autoref{sec:fhe_operation}), so key-switching is dominant. However, the main cost at high values of $L$ and $N$ is data movement. For example, at $L = 16$, $N = 16K$, each RNS polynomial (\texttt{RVec}) is 64\,KB; each ciphertext polynomial is 1\,MB; each ciphertext is 2\,MB; and the key-switch hints dominate, taking up 32\,MB. With F1\xspace's compute throughput, fetching the inputs of each key-switching from off-chip memory would demand about 10\,TB/s of memory bandwidth. Thus, it is crucial to reuse these values as much as possible. Fortunately, key-switch hints can be reused: all homomorphic multiplications use the same key-switch hint matrices, and each automorphism has its own pair of matrices. But values are so large that few of them fit on-chip. Finally, note that there is no effective way to decompose or tile this operation to reduce storage needs while achieving good reuse: tiling the key-switch hint matrices on either dimension produces many long-lived intermediate values; and tiling across \texttt{RVec} elements is even worse because in NTTs every input element affects every output element. \paragraph{Performance requirements:} We conclude that, to accommodate these large operands, an FHE accelerator requires a memory system that \emph{(1)} decouples data movement from computation, as demand misses during frequent key-switches would tank performance; and \emph{(2)} implements a large amount of on-chip storage (over 32\,MB in our example) to allow reuse across entire homomorphic operations (e.g., reusing the same key-switch hints across many homomorphic multiplications). Moreover, the FHE accelerator must be designed to use the memory system well. First, scheduling data movement and computation is crucial: data must be fetched far ahead of its use to provide decoupling, and operations must be ordered carefully to maximize reuse. Second, since values are large, excessive parallelism can increase footprint and hinder reuse. Thus, the system should use relatively few high-throughput functional units rather than many low-throughput ones. \paragraph{Functionality requirements:} Programmable FHE accelerators must support a wide range of parameters, both $N$ (polynomial/vector sizes) and $L$ (number of RNS polynomials, i.e., number of 32-bit prime factors of $Q$). While $N$ is generally fixed for a single program, $L$ changes as modulus switching sheds off polynomials. Moreover, FHE accelerators must avoid overspecializing in order to support algorithmic diversity. For instance, we have described \emph{an} implementation of key-switching, but there are others~\cite{kim:jmir18:helr,gentry:crypto2012:homomorphic} with different tradeoffs. % For example, an alternative implementation requires much more compute but has key-switch hints that grow with $L$ instead of $L^2$, so it becomes attractive for very large $L$ ($\sim$20). F1\xspace accelerates \emph{primitive operations on large vectors}: modular arithmetic, NTTs, and automorphisms. It exploits wide vector processing to achieve very high throughput, even though this makes NTTs and automorphisms costlier. F1\xspace avoids building functional units for coarser primitives, like key-switching, which would hinder algorithmic diversity. \paragraph{Limitations of prior accelerators:} Prior work has proposed several FHE accelerators for FPGAs~\cite{cousins:hpec14:fpga-he,cousins:tetc17:fpga-he,doroz:tc15:accelerating-fhe,roy:hpca19:fpga-he,migliore:tecs17:he-karatsuba,riazi:asplos20:heax,turan:tc20:heaws,mert:tvlsi20:bfv-accel}. These systems have three important limitations. First, they work by accelerating some primitives but defer others to a general-purpose host processor, and rely on the host processor to sequence operations. This causes excessive data movement that limits speedups. Second, these accelerators build functional units for \emph{fixed parameters} $N$ and $L$ (or $\log Q$ for those not using RNS). Third, many of these systems build overspecialized primitives that limit algorithmic diversity. Most of these systems achieve limited speedups, about 10$\times$ over software baselines. HEAX~\cite{riazi:asplos20:heax} achieves larger speedups (200$\times$ vs.\ a single core). But it does so by overspecializing: it uses relatively low-throughput functional units for primitive operations, so to achieve high performance, it builds a fixed-function pipeline for key-switching. \subsection{FHE schemes other than BGV} \label{sec:fhe_others} We have so far focused on BGV, but other FHE schemes provide different tradeoffs. For instance, whereas BGV requires integer plaintexts, CKKS~\cite{cheon:ictaci17:homomorphic} supports ``approximate'' computation on \mbox{fixed-point} values. B/FV~\cite{brakerski:crypto12:fully,fan:iacr12:somewhat} encodes plaintexts in a way that makes modulus switching before homomorphic multiplication unnecessary, thus easing programming (but forgoing the efficiency gains of modulo switching). And GSW~\cite{gentry:crypto13:homomorphic} features reduced, asymmetric noise growth under homomorphic multiplication, but encrypts a small amount of information per ciphertext (not a full $N/2$-element vector). Because F1\xspace accelerates primitive operations rather than full homomorphic operations, it supports BGV, CKKS, and GSW with the same hardware, since they use the same primitives. Accelerating B/FV would require some other primitives, so, though adding support for them would not be too difficult, our current implementation does not target it. \section{F1 Architecture}\label{sec:arch} \autoref{fig:arch} shows an overview of F1\xspace, which we derive from the insights in \autoref{sec:fhe_analysis}. \paragraph{Vector processing with specialized functional units:} F1\xspace features wide-vector execution with functional units (FUs) tailored to primitive FHE operations. Specifically, F1\xspace implements vector FUs for modular addition, modular multiplication, NTTs (forward and inverse in the same unit), and automorphisms. Because we leverage RNS representation, these FUs use a fixed, small arithmetic word size (32 bits in our implementation), avoiding wide arithmetic. \figArch FUs process vectors of configurable \emph{length} $N$ using a fixed number of \emph{vector lanes} $E$. Our implementation uses $E=$128 lanes and supports power-of-two lengths $N$ from 1,024 to 16,384. This covers the common range of FHE polynomial sizes, so an RNS polynomial maps to a single vector. Larger polynomials (e.g., of 32K elements) can use multiple vectors. All FUs are \emph{fully pipelined}, so they achieve the same throughput of $E=$128 elements/cycle. FUs consume their inputs in contiguous chunks of $E$ elements in consecutive cycles. This is easy for element-wise operations, but hard for NTTs and automorphisms. \autoref{sec:FUs} details our novel FU implementations, including the first vector implementation of automorphisms. Our evaluation shows that these FUs achieve much higher performance than those of prior work. This is important because, as we saw in \autoref{sec:fhe_analysis}, \emph{having fewer high-throughput FUs reduces parallelism and thus memory footprint}. \paragraph{Compute clusters:} Functional units are grouped in \emph{compute clusters}, as \autoref{fig:arch} shows. Each cluster features several FUs (1 NTT, 1 automorphism, 2 multipliers, and 2 adders in our implementation) and a banked register file that can (cheaply) supply enough operands each cycle to keep all FUs busy. The chip has multiple clusters (16 in our implementation). \paragraph{Memory system:} F1\xspace features an explicitly managed memory hierarchy. As \autoref{fig:arch} shows, F1\xspace features a large, heavily banked scratchpad (64\,MB across {16} banks in our implementation). The scratchpad interfaces with both high-bandwidth off-chip memory (HBM2 in our implementation) and with compute clusters through an on-chip network. F1\xspace uses decoupled data orchestration~\cite{pellauer:asplos19:buffets} to hide main memory latency. Scratchpad banks work autonomously, fetching data from main memory far ahead of its use. Since memory has relatively low bandwidth, off-chip data is always staged in scratchpads, and compute clusters do not access main memory directly. The on-chip network connecting scratchpad banks and compute clusters provides very high bandwidth, which is necessary because register files are small and achieve limited reuse. We implement a single-stage bit-sliced crossbar network~\cite{passas:tocaid12:crossbar} that provides full bisection bandwidth. Banks and the network have wide ports (512 bytes), so that a single scratchpad bank can send a vector to a compute unit at the rate it is consumed (and receive it at the rate it is produced). This avoids long staging of vectors at the register files. \paragraph{Static scheduling:} Because FHE programs are completely regular, F1\xspace adopts a \emph{static, exposed microarchitecture}: all components have fixed latencies, which are exposed to the compiler. The compiler is responsible for scheduling operations and data transfers in the appropriate cycles to prevent structural or data hazards. This is in the style of VLIW processors~\cite{fisher:isca83:very}. Static scheduling simplifies logic throughout the chip. For example, FUs need no stalling logic; register files and scratchpad banks need no dynamic arbitration to handle conflicts; and the on-chip network uses simple switches that change their configuration independently over time, without the buffers and arbiters of packet-switched networks. Because memory accesses do have a variable latency, we assume the worst-case latency, and buffer data that arrives earlier % (note that, because we access large chunks of data, e.g., 64\,KB, this worst-case latency is not far from the average). \paragraph{Distributed control:} Though static scheduling is the hallmark of VLIW, F1\xspace's implementation is quite different: rather than having a single stream of instructions with many operations each, in F1\xspace each component has an \emph{independent instruction stream}. % This is possible because F1\xspace does not have any control flow: though FHE programs may have loops, we unroll them to avoid all branches, and compile programs into linear sequences of instructions. This approach may appear costly. But vectors are very long, so each instruction encodes a lot of work and this overhead is minimal. Moreover, this enables a compact instruction format, which encodes a single operation followed by the number of cycles to wait until running the next instruction. This encoding avoids the low utilization of VLIW instructions, which leave many operation slots empty. Each FU, register file, network switch, scratchpad bank, and memory controller has its own instruction stream, which a control~unit~fetches in small blocks and distributes to components. Overall, instruction fetches consume less than 0.1\% of memory traffic. \paragraph{Register file (RF) design:} Each cluster in F1\xspace requires 10 read ports and 6 write ports to keep all FUs busy. To enable this cheaply, we use an 8-banked \emph{element-partitioned} register file design~\cite{asanovic:ucb98:vector} that leverages long vectors: each vector is striped across banks, and each FU cycles through all banks over time, using a single bank each cycle. By staggering the start of each vector operation, FUs access different banks each cycle. This avoids multiporting, requires a simple RF-FU interconnect, and performs within 5\% of an ideal infinite-ported RF. \section{Scheduling Data and Computation}\label{sec:scheduler} We now describe F1\xspace's software stack, focusing on the new static scheduling algorithms needed to use hardware well. \figCompilerOverview \autoref{fig:compilerOverview} shows an overview of the F1\xspace compiler. The compiler takes as input an FHE program written in a high-level domain specific language (\autoref{sec:programming}). The compiler is structured in three stages. First, the \emph{homomorphic operation compiler} orders high-level operations to maximize reuse and translates the program into a \emph{computation dataflow graph}, where operations are computation instructions but there are no loads or stores. Second, the \emph{off-chip data movement scheduler} % schedules transfers between main memory and the scratchpad to achieve decoupling and maximize reuse. This phase uses a simplified view of hardware, considering it as a scratchpad directly attached to functional units. % The result is a dataflow graph that includes loads and stores from off-chip memory. Third, the \emph{cycle-level scheduler} refines this dataflow graph. It uses a cycle-accurate hardware model to divide instructions across compute clusters and schedule on-chip data transfers. This phase determine the exact cycles of all operations, and produces the instruction streams for all components. This multi-pass scheduling primarily minimizes off-chip data movement, the critical bottleneck. Only in the last phase do we consider on-chip placement and data movement. \paragraph{Comparison with prior work:} We initially tried static sched\-uling algorithms from prior work~\cite{blelloch:acm1999:provably,marchal:jpdc2019:limiting,goodman:ics1988:code,ozer:micro1998:unified,barany:odes2011:register}, which primarily target VLIW architectures. However, we found these approaches ill-suited to F1\xspace for multiple reasons. First, VLIW designs have less-flexible decoupling mechanisms and minimizing data movement is secondary to maximizing compute operations per cycle. Second, prior algorithms often focus on loops, where the key concern is to find a compact repeating schedule, e.g., through software pipelining~\cite{lam1989software}. By contrast, F1\xspace has no flow control and we can schedule each operation independently. Third, though prior work has proposed register-pressure-aware instruction scheduling algorithms, they targeted small register files and basic blocks, whereas we must manage a large scratchpad over a much longer horizon. Thus, the algorithms we tried either worked poorly~\cite{ozer:micro1998:unified, goodman:ics1988:code, marchal:jpdc2019:limiting} or could not scale to the sizes required~\cite{barany:odes2011:register, xu:sigplan2007:tetris, touati:ijpp2005:register, berson:pact1993:ursa}. For example, when considering an algorithm such as Code Scheduling to Minimize Register Usage (CSR)~\cite{goodman:ics1988:code}, we find that the schedules it produces suffer from a large blowup of live intermediate values. This large footprint causes scratchpad thrashing and results in poor performance. Furthermore, CSR is also quite computationally expensive, requiring long scheduling times for our larger benchmarks. We evaluate our approach against CSR in \autoref{sec:sensitivity}. We also attempted to frame scheduling as a register allocation problem. Effectively, the key challenge in all of our schedules is \emph{data movement}, not computation. Finding a register allocation which minimizes spilling could provide a good basis for an effective schedule. However, our scratchpad stores at least 1024 residue vectors (1024 at maximum $N = 16K$, more for smaller values of $N$), and many of our benchmarks involve hundreds of thousands of instructions, meaning that register allocation algorithms simply could not scale to our required sizes~\cite{barany:odes2011:register, xu:sigplan2007:tetris, touati:ijpp2005:register, berson:pact1993:ursa}. \subsection{Translating the program to a dataflow graph} \label{sec:programming} We implement a high-level domain-specific language (DSL) for writing F1\xspace programs. To illustrate this DSL and provide a running example, \autoref{listing:mv} shows the code for matrix-vector multiplication. This follows HELib's algorithm~\cite{halevi:crypto14:algorithms} , which \autoref{fig:MultDataflow} shows. This toy $4 \times 16K$ matrix-vector multiply uses input ciphertexts with $N=16K$. Because accessing individual vector elements is not possible, the code uses homomorphic rotations % to produce each output element. \begin{figure} \begin{center} \begin{lstlisting}[caption={$(4 \times 16K)$ matrix-vector multiply in F1\xspace's DSL.}, mathescape=true, style=custompython, label=listing:mv] p = Program(N = 16384) M_rows = [ p.Input(L = 16) for i in range(4) ] output = [ None for i in range(4) ] V = p.Input(L = 16) def innerSum(X): for i in range(log2(p.N)): X = Add(X, Rotate(X, 1 << i)) return X for i in range(4): prod = Mul(M_rows[i], V) output[i] = innerSum(prod) \end{lstlisting} \end{center} \vspace{0.15cm} \end{figure} As \autoref{listing:mv} shows, programs in this DSL are at the level of the simple FHE interface presented in \autoref{sec:fhe_mapping}. There is only one aspect of the FHE implementation in the DSL: programs encode the desired noise budget ($L=16$ in our example), as the compiler does not automate noise management. \subsection{Compiling homomorphic operations} The first compiler phase works at the level of the homomorphic operations provided by the DSL. It clusters operations to improve reuse, and translates them down to instructions. \paragraph{Ordering} homomorphic operations seeks to maximize the reuse of key-switch hints, which is crucial to reduce data movement (\autoref{sec:fhe_analysis}). For instance, the program in \autoref{listing:mv} uses 15 different sets of key-switch hint matrices: one for the multiplies (line 12), and a different one for \emph{each} of the rotations (line 8). If this program was run sequentially as written, it would cycle through all 15 key-switching hints (which total 480\,MB, exceeding on-chip storage) four times, achieving no reuse. Clearly, it is better to reorder the computation to perform all four multiplies, and then all four \texttt{Rotate(X, 1)}, and so on. This reuses each key-switch hint four times. To achieve this, this pass first clusters \emph{independent} homomorphic operations that reuse the same hint, then orders all clusters through simple list-scheduling. This generates schedules with good key-switch hint reuse. \figMultDataflow \paragraph{Translation:} Each homomorphic operation is then compiled into instructions, using the implementation of each operation in the target FHE scheme (BGV, CKKS, or GSW). Each homomorphic operation may translate to thousands of instructions. These instructions are also ordered to minimize the amount of intermediates. The end result is an instruction-level dataflow graph where every instruction is tagged with a priority that reflects its global order. The compiler exploits algorithmic choice. Specifically, there are multiple implementations of key-switching (\autoref{sec:fhe_analysis}), and the right choice depends on $L$, the amount of key-switch reuse, and load on FUs. The compiler leverages knowledge of operation order to estimate these and choose the right variant. \subsection{Scheduling data transfers} \label{sec:datatransfers} The second compiler phase consumes an instruction-level dataflow graph and produces an approximate schedule that includes data transfers decoupled from computation, minimizes off-chip data transfers, and achieves good parallelism. This requires solving an interdependent problem: when to bring a value into the scratchpad and which one to replace depends on the computation schedule; and to prevent stalls, the computation schedule depends on which values are in the scratchpad. To solve this problem, this scheduler uses a simplified model of the machine: it does not consider on-chip data movement, and simply treats all functional units as being directly connected to the scratchpad. % The scheduler is greedy, scheduling one instruction at a time. It considers instructions ready if their inputs are available in the scratchpad, and follows instruction priority among ready ones. To schedule loads, we assign each load a priority \begin{equation*} p(\text{load}) = \max \{ p(u) | u \in users(\text{load})\}, \end{equation*} then greedily issue loads as bandwidth becomes available. When issuing an instruction, we must ensure that there is space to store its result. We can often replace a dead value. % When no such value exists, we evict the value with the furthest expected time to reuse. We estimate time to reuse as the maximum priority among unissued users of the value. This approximates Belady's optimal replacement policy~\cite{belady1966study}. Evictions of dirty data add stores to the dataflow graph. When evicting a value, we add spill (either dirty or clean) and fill instructions to our dataflow graph. \subsection{Cycle-level scheduling} Finally, the cycle-level scheduler takes in the data movement schedule produced by the previous phase, and schedules all operations for all components considering all resource constraints and data dependences. This phase distributes computation across clusters and manages their register files and all on-chip transfers. Importantly, this scheduler is fully constrained by its input schedule's off-chip data movement. It does not add loads or stores in this stage, but it does move loads to their earliest possible issue cycle to avoid stalls on missing operands. All resource hazards are resolved by stalling. In practice, we find that this separation of scheduling into data movement and instruction scheduling produces good schedules in reasonable compilation times. This stage works by iterating through all instructions in the order produced by the previous compiler phase (\autoref{sec:datatransfers}) and determining the minimum cycle at which all required on-chip resources are available. We consider the availability of off-chip bandwidth, scratchpad space, register file space, functional units, and ports. During this final compiler pass, we finally account for store bandwidth, scheduling stores (which result from spills) as needed. In practice, we find that this does not hurt our performance much, as stores are infrequent across most of our benchmarks due to our global schedule and replacement policy design. After the final schedule is generated, we validate it by simulating it forward to ensure that no clobbers or resource usage violations occur. It is important to note that because our schedules are fully static, our scheduler also doubles as a performance measurement tool. As illustrated in \autoref{fig:compilerOverview}, the compiler takes in an architecture description file detailing a particular configuration of F1\xspace. This flexibility allows us to conduct design space explorations very quickly (\autoref{sec:scalability}). \section{Functional Units} \label{sec:FUs} In this section, we describe F1\xspace's novel functional units. These include the first vectorized automorphism unit (\autoref{sec:automorphism}), the first fully-pipelined flexible NTT unit (\autoref{sec:fourStepNTT}), and a new simplified modular multiplier adapted to FHE (\autoref{sec:modMult}). \subsection{Automorphism unit}\label{sec:automorphism} Because F1\xspace uses $E$ vector lanes, each residue polynomial is stored and processed as $G$ groups, or \emph{chunks}, of $E$ elements each ($N=G\cdot E$). An automorphism $\sigma_k$ maps the element at index $i$ to index $ki \textrm{ mod } N$; there are $N$ automorphisms total, two for each odd $k < N$ (\autoref{sec:fhe_operation}). The key challenge in designing an automorphism unit is that these permutations are hard to vectorize: we would like this unit to consume and produce $E=$128 elements/cycle, but the vectors are much longer, with $N$ up to 16\,K, and elements are permuted across different chunks. Moreover, we must support variable $N$ \emph{and} all automorphisms. Standard solutions fail: a 16\,K$\times$16\,K crossbar is much too large; a scalar approach, like reading elements in sequence from an SRAM, is too slow (taking $N$ cycles); and using banks of SRAM to increase throughput runs into frequent bank conflicts: each automorphism ``spreads''~elements with a different stride, so regardless of the \mbox{banking} scheme, some automorphisms will map many consecutive elements to the~same~bank. \figAutomorphism We contribute a new insight that makes vectorizing automorphisms simple: if we interpret a residue polynomial as a $G \times E$ matrix, an automorphism can always be decomposed into two independent \emph{column} and \emph{row permutations}. If we transpose this matrix, both column and row permutations can be applied \emph{in chunks of $E$ elements}. \autoref{fig:automorphism} shows an example of how automorphism $\sigma_3$ is applied to a residue polynomial with $N=16$ and $E=4$ elements/cycle. Note how the permute column and row operations are local to each $4$-element chunk. Other $\sigma_k$ induce different permutations, but with the same row/column structure. \figautfu Our automorphism unit, shown in \autoref{fig:aut_fu}, uses this insight to be both vectorized (consuming $E=128$ elements/cycle) and fully pipelined. Given a residue polynomial of $N=G\cdot E$ elements, the automorphism unit first applies the column permutation to each $E$-element input. Then, it feeds this to a \emph{transpose unit} that reads in the whole residue polynomial interpreting it as a $G\times E$ matrix, and produces its transpose $E\times G$. The transpose unit outputs $E$ elements per cycle (outputting multiple rows per cycle when $G < E$). Row permutations are applied to each $E$-element chunk, and the reverse transpose is applied. Further, we decompose both the row and column permutations into a pipeline of sub-permutations that are \textit{fixed in hardware}, with each sub-permutation either applied or bypassed based on simple control logic; this avoids using crossbars for the $E$-element permute row and column operations. \paragraph{Transpose unit:} Our \textit{quadrant-swap transpose} unit transposes an $E \times E$ (e.g., $128\times 128$) matrix by recursively decomposing it into quadrants and exploiting the identity \begin{equation*} \left[ \begin{array}{c|c} \texttt{A} & \texttt{B}\\ \hline \texttt{C} & \texttt{D} \end{array}\right]^{\textrm{T}} = \left[ \begin{array}{c|c} \texttt{A}^{\textrm{T}} & \texttt{C}^{\textrm{T}} \\ \hline \texttt{B}^{\textrm{T}} & \texttt{D}^{\textrm{T}} \end{array}\right]. \end{equation*} The basic building block is a $K \times K$ \textit{quadrant-swap} unit, which swaps quadrants \texttt{B} and \texttt{C}, as shown in \autoref{fig:quadrantSwap}(left). Operationally, the quadrant swap procedure consists of three steps, each taking $K/2$ cycles: \begin{enumerate} \item Cycle \texttt{i} in the first step reads \texttt{A[i]} and \texttt{C[i]} and stores them in \texttt{top[i]} and \texttt{bottom[i]}, respectively. \item Cycle \texttt{i} in the second step reads \texttt{B[i]} and \texttt{D[i]}. The unit activates the first swap MUX and the bypass line, thus storing \texttt{D[i]} in \texttt{top[i]} and outputing \texttt{A[i]} (by reading from \texttt{top[i]}) and \texttt{B[i]} via the bypass line. \item Cycle \texttt{i} in the third step outputs \texttt{D[i]} and \texttt{C[i]} by reading from \texttt{top[i]} and \texttt{bottom[i]}, respectively. The second swap MUX is activated so that \texttt{C[i]} is on top. \end{enumerate} Note that step $3$ for one input can be done in parallel with step $1$ for the next, so the unit is \emph{fully pipelined}. \figQuadrantSwap The transpose is implemented by a full $E \times E$ quadrant-swap followed by $\log_2E$ layers of smaller transpose units to recursively transpose \texttt{A}, \texttt{B}, \texttt{C}, and \texttt{D}. \autoref{fig:quadrantSwap} (right) shows an implementation for $E=8$. Finally, by selectively bypassing some of the initial quadrant swaps, this transpose unit also works for all values of $N$ ($N=G\times E$ with power-of-2 $G < E$). Prior work has implemented transpose units for signal-processing applications, either using registers~\cite{wang2018pipelined,zhang2020novel} or with custom SRAM designs~\cite{shang2014single}. Our design has three advantages over prior work: it uses standard SRAM memory, so it is dense without requiring complex custom SRAMs; it is fully pipelined; and it works for a wide range of dimensions. \subsection{Four-step NTT unit}\label{sec:fourStepNTT} There are many ways to implement NTTs in hardware: an NTT is like an FFT~\cite{cooley:moc65:algorithm} but with a butterfly that uses modular multipliers. We implement $N$-element NTTs (from 1K to 16K) as a composition of smaller $E$=128-element NTTs, since implementing a full 16K-element NTT datapath is prohibitive. The challenge is that standard approaches result in memory access patterns that are hard to vectorize. \figFourStepNTT To that end, we use the \textit{four-step variant} of the FFT algorithm~\cite{bailey:supercomputing89:FFTs}, which adds an extra multiplication to produce a vector-friendly decomposition. \autoref{fig:fourStepNTT} illustrates our four-step NTT pipeline for $E=4$; we use the same structure with $E=128$. The unit is fully pipelined and consumes $E$ elements per cycle. To compute an $N=E\times E$ NTT, the unit first computes an $E$-point NTT on each $E$-element group, multiplies each group with twiddles, transposes the $E$ groups, and computes another $E$-element NTT on each transpose. The same NTT unit implements the inverse NTT by storing multiplicative factors (\textit{twiddles}) required for both forward and inverse NTTs in a small \textit{twiddle SRAM}. Crucially, we are able to support all values of $N$ using a single four-step NTT pipeline by conditionally bypassing layers in the second NTT butterfly. We use the same transpose unit implementation as with automorphisms. Our four-step pipeline supports negacyclic NTTs (NCNs), which are more efficient than standard non-negacyclic NTTs (that would require padding, \autoref{sec:algoInsights}). Specifically, we extend prior work~\cite{poppelmann2015high,roy2014compact,lyubashevsky:tact10:ideal} in order to support \emph{both} forward and inverse NCNs using the same hardware as for the standard NTT. Namely, prior work shows how to either \emph{(1)} perform a forward NCN via a standard decimation-in-time (DIT) NTT pipeline, or \emph{(2)} perform an inverse NCN via a standard decimation-in-frequency (DIF) NTT pipeline. The DIF and DIT NTT variants use different hardware; therefore, this approach requires separate pipelines for forward and inverse NCNs. Prior work~\cite{lyubashevsky:tact10:ideal} has shown that separate pipelines can be avoided by adding a multiplier either before or after the NTT: doing an \emph{inverse} NCN using a \emph{DIT} NTT requires a multiplier unit \emph{after} the NTT, while doing a \emph{forward} NCN using a \emph{DIF} NTT requires a multiplier unit \emph{before} the NTT. We now show that \emph{both} the forward and inverse NCN can be done in the same standard four-step NTT pipeline, with \emph{no additional hardware}. This is because the four-step NTT already has a multiplier and two NTTs in its pipeline. We set the first NTT to be decimation-in-time and the second to be decimation-in-frequency (\autoref{fig:fourStepNTT}). To do a forward NTT, we use the forward NCN implementation via DIT NTT for the first NTT; we modify the contents of the Twiddle SRAM so that the multiplier does the pre-multiplication necessary to implement a forward NCN in the second NTT (which is DIF and thus requires the pre-multiplication). Conversely, to do an inverse NTT, we modify the Twiddle SRAM contents to do the post\hyp{}mul\-ti\-pli\-ca\-tion necessary to implement an inverse NCN in the first NTT (which is DIT); and we use the inverse NCN imple\-men\-ta\-tion via DIF NTT for the second NTT. The NTT unit is large: each of the 128-element NTTs requires $E(\log (E)-1)/2$=384 multipliers, and the full unit uses 896 multipliers. But its high throughput improves performance over many low-throughput NTTs (\autoref{sec:evaluation}). % This is the first implementation of a fully-pipelined four-step NTT unit, improving NTT performance by 1,600$\times$ over the state of the art (\autoref{sec:perf}). \subsection{Optimized modular multiplier}\label{sec:modMult} \tblModMult Modular multiplication computes $a\cdot b \textrm{ mod } q$. This is the most expensive and frequent operation. Therefore, improvements to the modular multiplier have an almost linear impact on the computational capabilities of an FHE accelerator. Prior work~\cite{mert:euromicro19:design} recognized that a Montgomery multiplier~\cite{montgomery:mom85:modular} within NTTs can be improved by leveraging the fact that the possible values of modulus $q$ are restricted by the number of elements the NTT is applied to. We notice that if we only select moduli $q_i$, such that $q_i = -1 \textrm{ mod } 2^{16}$, we can remove a mutliplier stage from~\cite{mert:euromicro19:design}; this reduces area by 19\% and power by 30\% (\autoref{tbl:modMult}). The additional restriction on $q$ is acceptable because FHE requires at most 10s of moduli~\cite{gentry:crypto2012:homomorphic}, and our approach allows for 6,186~prime~moduli. \section{F1\xspace Implementation} \label{sec:implementation} We have implemented F1\xspace's components in RTL, and synthesize them in a commercial 14/12nm process using state-of-the-art tools. These include a commercial SRAM compiler that we use for scratchpad and register file banks. We use a dual-frequency design: most components run at 1\,GHz, but memories (register files and scratchpads) run double-pumped at 2\,GHz. Memories meet this frequency easily and this enables using single-ported SRAMs while serving up to two accesses per cycle. By keeping most of the logic at 1\,GHz, we achieve higher energy efficiency. We explored several non-blocking on-chip networks (Clos, Benes, and crossbars). We use 3 16$\times$16 bit-sliced crossbars~\cite{passas:tocaid12:crossbar} (scratch\-pad$\rightarrow$cluster, cluster$\rightarrow$scratchpad, and cluster$\rightarrow$cluster). % \autoref{tbl:GF12} shows a breakdown of area by component, as well as the area of our F1\xspace configuration, 151.4\,mm$^2$. FUs take 42\% of the area, with 31.7\% going to memory, 6.6\% to the on-chip network, and 19.7\% to the two HBM2 PHYs. We assume 512\,GB/s bandwidth per PHY; this is similar to the NVIDIA A100 GPU~\cite{choquette2021nvidia}, which has 2.4\,TB/s with 6 HBM2E PHYs~\cite{nvidiadgx}. We use prior work to estimate HBM2 PHY area~\cite{rambuswhite, dasgupta20208} and power~\cite{rambuswhite, ge2011design}. This design is constrained by memory bandwidth: though it has 1\,TB/s of bandwidth, the on-chip network's bandwidth is 24\,TB/s, and the aggregate bandwidth between RFs and FUs is 128\,TB/s. This is why maximizing reuse is crucial. \section{Experimental Methodology} \paragraph{Modeled system:} We evaluate our F1\xspace implementation from \autoref{sec:implementation}. We use a cycle-accurate simulator to execute F1\xspace programs. Because the architecture is static, this is very different from conventional simulators, and acts more as a checker: it runs the instruction stream at each component and verifies that latencies are as expected and there are no missed dependences or structural hazards. We use activity-level energies from RTL synthesis to produce energy breakdowns. \paragraph{Benchmarks:} We use several FHE programs to evaluate F1\xspace. % All programs come from state-of-the-art software implementations, which we port to F1\xspace: \subparagraph{Logistic regression} uses the HELR algorithm~\cite{han:aaai19:logistic}, which is based on CKKS. We compute a single batch of logistic regression training with up to $256$ features, and $256$ samples per batch, starting at computational depth $L = 16$; this is equivalent to the first batch of HELR's MNIST workload. This computation features % ciphertexts with large $\log Q$ ($L = 14,15,16$), so it needs careful data orchestration to run efficiently. \subparagraph{Neural network} benchmarks come from Low Latency CryptoNets (LoLa)~\cite{brutzkus:icml19:low}. This work uses B/FV, an FHE scheme that F1\xspace does not support, so we use CKKS instead. We run two neural networks: LoLa-MNIST is a simple, LeNet-style network used on the MNIST dataset~\cite{lecunn:ieee98:gradient-document}, while LoLa-CIFAR is a much larger 6-layer network (similar in computation to MobileNet v3~\cite{howard2019searching}) used on the CIFAR-10 dataset~\cite{cifar10}. LoLa-MNIST includes two variants with unencrypted and encrypted weights; LoLa-CIFAR is available only with unencrypted weights. These three benchmarks use relatively low $L$ values (their starting $L$ values are 4, 6, and 8, respectively), so they are less memory-bound. They also feature frequent automorphisms, showing the need for a fast automorphism~unit. \tblGF % \subparagraph{DB Lookup} is adapted from HELib's \texttt{BGV\_country\_db\_lookup}~\cite{helib:db-lookup}. A BGV-encrypted query string is used to traverse an encrypted key-value store and return the corresponding value. The original implementation uses a low security level for speed of demonstration, but in our version, we implement it at $L=$17, $N=$16K for realism. We also parallelize the CPU version so it can effectively use all available cores. DB Lookup is both deep and wide, so running it on F1\xspace incurs substantial off-chip data movement. \addtocounter{table}{1} \tblMicrobenchmark \subparagraph{Bootstrapping:} We evaluate bootstrapping benchmarks for BGV and CKKS. Bootstrapping takes an $L=1$ ciphertext with an exhausted noise budget and refreshes it by bringing it up to a chosen top value of $L=L_{max}$, then performing the bootstrapping computation to eventually obtain a usable ciphertext at a lower depth (e.g., $L_{max} - 15$ for BGV). For BGV, we use Sheriff and Peikert's algorithm~\cite{alperin:crypto13:practical} for non-packed BGV boot\-strap\-ping, with $L_{max} = 24$. This is a particularly challenging benchmark because it features computations at large values of $L$. This exercises the scheduler's algorithmic choice component, which selects the right key-switch method to balance computation and data movement. For CKKS, we use non-packed CKKS bootstrapping from HEA\-AN~\cite{cheon:eurocrypt2018:bootstrapping}, also with $L_{max} = 24$. CKKS bootstrapping has many fewer ciphertext multiplications than BGV, greatly reducing reuse opportunities for key-switch hints. \paragraph{Baseline systems:} We compare F1\xspace with a CPU system running the baseline programs (a 4-core, 8-thread, 3.5\,GHz Xeon E3-1240v5). Since prior accelerators do not support full programs, we also include microbenchmarks of single operations and compare against HEAX~\cite{riazi:asplos20:heax}, the fastest prior accelerator. \section{Evaluation}\label{sec:evaluation} \subsection{Performance}\label{sec:perf} \addtocounter{table}{-2} \tblBenchmark \addtocounter{table}{1} \paragraph{Benchmarks:} \autoref{tbl:benchmark} compares the performance of F1\xspace and the CPU on full benchmarks. It reports execution time in milliseconds for each program (lower is better), and F1\xspace's speedup over the CPU (higher is better). F1\xspace achieves dramatic speedups, from 1,195$\times$ to 17,412$\times$ (5,432$\times$ gmean). CKKS bootstrapping has the lowest speedups as it's highly memory-bound; other speedups are within a relatively narrow band, as compute and memory traffic are more balanced. These speedups greatly expand the applicability of FHE. Consider deep learning: in software, even the simple LoLa-MNIST network takes seconds per inference, and a single inference on the more realistic LoLa-CIFAR network takes \emph{20 minutes}. F1\xspace brings this down to 241 \emph{milliseconds}, making real-time deep learning inference practical: when offloading inferences to a server, this time is comparable to the roundtrip latency between server and client. \paragraph{Microbenchmarks:} \autoref{tbl:microbenchmark} compares the performance of F1\xspace, the CPU, and HEAX$_\sigma$ on four microbenchmarks: the basic NTT and automorphism operations on a single ciphertext, and homomorphic multiplication and permutation (which uses automorphisms). We report three typical sets of parameters. We use microbenchmarks to compare against prior accelerators, in particular HEAX. But prior accelerators do not implement automorphisms, so we extend each HEAX key-switching pipeline with an SRAM-based, scalar automorphism unit. We call this extension HEAX$_\sigma$. \autoref{tbl:microbenchmark} shows that F1\xspace achieves large speedups over HEAX$_\sigma$, ranging from 172$\times$ to 1,866$\times$. Moreover, F1\xspace's speedups over the CPU are even larger than in full benchmarks. This is because microbenchmarks are pure compute, and thus miss the data movement bottlenecks of FHE programs. \subsection{Architectural analysis} To gain more insights into these results, we now analyze F1\xspace's data movement, power consumption, and compute. \paragraph{Data movement:} \autoref{fig:dataMovement} shows a breakdown of off-chip memory traffic across data types: key-switch hints (KSH), inputs/outputs, and intermediate values. KSH and input/output traffic is broken into compulsory and non-compulsory (i.e., caused by limited scratchpad capacity). Intermediates, which are always non-compulsory, are classified as loads or stores. \autoref{fig:dataMovement} shows that key-switch hints dominate in high-depth workloads (LogReg, DB Lookup, and bootstrapping), taking up to 94\% of traffic. Key-switch hints are also significant in the LoLa-MNIST variants. This shows why scheduling should prioritize them. Second, due our scheduler design, F1\xspace approaches compulsory traffic for most benchmarks, with non\hyp{}compulsory accesses adding only 5-18\% of traffic. The exception is LoLa-CIFAR, where intermediates consume 75\% of traffic. LoLa-CIFAR has very high reuse of key-switch hints, and exploiting it requires spilling intermediate ciphertexts. \figDataMovement \figOpBreakdown \paragraph{Power consumption:} \autoref{fig:power} reports average power for each benchmark, broken down by component. This breakdown also includes off-chip memory power (\autoref{tbl:GF12} only included the on-chip component). Results show reasonable power consumption for an accelerator card. Overall, computation consumes 20-30\% of power, and data movement dominates. \paragraph{Utilization over time:} F1\xspace's average FU utilization is about 30\%. However, this doesn't mean that fewer FUs could achieve the same performance: benchmarks have memory\hyp{}bound phases that weigh down average FU utilization. To see this, \autoref{fig:opBreakdown} shows a breakdown of FU utilization over time for LoLa-MNIST Plaintext Weights. \autoref{fig:opBreakdown} also shows off-chip bandwidth utilization over time (black line). The program is initially memory-bound, and few FUs are active. As the memory-bound phase ends, compute intensity grows, utilizing a balanced mix of the available FUs. Finally, due to decoupled execution, when memory bandwidth utilization peaks again, F1\xspace can maintain high compute intensity. The highest FU utilization happens at the end of the benchmark and is caused by processing the final (fully connected) layer, which is highly parallel and already has all inputs available on-chip. \subsection{Sensitivity studies} \label{sec:sensitivity} \tblSensitivity To understand the impact of our FUs and scheduling algorithms, we evaluate F1\xspace variants without them. \autoref{tbl:sensitivity} reports the \emph{slowdown (higher is worse)} of F1\xspace with: \emph{(1)} low\hyp{}throughput NTT FUs that follow the same design as HEAX (processing one stage of NTT butterflies per cycle); % \emph{(2)} low\hyp{}throughput automorphism FUs using a serial SRAM memory, and \emph{(3)} Goodman's register-pressure-aware scheduler~\cite{goodman:ics1988:code}. For the FU experiments, our goal is to show the importance of having high-throughput units. Therefore, the low-throughput variants use many more (NTT or automorphism) FUs, so that aggregate throughput across all FUs in the system is the same. Also, the scheduler accounts for the characteristics of these FUs. In both cases, performance drops substantially, by gmean 2.6$\times$ and 3.3$\times$. This is because achieving high throughput requires excessive parallelism, which hinders data movement, forcing the scheduler to balance both. Finally, the scheduler experiment uses register-pressure-aware scheduling~\cite{goodman:ics1988:code} as the off-chip data movement scheduler instead, operating on the full dataflow graph. This algorithm was proposed for VLIW processors and register files; we apply it to the larger scratchpad. The large slowdowns show that prior capacity-aware schedulers are ineffective on F1\xspace. \figConfigs \subsection{Scalability} \label{sec:scalability} Finally, we study how F1\xspace's performance changes with its area budget: we sweep the number of compute clusters, scratchpad banks, HBM controllers, and network topology to find the most efficient design at each area. \autoref{fig:pareto} shows this Pareto frontier, with area in the $x$-axis and performance in the $y$-axis. This curve shows that, as F1\xspace scales, it uses resources efficiently: performance grows about linearly through a large range of areas. \subsection{Functional Simulation}\label{sec:functional_simulation} Here we describe our software simulation efforts for F1. Currently, we have a functional simulator written in C++ on top of Shoup's Number Theory Library.\footnote{\url{https://libntl.org/}} This simulator measures \emph{input-output correctness} and \emph{calls to functional units} throughout a computation. The underlying algorithms are not the same as F1's functional units, but they match common methods used in software (i.e., HElib's algorithms). This allows one to verify correctness of FHE algorithms and to create a dataflow graph. The simulator has all our functional units implemented in software: modular additions, modular multiplications, automorphisms, and NTTs. We then build ciphertext-level operations by calls to these algorithms: ciphertext addition, ciphertext multiplication, rotations, modulus-switching, and a simplified bootstrapping procedure, for non-packed ciphertexts. Our functional simulator works for the parameter ranges discussed throughout the paper: polynomial/ring dimension $N$ as an arbitrary power of 2 (usually 1024-16384 for security) and RNS moduli where each is an NTT-friendly prime, $q_i \equiv 1 \bmod 2N$, roughly 24 bits long. Further, each moduli is sampled randomly, similarly to other FHE RNS implementations. \section{Related Work} \label{sec:related} We now discuss related work not covered so far. \paragraph{FHE accelerators:} Prior work has proposed accelerators for individual FHE operations, but not full FHE computations~\cite{cousins:hpec12:sipher-fpga,cousins:hpec14:fpga-he,cousins:tetc17:fpga-he,doroz:tc15:accelerating-fhe,roy:hpca19:fpga-he,mert:tvlsi20:bfv-accel,migliore:tecs17:he-karatsuba,riazi:asplos20:heax,turan:tc20:heaws}. These designs target FPGAs and rely on a host processor; \autoref{sec:fhe_analysis} discussed their limitations. Early designs accelerated small primitives like NTTs, and were dominated by host-FPGA communication. State-of-the-art accelerators execute a full homomorphic multiplication independently: Roy et al.~\cite{roy:hpca19:fpga-he} accelerate B/FV multiplication by 13$\times$ over a CPU; HEAWS~\cite{turan:tc20:heaws} accelerates B/FV multiplication, and uses it to speed a simple benchmark by 5$\times$; and HEAX~\cite{riazi:asplos20:heax} accelerates CKKS multiplication and key-switching by up to 200$\times$. These designs suffer high data movement (e.g., HEAX does not reuse key-switch hints) and use fixed pipelines with relatively low-throughput FUs. We have shown that accelerating FHE programs requires a different approach: data movement becomes the key constraint, requiring new techniques to extract reuse {across} homomorphic operations; and fixed pipelines cannot support the operations of even a single benchmark. Instead, F1\xspace achieves flexibility and high performance by exploiting wide-vector execution with high-throughput FUs. This lets F1\xspace execute not only full applications, but different FHE schemes. \paragraph{Hybrid HE-MPC accelerators:} Recent work has also proposed ASIC accelerators for some homomorphic encryption primitives in the context of oblivious neural networks~\cite{juvekar2018gazelle,reagen:hpca21:cheetah}. These approaches are very different from FHE: they combine homomorphic encryption with multi-party computation (MPC), executing a single layer of the network at a time and sending intermediates to the client, which computes the final activations. Gazelle~\cite{juvekar2018gazelle} is a low-power ASIC for homomorphic evaluations, and Cheetah~\cite{reagen:hpca21:cheetah} introduces algorithmic optimizations and a large ASIC design that achieves very large speedups over Gazelle. These schemes avoid high-depth FHE programs, so server\hyp{}side homomorphic operations are cheaper. But they are limited by client-side computation and client-server communication: Cheetah and Gazelle use cipher\-texts that are up to $\sim40\times$ small\-er than those used by F1\xspace; however, they re\-quire the client to re\--en\-crypt ciphertexts \textit{every} time they are mul\-ti\-pli\-ed on the server to prevent noise blowup. CHOCO~\cite{vanderhagen:arxiv21:choco} shows that client-side computation costs for HE-MPC are substantial, and when they are accelerated, network latency and throughput overheads dominate (several seconds per DNN inference). By contrast, F1\xspace enables offloading the full inference using FHE, avoiding frequent communication. As a result, a direct comparison between these accelerators and F1 is not possible. F1's hardware also differs substantially from Cheetah and Gazelle. First, Cheetah and Gazelle implement fixed-function pipelines (e.g., for output-stationary DNN inference in Cheetah), whereas F1 is programmable. Second, Cheetah, like HEAX, uses many FUs with relatively low throughput, whereas F1 uses few high-throughput units (e.g., 40$\times$ faster NTTs). Cheetah's approach makes sense for their small ciphertexts, but as we have seen (\autoref{sec:sensitivity}), it is impractical for FHE. \paragraph{GPU acceleration:} Finally, prior work has also used GPUs to accelerate different FHE schemes, including GH~\cite{wang:hpec12:fhe-gpu,wang:tc13:fhe-gpu}, BGV~\cite{wang:iscas14:leveled-gpu}, and B/FV~\cite{al:emerging19:implementation}. Though GPUs have plentiful compute and bandwidth, they lack modular arithmetic, their pure data-parallel approach makes non-element-wise operations like NTTs expensive, and their small on-chip storage adds data movement. As a result, GPUs achieve only modest performance gains. For instance, Badawi et al.~\cite{al:emerging19:implementation} accelerate B/FV multiplication using GPUs, and achieve speedups of around 10$\times$ to 100$\times$ over single-thread CPU execution (and thus commensurately lower speedups over multicore CPUs, as FHE operations parallelize well). \section{Conclusion} FHE has the potential to enable computation offloading with guaranteed security. But FHE's high computation overheads currently limit its applicability to narrow cases (simple computations where privacy is paramount). F1\xspace tackles this challenge, accelerating full FHE computations by over 3-4 orders of magnitude. This enables new use cases for FHE, like secure real-time deep learning inference. F1\xspace is the first FHE accelerator that is programmable, i.e., capable of executing full FHE programs. In contrast to prior accelerators, which build fixed pipelines tailored to specific FHE schemes and parameters, F1\xspace introduces a more effective design approach: it accelerates the \emph{primitive} computations shared by higher-level operations using novel high\hyp{}throughput functional units, and hardware and compiler are co-designed to minimize data movement, the key bottleneck. % This flexibility makes F1\xspace broadly useful: the same hardware can accelerate all operations within a program, arbitrary FHE programs, and even multiple FHE schemes. In short, our key contribution is to show that, for FHE, we can achieve ASIC-level performance without sacrificing programmability. \section*{Acknowledgments} We thank the anonymous reviewers, Maleen Abeydeera, Hyun Ryong Lee, Quan Nguyen, Yifan Yang, Victor Ying, Guowei Zhang, and Joel Emer for feedback on the paper; Tutu Ajayi, Austin Rovinski, and Peter Li for help with the HDL toolchain setup; Shai Halevi, Wei Dai, Olli Saarikivi, and Madan Musuvathi for email correspondence. This research was developed with funding from the Defense Advanced Research Projects Agency (DARPA) under contract number Contract No. HR0011-21-C-0035. The views, opinions and/or findings expressed are those of the author and should not be interpreted as representing the official views or policies of the Department of Defense or the U.S. Government. Nikola Samardzic was supported by the Jae S. and Kyuho Lim Graduate Fellowship at MIT. \bibliographystyle{IEEEtranS}
{'timestamp': '2021-09-28T02:12:37', 'yymm': '2109', 'arxiv_id': '2109.05371', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05371'}
arxiv
\section{Introduction} \vspace*{-0.15cm} Cell-Free Massive Multiple Input Multiple Output (MIMO) has recently been introduced to reduce the intercell interference of colocated Massive MIMO architectures. This is a network deployment where a large number of access points (APs) are located in a given coverage area to serve a small number of users \cite{ngo2017cell}. All the APs collaborate with each other via a backhaul network and serve all the users in the absence of cell boundaries. The system performance is enhanced in Cell-Free Massive MIMO systems because they inherit the benefits of the distributed MIMO and network MIMO architectures, but the users are also close to the APs. When each AP is equipped with a single antenna, maximum-ratio combining (MRC) results in a good net throughput for every user, while ensuring a low computational complexity and offering a distributed implementation that is convenient for scalability purposes. However, this network deployment cannot guarantee a good service under harsh propagation environments. RIS is an emerging technology that is capable of shaping the radio waves at the electromagnetic level without applying digital signal processing methods and requiring power amplifiers \cite{le2020robust}. Each element of the RIS scatters (e.g., reflects) the incident signal without using radio frequency chains and power amplification. Integrating an RIS into wireless networks introduces digitally controllable links that scale up with the number of engineered scattering elements of the RIS, whose estimation is, however, challenged by the lack of digital signal processing units at the RIS. For simplicity, the main attention has so far been concentrated on designing the phase shifts with perfect channel state information (CSI) \cite{zhao2020intelligent,perovic2021achievable} and the references therein. As far as the integration of Cell-Free Massive MIMO and RIS is concerned, recent works have formulated and solved optimization problems with different communication objectives under the assumption of perfect (and instantaneous) CSI \cite{zhou2020achievable,zhang2020capacity}. Recent results have shown that designs for the phase shifts of the RIS elements based on statistical CSI may be of practical interest and provide good performance \cite{van2021outage}. In the depicted context, no prior work has analyzed an RIS-assisted Cell-Free Massive MIMO system in the presence of spatially-correlated channels. In this work, we consider an RIS-assisted Cell-Free Massive MIMO under spatially correlated channels. We exploit a channel estimation scheme that estimates the aggregated channels including both the direct and indirect links. We analytically show that, even by using a low complexity MRC technique, the non-coherent interference, small-scale fading effects, and additive noise are averaged out when the number of APs and RIS elements increases. The received signal includes, hence, only the desired signal and the coherent interference. We derive a closed-form expression of the net throughput for the uplink data transmission. The impact of the array gain, coherent joint transmission, channel estimation errors, pilot contamination, spatial correlation, and phase shifts of the RIS, which determine the system performance, are explicitly observable in the obtained analytical expressions. With the aid of numerical simulations, we verify the effectiveness of the proposed channel estimation scheme and the accuracy of the closed-form expression of the net throughput. The obtained numerical results show that the use of RISs enhance the net throughput per user significantly, especially when the direct links are blocked with high probability. \textit{Notation}: Upper and lower bold letters denote matrices and vectors. The identity matrix of size $N \times N$ is denoted by $\mathbf{I}_N$. $(\cdot)^{\ast},$ $(\cdot)^T,$ and $(\cdot)^H$ are the complex conjugate, transpose, and Hermitian transpose. $\mathbb{E}\{ \cdot\}$ and $\mathsf{Var} \{ \cdot \}$ denote the expectation and variance of a random variable. The circularly symmetric Gaussian distribution is denoted by $\mathcal{CN}(\cdot, \cdot)$ and $\mathrm{diag} (\mathbf{x})$ is the diagonal matrix whose main diagonal is given by $\mathbf{x}$. $\mathrm{tr}(\cdot)$ is the trace operator. The Euclidean norm of vector $\mathbf{x}$ is $\| \mathbf{x}\|$, and $\| \mathbf{X} \|$ is the spectral norm of matrix $\mathbf{X}$. Finally, $\mathrm{mod}(\cdot,\cdot)$ is the modulus operation and $\lfloor \cdot \rfloor$ denotes the truncated argument. \begin{figure}[t] \centering \includegraphics[trim=3.0cm 2.4cm 5.7cm 6.8cm, clip=true, width=2.6in]{FigSysModelIRSCellFreeV1} \vspace*{-0.2cm} \caption{An RIS-assisted Cell-Free Massive MIMO system where $M$ APs collaborate with each other to serve $K$ distant users.} \label{FigSysModel} \vspace*{-0.5cm} \end{figure} \vspace*{-0.5cm} \section{System Model, Channel Estimation, and RIS Phase-Shift Control} \label{Sec:SysModel} \vspace*{-0.2cm} We consider an RIS-assisted Cell-Free Massive MIMO system, where $M$ APs connected to a central processing unit (CPU) serve $K$ users on the same time and frequency resource. All APs and users are equipped with a single antenna and they are randomly located in the coverage area. The communication is assisted by an RIS that comprises $N$ engineered scattering elements that can modify the phases of the incident signals. The matrix of phase shifts of the RIS is denoted by $\pmb{\Phi} = \mathrm{diag} \left( [ e^{j\theta_1}, \ldots, e^{j\theta_N}]^T \right)$, where $\theta_n \in [-\pi, \pi]$ is the phase shift applied by the $n$-th element of the RIS. \vspace*{-0.2cm} \subsection{Channel Model} \vspace*{-0.2cm} We assume a quasi-static block fading model where each coherence interval comprises $\tau_c$ symbols. The APs have knowledge of only the channel statistics instead of the instantaneous channel realizations. Also, $\tau_p$ symbols ($\tau_p < \tau_c$) in each coherence interval are dedicated to the channel estimation and the remaining $(\tau_c - \tau_p)$ symbols are the data transmission. The following notation is used: $g_{mk}$ is the channel between the user~$k$ and the AP~$m$, which is the direct link \cite{wu2019intelligent}; $\mathbf{h}_m \in \mathbb{C}^{N}$ is the channel between the AP~$m$ and the RIS; and $\mathbf{z}_{k} \in \mathbb{C}^{N}$ is the channel between the RIS and the user~$k$. In this paper, we consider a realistic channel model by taking into account the spatial correlation among the scattering elements of the RIS, which is due to their sub-wavelength size, sub-wavelength inter-distance, and geometric layout. In an isotropic propagation environment, in particular, $g_{mk}, \mathbf{h}_m$, and $\mathbf{z}_k$ can be modeled as follows \begin{equation} \label{eq:Channels} g_{mk} \sim \mathcal{CN}(0, \beta_{mk}), \mathbf{h}_{m} \sim \mathcal{CN}(\mathbf{0}, \mathbf{R}_{m}), \mathbf{z}_{k} \sim \mathcal{CN}(\mathbf{0}, \widetilde{\mathbf{R}}_{k}), \end{equation} where $\beta_{mk}$ is the large-scale fading coefficient; $\mathbf{R}_{m} \in \mathbb{C}^{N \times N}$ and $\widetilde{\mathbf{R}}_{k} \in \mathbb{C}^{N \times N}$ are the covariance matrices. The covariance matrices in \eqref{eq:Channels} correspond to a general model, which can be further particularized for application to typical RIS designs and propagation environments. A correlation model that is applicable to isotropic scattering with uniformly distributed multipath components in the half-space in front of the RIS was recently reported in \cite{bjornson2020rayleigh}, whose covariance matrices are \begin{equation}\label{eq:CovarMa} \mathbf{R}_m = \alpha_{m} d_Hd_V\mathbf{R} \mbox{ and } \widetilde{\mathbf{R}}_{k} = \tilde{\alpha}_{k} d_Hd_V\mathbf{R}, \end{equation} where $\alpha_{m}, \tilde{\alpha}_{mk} \in \mathbb{C}$ are the large-scale channel coefficients. The matrices in \eqref{eq:CovarMa} assume that the size of each RIS element is $d_H \times d_V$, with $d_H$ being the horizontal width and $d_V$ being the vertical height of each RIS element. In particular, the $(l,t)$-th element of the spatial correlation matrix $\mathbf{R} \in \mathbb{C}^{N \times N }$ in \eqref{eq:CovarMa} is $[\mathbf{R}]_{lt}= \mathrm{sinc} (2 \|\mathbf{u}_{l} - \mathbf{u}_{t} \|/ \lambda)$, where $\lambda$ is the wavelength and $\mathrm{sinc}(x) = \sin(\pi x) / (\pi x)$ is the $\mathrm{sinc}$ function. The vector $\mathbf{u}_{x}, x \in \{l,t\}$ is given by $\mathbf{u}_{x} = [0, \mod(x-1,N_H)d_H, \lfloor (x-1)/N_H\rfloor d_V]^T$, where $N_H$ and $N_V$ denote the total number of RIS elements in each row and column, respectively. \vspace*{-0.15cm} \subsection{Uplink Pilot Training Phase} \vspace*{-0.15cm} The channels are independently estimated from the $\tau_p$ pilot sequences transmitted by the $K$ users. All the users share the same $\tau_p$ pilot sequences. In particular, $\pmb{\phi}_k \in \mathbb{C}^{\tau_p}$ with $\| \pmb{\phi}_k \|^2 = 1$ is defined as the pilot sequence allocated to the user~$k$. We denote by $\mathcal{P}_k$ the set of indices of the users (including the user~$k$) that share the same pilot sequence as the user~$k$. The pilot sequences are assumed to be mutually orthogonal such that the pilot reuse pattern is $\pmb{\phi}_{k'}^H \pmb{\phi}_k = 1$, $k' \in \mathcal{P}_k$. Otherwise, $\pmb{\phi}_{k'}^H \pmb{\phi}_k = 0$. During the pilot training phase, all the $K$ users transmit the pilot sequences to the $M$ APs simultaneously. In particular, the user~$k$ transmits the pilot sequence $\sqrt{\tau_p} \pmb{\phi}_k$. The received training signal at the AP~$m$ can be written as \begin{equation} \label{eq:ReceivedPilot} \mathbf{y}_{pm} = \sum_{k=1}^K \sqrt{p \tau_p} g_{mk} \pmb{\phi}_k + \sum_{k=1}^K \sqrt{p \tau_p} \mathbf{h}_{m}^H \pmb{\Phi} \mathbf{z}_{k} \pmb{\phi}_k + \mathbf{w}_{pm}, \end{equation} where $p$ is the normalized signal-to-noise ratio (SNR) of each pilot symbol, and $\mathbf{w}_{pm} \in \mathbb{C}^{\tau_p}$ is the additive noise at the AP~$m$, which is distributed as $\mathbf{w}_{pm} \sim \mathcal{CN} (\mathbf{0}, \mathbf{I}_{\tau_p})$. In order for the AP~$m$ to estimate the desired channels from the user~$k$, the received training signal in \eqref{eq:ReceivedPilot} is projected on $\pmb{\phi}_k^H$ as \begin{equation} \label{eq:ReceivedPilotv1} \begin{split} y_{pmk} &= \pmb{\phi}_k^H \mathbf{y}_{pm} = \sqrt{p \tau_p} \left(g_{mk} + \mathbf{h}_{m}^H \pmb{\Phi} \mathbf{z}_{k} \right) \\ &+ \sum_{k' \in \mathcal{P}_k \setminus \{k\} } \sqrt{p\tau_p} \left(g_{mk'} + \mathbf{h}_{m}^H \pmb{\Phi} \mathbf{z}_{k'} \right) + w_{pmk}, \end{split} \end{equation} where $w_{pmk} = \pmb{\phi}_k^H \mathbf{w}_{pm} \sim \mathcal{CN}(0, 1)$. We emphasize that the co-existence of the direct and indirect channels due to the presence of the RIS results in a complicated channel estimation process. In particular, the cascaded channel in \eqref{eq:ReceivedPilotv1} results in a nontrivial procedure to apply the minimum mean-square error (MMSE) estimation method, as reported in previous works, for processing the projected signals \cite{ngo2017cell,9136914}. Based on the specific signal structure in \eqref{eq:ReceivedPilotv1}, we denote the channel between the AP~$m$ and the user~$k$ through the RIS as \begin{equation} \label{eq:umk} u_{mk} = g_{mk} + \mathbf{h}_{m}^H \pmb{\Phi} \mathbf{z}_{k}, \end{equation} which is referred to as the \textit{aggregated channel} that comprises the direct and indirect link between the user~$k$ and the AP~$m$. By capitalizing on the definition of the aggregated channel in \eqref{eq:umk}, the required channels can be estimated in an effective manner even in the presence of the RIS. In particular, the aggregated channel in \eqref{eq:umk} is given by the product of weighted complex Gaussian and spatially correlated random variables, as given in \eqref{eq:Channels}. Conditioned on the phase shifts, we employ the linear MMSE method for estimating $u_{mk}$ at the AP. Despite the complex structure of the RIS-assisted channels, Lemma~\ref{lemma:ChannelEst} provides analytical expressions of the estimated channels. \begin{lemma} \label{lemma:ChannelEst} By assuming that the AP~$m$ employs the linear MMSE estimation method based on the observation in \eqref{eq:ReceivedPilotv1}, the estimate of the aggregate channel ${u}_{mk}$ is formulated as \begin{equation} \label{eq:ChannelEst} \hat{u}_{mk} = \big(\mathbb{E}\{ y_{pmk}^\ast u_{mk} \} y_{pmk} \big)/ \mathbb{E} \{ | y_{pmk} |^2 \} = c_{mk} y_{pmk}, \end{equation} where $c_{mk} = \mathbb{E}\{ y_{pmk}^\ast u_{mk} \} / \mathbb{E} \{ | y_{pmk} |^2 \}$ has the following closed-form expression \begin{equation} \label{eq:cmk} c_{mk} = \frac{\sqrt{p\tau_p} \big( \beta_{mk} + \mathrm{tr} \big( \pmb{\Phi}^H \mathbf{R}_{m} \pmb{\Phi} \widetilde{\mathbf{R}}_{k} \big)\big) }{p\tau_p \sum_{k' \in \mathcal{P}_k} \big( \beta_{mk'} + \mathrm{tr} \big( \pmb{\Phi}^H \mathbf{R}_{m} \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \big)\big) + 1}. \end{equation} The estimated channel in \eqref{eq:ChannelEst} has zero mean and variance $\gamma_{mk}$ equal to \begin{equation} \label{eq:gammamk} \gamma_{mk} = \mathbb{E} \{ |\hat{u}_{mk}|^2 \} = \sqrt{p\tau_p} \big(\beta_{mk} + \mathrm{tr} \big( \pmb{\Phi}^H \mathbf{R}_{m} \pmb{\Phi} \widetilde{\mathbf{R}}_{k} \big) \big)c_{mk}. \end{equation} Also, the channel estimation error $e_{mk} = u_{mk} - \hat{u}_{mk}$ and the channel estimate $\hat{u}_{mk}$ are uncorrelated. The channel estimation error has zero mean and variance equal to \begin{equation} \label{eq:EstError} \mathbb{E}\big\{ |e_{mk} |^2 \big\} = \beta_{mk} + \mathrm{tr} \big( \pmb{\Phi}^H \mathbf{R}_{m} \pmb{\Phi} \widetilde{\mathbf{R}}_{k} \big) - \gamma_{mk}. \end{equation} \end{lemma} \begin{proof} It is similar to the proof in \cite{Kay1993a}, and is obtained by applying similar analytical steps to the received signal in \eqref{eq:ReceivedPilotv1} and by taking into account the structure of the RIS-assisted channel and the spatial correlation matrices in \eqref{eq:Channels}. \end{proof} Lemma~\ref{lemma:ChannelEst} shows that, by assuming $\pmb{\Phi}$ fixed, the aggregated channel in \eqref{eq:umk} can be estimated without increasing the pilot training overhead, as compared to a conventional Cell-Free Massive MIMO system. The obtained channel estimate in \eqref{eq:ChannelEst} unveils the relation $\hat{u}_{mk'} = \frac{c_{mk'}}{c_{mk}}\hat{u}_{mk}$ if the user~$k'$ uses the same pilot sequence as the user~$k$. Because of pilot contamination, it may be difficult to distinguish the signals of these two users. In the following, the analytical expression of the channel estimates in Lemma~\ref{lemma:ChannelEst} are employed for signal detection in the uplink data transmission. They are used also to optimize the phase shifts of the RIS in order to minimize the channel estimation error and to evaluate the corresponding ergodic net throughput. \vspace{-0.2cm} \subsection{RIS Phase-Shift Control} \vspace{-0.1cm} Channel estimation is a critical aspect in Cell-Free Massive MIMO. As discussed in previous text, in many scenarios, non-orthogonal pilots have to be used. This causes pilot contamination, which may reduce the system performance significantly. In this section, we design an RIS-assisted phase shift control scheme that is aimed to improve the quality of channel estimation. To this end, we introduce the normalized mean square error (NMSE) of the channel estimate of the user~$k$ at the AP~$m$ as follows \begin{equation} \begin{split} & \mathrm{NMSE}_{mk} = \mathbb{E}\{|e_{mk}|^2\}/\mathbb{E}\{|u_{mk}|^2\} \\ &=1 - \frac{p \tau_p \big(\beta_{mk} + \mathrm{tr}(\pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k} ) \big)}{p \tau_p \sum_{k' \in \mathcal{P}_{k}}\big( \beta_{mk'} + \mathrm{tr}(\pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} ) \big) + 1}. \end{split} \end{equation} \vspace{-0.1cm} where the last equality is obtained from \eqref{eq:EstError}. We optimize the phase shift matrix $\pmb{\Phi}$ of the RIS so as to minimize the total NMSE obtained from all the users and all the APs as follows \begin{equation} \label{Prob:NMSEk} \begin{aligned} & \underset{\{ \theta_n \} }{\mathrm{minimize}} && \sum_{m=1}^M \sum_{k=1}^K \mathrm{NMSE}_{mk} \\ & \,\,\mathrm{subject \,to} & & -\pi \leq \theta_n \leq \pi, \forall n. \end{aligned} \end{equation} The optimal phase shifts solution to problem~\eqref{Prob:NMSEk} is obtained by exploiting the statistical CSI that include the large-scale fading coefficients and the covariance matrices. Problem~\eqref{Prob:NMSEk} is a fractional program, whose globally-optimal solution is not simple to be obtained for an RIS with a large number of independently tunable elements. Nonetheless, in the special network setup where the direct links from the APs to the users are weak enough to be negligible with respect to the RIS-assisted links, the optimal solution to problem~\eqref{Prob:NMSEk} is available in a closed-form expression as summarized in Corollary~\ref{corollary:EqualPhase}. \begin{corollary} \label{corollary:EqualPhase} If the direct links are weak enough to be negligible and the RIS-assisted channels are spatially correlated as formulated in \eqref{eq:CovarMa}, the optimal maximizer of the optimization problem in \eqref{Prob:NMSEk} is $\theta_1 = \ldots = \theta_N$, i.e., the equal phase shift design is optimal. \end{corollary} \begin{proof} The proof follows by analyzing the objective function of problem~\eqref{Prob:NMSEk} with respect to the phase-shift elements. The detailed proof is available in the journal version \cite{Chien2021TWC}. \end{proof} Corollary~\ref{corollary:EqualPhase} provides a simple but effective option to design the phase shifts of the RIS while ensuring the optimal estimation of the aggregated channels according to the sum- NMSE minimization criterion, provided that the direct link are completely blocked and the spatial correlation model in \eqref{eq:CovarMa} holds true. Therefore, an efficient channel estimation protocol can be designed even in the presence of an RIS with a large number of engineered scattering elements. The numerical results in Section~\ref{Sec:NumRes} show that the phase shift design in Corollary~\ref{corollary:EqualPhase} offers good gains in terms of net throughput even if the direct links are not negligible. \vspace*{-0.2cm} \section{Uplink Data Transmission and Performance Analysis With MR Combining}\label{Sec:UL} \vspace*{-0.1cm} In this section, we introduce a procedure to detect the uplink transmitted signals and derive an asymptotic closed-form expression of the ergodic net throughput. \vspace*{-0.2cm} \subsection{Uplink Data Transmission Phase} \vspace*{-0.15cm} In the uplink, all the $K$ users transmit their data to the $M$ APs simultaneously. Specifically, the user $k$ transmits a modulated symbol $s_k$ with $\mathbb{E}\{|s_k|^2\} =1$. This symbol is weighted by a power control factor $\sqrt{\eta_k}$, $0 \leq \eta_k \leq 1$. Then, the received baseband signal, $y_{um} \in \mathbb{C},$ at the AP~$m$ is \begin{equation} \label{eq:yum} y_{m} = \sqrt{\rho} \sum_{k=1}^K \sqrt{\eta_{k}} u_{mk} s_k + w_{m}, \end{equation} where $\rho$ is the normalized uplink SNR of each data symbol and $w_{m}$ is the normalized additive noise with $w_{m} \sim \mathcal{CN}(0,1)$. For data detection, the MRC method is used at the CPU, i.e., $\hat{u}_{mk}, \forall m,k,$ in \eqref{eq:ChannelEst} is employed to detect the data transmitted by the user~$k$. In mathematical terms, the corresponding decision statistic is \begin{equation} \label{eq:ruk} r_{k} = \sqrt{\rho} \sum_{m=1}^M \sum_{k'=1}^K \sqrt{\eta_k} \hat{u}_{mk}^\ast u_{mk'} s_{k'} + \sum_{m=1}^M \hat{u}_{mk}^\ast w_{m}. \end{equation} Based on the observation $r_{k}$, the uplink ergodic net throughput of the user~$k$ is analyzed in the next subsection. \vspace*{-0.2cm} \subsection{Asymptotic Analysis} \label{subsec:Asymul} \vspace*{-0.15cm} Since the number of APs, $M$, and the number of tunable elements of the RIS, $N$, can be large, we analyze the performance of two case studies: $(i)$ $N$ is fixed and $M$ is large; and $(ii)$ both $N$ and $M$ are large. The asymptotic analysis is conditioned upon a given setup of the CSI. To this end, the uplink weighted signal in \eqref{eq:ruk} is split into three terms based on the pilot reuse set $\mathcal{P}_k$, as follows \begin{equation} \label{eq:rukv1} \begin{split} & r_{k} = \underbrace{\sqrt{\rho} \sum_{k' \in \mathcal{P}_k } \sum_{m=1}^M \sqrt{\eta_{k'}} \hat{u}_{mk}^\ast u_{mk'} s_{k'}}_{\mathcal{T}_{k1}} + \\ & \underbrace{\sqrt{\rho} \sum_{k' \notin \mathcal{P}_k} \sum_{m=1}^M \sqrt{\eta_{k'}} \hat{u}_{mk}^\ast u_{mk'} s_{k'}}_{\mathcal{T}_{k2}} + \underbrace{\sum_{m=1}^M \hat{u}_{mk}^\ast w_{m}}_{\mathcal{T}_{k3}}, \end{split} \end{equation} where $\mathcal{T}_{k1}$ accounts for the signals received from all the users in $\mathcal{P}_k$, and $\mathcal{T}_{k2}$ accounts for the mutual interference from the users that are assigned orthogonal pilot sequences. The impact of the additive noise obtained after applying MR combining is given by $\mathcal{T}_{k3}$. From \eqref{eq:ReceivedPilotv1}-\eqref{eq:ChannelEst}, we obtain the following identity \begin{equation} \label{eq:Termv1} \begin{split} & \sum_{m=1}^M \sqrt{\eta_{k'}} \hat{u}_{mk}^\ast u_{mk'} = \sum_{k'' \in \mathcal{P}_k \setminus \{k' \} } \sum_{m=1}^M \sqrt{\eta_{k'}p\tau_p} c_{mk} u_{mk'} u_{mk''}^{\ast} \\ &+ \sum_{m=1}^M \sqrt{\eta_{k'} p \tau_p} c_{mk} |u_{mk'}|^2 + \sum_{m=1}^M \sqrt{\eta_{k'}} c_{mk} u_{mk'} w_{pmk}^\ast, \end{split} \end{equation} \subsubsection{Case I} $N$ is fixed and $M$ is large, i.e., $M \rightarrow \infty$. In this case, we divide both sides of \eqref{eq:Termv1} by $M$ and exploits Tchebyshev’s theorem \cite{cramer2004random}\footnote{Let $X_1, \ldots, X_n$ be independent random variables such that $\mathbb{E}\{ X_i \} = \bar{x}_i$ and $\mathsf{Var}\{ X_i\} \leq c < \infty$. Then, Tchebyshev's theorem states $\frac{1}{n}\sum_{n'=1}^n X_{n'} \xrightarrow[n \rightarrow \infty]{P} \frac{1}{n} \sum_{n'} \bar{x}_{n'}.$} to obtain \begin{multline} \label{eq:Tchev1} \frac{1}{M} \sum_{m=1}^M \sqrt{\eta_{k'}} \hat{u}_{mk}^\ast u_{mk'} \xrightarrow[M \rightarrow \infty ]{P} \\ \frac{1}{M} \sum_{m=1}^M \sqrt{\eta_{k'} p \tau_p} c_{mk} \big(\beta_{mk'} + \mathrm{tr}\big( \pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \big) \big), \end{multline} where $\xrightarrow{P}$ denotes the convergence in probability.\footnote{A sequence $\{ X_n \}$ of random variables converges in probability to the random variable $X$ if, for all $\epsilon > 0$, it holds that $\lim_{n \rightarrow \infty} \mathrm{Pr}(|X_n - X| > \epsilon ) = 0$, where $\mathrm{Pr}(\cdot)$ denotes the probability of an event.} Note that the second and third terms in \eqref{eq:Termv1} converge to zero. By inserting \eqref{eq:Tchev1} into the decision variable in \eqref{eq:rukv1}, we obtain the following deterministic value \begin{multline} \label{eq:Asympt1} \frac{1}{M}r_{k} \xrightarrow[M\rightarrow \infty]{P} \\ \frac{1}{M} \sum_{k' \in \mathcal{P}_k} \sum_{m=1}^M \sqrt{\eta_{k'} p \tau_p \rho_u} c_{mk} \big(\beta_{mk'} + \mathrm{tr}\big( \pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \big) \big) s_{k'}, \end{multline} because $\mathcal{T}_{k2}/M \rightarrow 0$ and $\mathcal{T}_{k3}/M \rightarrow 0 $ as $M \rightarrow \infty$. The result in \eqref{eq:Asympt1} unveils that, for a fixed $N$, the channels become asymptotically orthogonal. In particular, the small scale fading, the non-coherent interference, and the additive noise vanish. The only residual impairment is the pilot contamination caused by the users that employ the same pilot sequence. Due to pilot contamination, the system performance cannot be improved by adding more APs if MRC is used. The contributions of both the direct and RIS-assisted indirect channels appear explicitly in \eqref{eq:Asympt1} through $\beta_{mk}$ and $\mathrm{tr}(\pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'})$, respectively. \subsubsection{Case II} Both $N$ and $M$ are large, i.e., $N\rightarrow \infty$ and $M \rightarrow \infty$. We first need some assumptions on the covariance matrices $\mathbf{R}_m$ and $\widetilde{\mathbf{R}}_{k}$, as summarized as follows. \begin{assumption} \label{Assumption1} For $m= 1,\ldots,M$ and $k=1,\ldots,K,$ the covariance matrices $\mathbf{R}_m$ and $\widetilde{\mathbf{R}}_{k}$ are assumed to fulfill the following properties \begin{align} &\underset{N}{\limsup} \, \| \mathbf{R}_m\|_2 < \infty, \underset{N}{\liminf} \, \frac{1}{N} \mathrm{tr} ( \mathbf{R}_m) > 0, \label{eq:Asymp1}\\ &\underset{N}{\limsup} \, \| \widetilde{\mathbf{R}}_{k} \|_2 < \infty, \underset{N}{\liminf} \, \frac{1}{N} \mathrm{tr} ( \widetilde{\mathbf{R}}_{k}) > 0. \label{eq:Asymp2v1} \end{align} \end{assumption} The assumptions in \eqref{eq:Asymp1} and \eqref{eq:Asymp2v1} imply that the largest singular value and the sum of the eigenvalues (counted with their mutiplicity) of the $N \times N$ covariance matrices that characterize the spatial correlation among the channels of the RIS elements are finite and positive. Dividing both sides of \eqref{eq:Termv1} by $MN$ and applying Tchebyshev’s theorem, we obtain \begin{multline}\label{eq:AsymMNUL} \frac{1}{MN} \sum_{m=1}^M \sqrt{\eta_{k'}} \hat{u}_{mk}^\ast u_{mk'} \xrightarrow[\substack{M \rightarrow \infty\\ N \rightarrow \infty} ]{P} \\ \frac{1}{MN} \sum_{m=1}^M \sqrt{\eta_{k'} p\tau_p \rho_u} c_{mk} \mathrm{tr}\big( \pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \big). \end{multline} We observe that $\pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'}$ is similar to $\widetilde{\mathbf{R}}_{k'}^{1/2} \pmb{\Phi} \mathbf{R}_{m} \pmb{\Phi}^H \widetilde{\mathbf{R}}_{k'}^{1/2}$, which is a positive semi-definite matrix.\footnote{Two matrices $\mathbf{A}$ and $\mathbf{B}$ of size $N \times N$ are similar if there exists an invertible $N \times N$ matrix $\mathbf{U}$ such that $\mathbf{B} = \mathbf{U}^{-1} \mathbf{A} \mathbf{U}$.} Because similar matrices have the same eigenvalues, it follows that $\mathrm{tr}\big( \pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \big) >0$. Based on Assumption~\ref{Assumption1}, we obtain the following inequalities \begin{equation} \label{eq:traceConv} \begin{split} & \frac{1}{N}\mathrm{tr}\big(\pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \big) \stackrel{(a)}{\leq} \frac{1}{N} \| \pmb{\Phi} \|_2 \mathrm{tr}\big( \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \big) \\ & \stackrel{(b)}{=} \frac{1}{N}\mathrm{tr}\big( \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \mathbf{R}_m \big) \stackrel{(c)}{\leq} \frac{1}{N} \| \widetilde{\mathbf{R}}_{k'} \|_2 \mathrm{tr}(\mathbf{R}_{m}), \end{split} \end{equation} where $(a)$ is obtained by an inequality on the trace of the product of matrices; $(b)$ follows because $\|\pmb{\Phi}\|_2 = 1$; and $(c)$ is obtained from Assumption~\ref{Assumption1}. Based on Assumption~\ref{Assumption1}, in addition, the last inequality in \eqref{eq:rukv1} is bounded by a positive constant. From \eqref{eq:AsymMNUL} and \eqref{eq:traceConv}, therefore, the decision variable in \eqref{eq:rukv1} can be formulated as \begin{multline} \label{eq:Asymp2} \frac{1}{MN}r_{k} \xrightarrow[\substack{M\rightarrow \infty\\ N \rightarrow \infty}]{P} \\ \frac{1}{MN} \sum_{k' \in \mathcal{P}_k} \sum_{m=1}^M \sqrt{\eta_{k'} p\tau_p \rho_u} c_{mk} \mathrm{tr}\big( \pmb{\Phi}^H \mathbf{R}_m \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \big) s_{k'}. \end{multline} The expression obtained in \eqref{eq:Asymp2} reveals that, as $M,N \rightarrow \infty$, the post-processed signal at the CPU consists of the desired signal of the intended user $k$ and the interference from the other users in $\mathcal{P}_k$. Compared with \eqref{eq:Asympt1}, we observe that \eqref{eq:Asymp2} is independent of the direct links and depends only on the RIS-assisted indirect links. This highlights the potentially promising contribution of an RIS, in the limiting regime $M,N \rightarrow \infty$, for enhancing the system performance. \vspace*{-0.1cm} \subsection{Uplink Ergodic Net Throughput Analysis with a Finite Number of APs and Phase Shifts} \vspace*{-0.1cm} We now focus our attention on the practical setup in which $M$ and $N$ are both finite. By utilizing the user-and-then forget channel capacity bounding method \cite{Chien2021TWC}, the uplink ergodic net throughput of the user $k$ can be computed in a closed-form expression for \eqref{eq:ULRateMRC} as given in Theorem~\ref{theorem:ULMR}. \begin{theorem} \label{theorem:ULMR} If the CPU utilizes the MRC method, a lower bound closed-form expression for the uplink net throughput of the user~$k$ is given as follows \begin{equation} \label{eq:ULRateMRC} R_{k} = B\nu\left( 1 - \tau_p/\tau_c \right) \log_2 \left( 1 + \mathrm{SINR}_{k} \right), \mbox{[Mbps]}, \end{equation} where $B$ is the system bandwidth measured in MHz and $0 \leq \nu \leq 1$ is the portion of each coherence interval that is dedicated to the uplink data transmission. The effective uplink signal-to-noise-plus-interference ratio (SINR) is \begin{equation} \label{eq:ClosedFormSINR} \mathrm{SINR}_{k} = \rho \eta_{k} \left( \sum_{m=1}^M \gamma_{mk} \right)^2 \big/ (\mathsf{MI}_{k} + \mathsf{NO}_{k}), \end{equation} where $\mathsf{MI}_{k}$ is the mutual interference and the noise denoted by $\mathsf{NO}_{k}$ are, respectively, given by \begin{align} &\mathsf{MI}_{k} = \rho_u \sum_{k'=1}^K \sum_{m=1}^M \eta_{k'} \gamma_{mk} \delta_{mk'} + p \tau_p \rho_u \sum_{k' \in \mathcal{P}_k} \sum_{m=1}^M \eta_{k'} c_{mk}^2 \notag \\ & \times \mathrm{tr}(\pmb{\Theta}_{mk'}^2) + p \tau_p \rho_u \sum_{k' =1 }^K \sum_{k'' \in \mathcal{P}_k} \sum_{m=1}^M \sum_{m'=1}^M\eta_{k'} c_{mk}c_{m'k} \times \notag \\ & \mathrm{tr}( \pmb{\Theta}_{mk'} \pmb{\Theta}_{m'k''}) + p \tau_p \rho_u \sum_{k' \in \mathcal{P}_k \setminus \{ k\} } \eta_{k'} \left(\sum_{m=1}^M c_{mk} \delta_{mk'} \right)^2,\\ & \mathsf{NO}_{k} = \sum_{m=1}^M \gamma_{mk}, \end{align} with $\delta_{mk'} =\beta_{mk'} + \mathrm{tr}\big( \pmb{\Phi}^H \mathbf{R}_{m} \pmb{\Phi} \widetilde{\mathbf{R}}_{k'} \big)$, $c_{mk}$ given in \eqref{eq:cmk}, and $\gamma_{mk}$ given in \eqref{eq:gammamk}. \end{theorem} \begin{proof} The main idea of proof is to average out the randomness by using the use-and-then-forget capacity bounding technique and fundamental properties of Massive MIMO. The detailed proof is available in the journal version \cite{Chien2021TWC}. \end{proof} By direct inspection of the SINR in \eqref{eq:ClosedFormSINR}, the numerator increases with the square of the sum of the variances of the channel estimates, $\gamma_{mk},\forall m,$ thanks to the joint coherent transmission. On the other hand, the first term in the denominator represents the power of the interference. Due to the limited and finite number of orthogonal pilot sequences being used, it represents the impact of pilot contamination. The last term is the additive noise. The SINR in \eqref{eq:ClosedFormSINR} is a multivariate function of the matrix of phase shifts of the RIS and of the channel statistics, i.e., the channel covariance matrices. Compared with conventional Cell- Free Massive MIMO systems, the strength of the desired signal increases thanks to the assistance of an RIS. However, the coherent and non-coherent interference become more severe as well, due to the need of estimating both the direct and indirect links in the presence of an RIS. \begin{figure*}[t] \begin{minipage}{0.33\textwidth} \centering \includegraphics[trim=0.9cm 0cm 1.3cm 0.2cm, clip=true, width=2.4in]{FigActiveProbSumUserR1} \vspace*{-0.5cm}\\ (a) \vspace*{-0.1cm} \end{minipage} \begin{minipage}{0.33\textwidth} \centering \includegraphics[trim=0.9cm 0cm 1.3cm 0.5cm, clip=true, width=2.4in]{FigCDFSumUserR1} \vspace*{-0.5cm}\\ (b) \vspace*{-0.1cm} \end{minipage} \begin{minipage}{0.33\textwidth} \centering \includegraphics[trim=0.9cm 0cm 1.3cm 0.5cm, clip=true, width=2.4in]{FigDiffPhasePerUserUplinkR1} \vspace*{-0.5cm}\\ (c) \vspace*{-0.1cm} \end{minipage} \caption{The sum net throughput [Mbps]: $(a)$ Average sum net throughput versus the unblocked probability of the direct links; $(b)$ CDF of the sum net throughput with the unblocked probability of the direct links $\tilde{p} = 0.2$; $(c)$ Sum net throughput as a function of the phase shift setup (equal or random) and the unblocked probability of the direct links $\tilde{p} = 0.2$.} \label{FigPerformance} \vspace*{-0.6cm} \end{figure*} \vspace*{-0.2cm} \section{Numerical Results} \label{Sec:NumRes} \vspace*{-0.2cm} We consider a geographic area of size $1$~km$^2$ that is wrapped around at the edges. The locations of $100$ APs and $10$ users are given in terms of $(x,y)$ coordinates. To simulate a harsh communication environment, the APs are uniformly distributed in the sub-region $x,y \in [-0.75, -0.5]$~km, while the users are uniformly distributed in the sub-region $x,y \in [0.375, 0.75]$~km. An RIS with $N = 900$ is located at the origin, i.e., $(x, y) = (0, 0)$. Each coherence interval comprises $\tau_c = 200$ symbols and $\tau_p =5$ orthonormal pilot sequences. The large-scale fading coefficients $\alpha_m$ and $\tilde{\alpha}_{mk}$ are generated according to the three-slope propagation model in \cite{ngo2017cell}. The large-scale fading coefficient $\beta_{mk}$ is formulated as $\beta_{mk} = \bar{\beta}_{mk}a_{mk},$ where $\bar{\beta}_{mk}$ is generated by the three-slope propagation model in \cite{ngo2017cell}. The binary variables $a_{mk}$ accounts for the probability that the direct links are unblocked, and it is defined as $a_{mk} =1$ with probability $\tilde{p}$. Otherwise, $a_{mk} =0$ with probability $1 -\tilde{p}$, where $\tilde{p} \in [0,1]$ is the probability that the direct link is not blocked.The covariance matrices are generated according to the spatial correlation model in \eqref{eq:CovarMa} with $d_H = d_V = \lambda/4$. The pilot power is $100$~mW and $\nu = 1$. The power control coefficients are $\eta_k = 1, \forall k$. Without loss of generality, in particular, the $N$ phase shifts in $\pmb{\Phi}$ are all set equal to $\pi/4$, except in Fig.~\ref{FigPerformance}(c) with different phase shifts. Three system configurations are considered for comparison: \begin{itemize} \item[$i)$] \textit{RIS-Assisted Cell-Free Massive MIMO}: This is the proposed system model where the direct links are unblocked with probability $\tilde{p}$. It is denoted by ``RIS-CellFree". \item[$ii)$] \textit{Conventional Cell-Free Massive MIMO}: This is the same as the previous model with the only exception that the RIS is not deployed. It is denoted by ``CellFree". \item[$iii)$] \textit{Cell-Free Massive MIMO without the direct links}: This is the worst case study in which the direct links are blocked with unit probability and the uplink transmission is ensured only through the RIS. This setup is denoted by ``RIS-CellFree-NoLOS". \end{itemize} In Fig.~\ref{FigPerformance}(a), we illustrate the sum net throughput as a function of the probability $\tilde{p}$. In particular, the average sum net throughput is defined as $\sum_{k=1}^K \mathbb{E} \{ R_{k} \}$. Cell-Free Massive MIMO provides the worst performance if the blocking probability is large ($\tilde{p}$ is small). If the direct links are unreliable, as expected, the net throughput offered by Cell-Free Massive MIMO tends to zero if $\tilde{p} \rightarrow 0$. In addition, the proposed RIS-assisted Cell-Free Massive MIMO setup offers the best net throughput, since it can overcome the unreliability of the direct links. An RIS is particularly useful if $\tilde{p}$ is small since in this case the direct links are not able to support a high throughput. Fig.~\ref{FigPerformance}(b) compares the three considered systems in terms of sum net throughput (defined as $\sum_{k=1}^K R_{k}$) when $\tilde{p} = 0.2$. We observe the net advantage of the proposed RIS-assisted Cell-Free Massive MIMO system. The worst-case RIS-assisted Cell-Free Massive MIMO system setup (i.e., $\tilde{p} = 0$) outperforms the Cell-Free Massive MIMO setup in the absence of an RIS. Fig.~\ref{FigPerformance}(c) focuses on the RIS-asissted Cell-Free Massive MIMO setup, since it provides the best performance. We compare the sum net throughput as a function of the phase shifts of the RISs (random and uniform phase shifts according to Corollary \ref{corollary:EqualPhase} in the presence of spatially-correlated and spatially-independent fading channels according to \eqref{eq:CovarMa}. In the presence of spatial correlation, we consider $\mathbf{R}_m = \alpha_m d_H d_V \mathbf{I}_N$ and $\widetilde{\mathbf{R}}_k = \tilde{\alpha}_{k} d_H d_V \mathbf{I}_N, \forall m,k$. If the spatial correlation is not considered, there is no significant difference between the random and uniform phase shifts setup. In the presence of spatial correlation, on the other hand, the proposed uniform phase shift design, which is obtained from Corollary~\ref{corollary:EqualPhase}, provides a much better throughput. This result highlights the relevance of using even simple optimization designs for RIS-assisted communications in the presence of spatial correlation. \vspace*{-0.2cm} \section{Conclusion}\label{Sec:Conclusion} \vspace*{-0.2cm} We have considered an RIS-assisted Cell-Free Massive MIMO system and have introduced an efficient channel estimation scheme to overcome the high channel estimation overhead. An optimal design for the phase shifts of the RIS that minimizes the channel estimation error has been introduced and has been used for system analysis. Also, a closed-form expression of the ergodic net throughput for the uplink data transmission phase has been proposed. Based on them, the performance of RIS-assisted Cell-Free Massive MIMO has been analyzed as a function of the fading spatial correlation and the blocking probability of the direct AP-user links. The numerical results have shown that the presence of an RIS is very useful if the AP-user links are mostly unreliable with high probability. \vspace*{-0.2cm} \bibliographystyle{IEEEtran}
{'timestamp': '2021-09-17T02:10:29', 'yymm': '2109', 'arxiv_id': '2109.05444', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05444'}
arxiv
\section{Introduction} Hard disk drives or HDDs have been the primary storage systems in large-scale data centers. Like any electronic device, HDDs also have a limited lifespan. To monitor operational health of these devices, operators frequently rely on S.M.A.R.T. (Self-Monitoring Analysis and Reporting Technology). S.M.A.R.T. logs device health data such as power-on hours, temperature and sector error rates, head flying hours and so on. \cite{smart}. These are set by each drive manufacturer along with a threshold for each attribute which is traditionally used to detect failure. If a hard drive is operating as it should, each S.M.A.R.T. attribute should ideally not be outside this threshold. Backblaze, a cloud storage and data backup company, has over 171,000 hard drives in their data center \cite{backblaze}. With an annualized failure rate of 0.93\% in 2020, over a thousand of their hard drives failed \cite{klein_2021}. It follows that it is necessary for hard drive manufacturers and companies like Backblaze to know the remaining useful life (RUL) of their hard drives. This would not only help reduce downtime at a large data center, but would help protect valuable user data. S.M.A.R.T. attributes are a great way of detecting imminent failure of hard drives \cite{beach_2021}, but it would be ideal to predict the RUL of a hard drive. This would allow consumers to know that they need to start making backups and initiate planning to buy a new hard drive long before it fails. It would also allow companies like Backblaze to prepare to replace a drive ahead of time. \textbf{Contributions:} In this work, we propose methods for data standardization, normalization and RUL prediction for working with the highly class-imbalanced Backblaze data using a Bidirectional Long Short Term Memory Network \cite{bidirection_lstm} with multiple days of look-back period. Our approach considers S.M.A.R.T. features which are highly correlated to failure and builds a prediction pipeline that takes into consideration the long-term temporal relations in the failure data. We employ a vanilla Long Short Term Memory Network under similar data preprocessing conditions to contend that the Bi-LSTM outperforms the standard LSTM implementation on all lookback periods. We also consider a Random Forest baseline which upon inspection is found to generate sub-par learning capability on the failure data thereby reinforcing the need for learning temporal sequence patterns as our Bi-LSTM model does. At an accuracy of 96.4\% for a 15 day look-back, our model is among the state-of-the-art reported in the literature. An overview of our approach is shown in Fig. \ref{fig:workflow}. \begin{figure*}[ht!] \begin{center} \makebox[\linewidth]{ \includegraphics[scale=0.5]{figures/workflow-complex.pdf} } \caption{Overview of the workflow for our approach.} \label{fig:workflow} \end{center} \end{figure*} \section{Previous Approaches} In this section, we review some of the previous works focused on remaining useful life prediction of HDDs. For ease of review, we have divided these into statistical and machine learning approaches. \subsection{\textbf{Statistical Approaches}} Remaining useful life prediction is inherently a time series problem. The S.M.A.R.T. features of each hard drive are recorded at a constant time interval. Each S.M.A.R.T. attribute value is dependant on the previous value. This lack of independence makes this problem difficult to solve with simple statistical models such as linear regression. This section will briefly cover a few statistical approaches historically taken. For more details, the reader is encouraged to see the cited papers. One such approach (Wang et al.) involved using a two-step parametric method. The first step was transforming the variables into Gaussian variables with the Box-Cox transformation, using Mahalanobis distance to get the variables into one index. This was used for anomaly detection. Second, a generalized likelihood ratio test with a sliding window was used to predict failure. This method resulted in around a 68\% failure detection rate \cite{wang_ma_chow_tsui_2014}. Another approach (Wang et al.) used an adaptive Rao-Blackwellized particle filter error tracking method. This gave a health status to the HDD. The failure was predicted by using a threshold that is placed by the adaptive error tracking. Using an accelerated degradation test, they were able to achieve a 97.44\% failure detection rate \cite{wang_he_jiang_chow_2021}. It should be noted that this approach was used to predict whether a hard disk drive would fail, not the RUL of an HDD. A third approach (He, Yang and Xie) proposes using the Weibull distribution instead of the exponential distribution to predict RUL. Using sectional Weibull modeling can better capture the nuances of the HDD time-to-failure distribution \cite{6407546}. The above approaches rely heavily on a deep understanding of specific statistical techniques to predict impending failure. Model-driven approaches are highly pointed and they do not always end up learning the complex, underlying patterns in unstructured failure data with class imbalance. \subsection{\textbf{Data-driven Approaches}} In recent years, there has been an exponential rise in the adoption of data-driven approaches for fault prediction tasks. The solution frameworks involving the (a) prediction of RUL of an HDD instance and (b) classifying whether an HDD instance will fail within a certain number of days have both seen significant improvements with the adoption of machine learning and and deep learning approaches. This section will briefly survey some machine learning methods widely used in HDD RUL prediction. A Bayesian Network is "a probabilistic graphical model that represents a set of random variables and their conditional dependencies" \cite{chaves_de}. These use the S.M.A.R.T. attributes to predict the probability that a hard drive will fail at a particular time. Simple (Chaves et al.) \cite{chaves_de, chaves_de_2016} and Combined Bayesian Networks (Jia et al.) \cite{pang_jia_stones_wang_liu_2016} have been used to predict the RUL. The Combined Bayesian Network is able to combine multiple machine learning classifiers to give a model that can predict more accurately than an individual classifier. Relatively-straightforward machine learning models have also had some success in solving this problem. Machine learning algorithms such as Support Vector Machines (SVM), Decision Trees (DT), and Random Forests (RF) are frequently used. These algorithms are often used as a baseline or control to compare a proposed method to \cite{hu_han_xu_jiang_qi_2020}, as they are known to be well-performing. However, RF algorithms have shown to predict the RUL very well, and are commonly treated as more than a baseline \cite{shen_wan_lim_yu_2018, anantharaman_qiao_jadav_2018, aussel_jaulin_gandon_petetin_fazli_chabridon_2017}. Random Forest algorithms do not require a sequence of time data, so the input of current S.M.A.R.T. attribute values would be enough to predict the RUL \cite{anantharaman_qiao_jadav_2018}. This means that RF approaches need less data, offering an advantage over some of the time-dependant models discussed later. By far, the most common method to predict the RUL of hard drives involves using Long Short-Term Memory networks (LSTMs). These are an improvement on Recurrent Neural Networks that can help solve the vanishing gradient problem \cite{LSTM}. A detailed explanation of the LSTM and one of its variants is provided in the next section. LSTMs \cite{aussel_jaulin_gandon_petetin_fazli_chabridon_2017, basak_sengupta_dubey_2019, shen_ren_wan_lan_2021}, Convolutional Neural Network LSTMs \cite{246172}, Clustered LSTMs \cite{basak_sengupta_wen_dubey_2021}, and Attention LSTMs \cite{chen_wu_zhao_guretno_yan_li_2021, wang_wang_sun_2021} have all been used to predict hard drive failure or the RUL of a hard drive with a high degree of success. A convolutional neural network LSTM (CNN-LSTM) is able to combine the benefits of both CNNs and LSTMs into one model. The CNN uses convolutional layers to reduce variation in the input. This filtered input is then passed to the LSTM, giving the LSTM better input than without the CNN. This combined model could give better results than a simple CNN or LSTM would alone \cite{246172} \cite{sainath_vinyals_senior_sak_2015}. An encoder decoder LSTM, also known as a sequence-to-sequence model, uses two models. The first model encodes the input sequence to a fixed length. The second model decodes that fixed length input and predicts a sequence of output \cite{cho_van}. Remaining useful life prediction does not necessarily call for sequence prediction. All we need to predict is one number, the RUL. However, encoder decoder models have shown great performance and are often the base to an attention LSTM, so it is worth mentioning. \section{The Long Short-Term Memory Network} Recurrent neural networks (RNNs) are a form of neural networks that are commonly used for machine learning tasks involving a sequence of inputs. This could be anything from text classification \cite{rnn_ex1} to time series forecasting \cite{rnn_ex2}. However, recurrent neural networks suffer from the vanishing gradient problem which occurs when the network's weights are being updated based on the gradient during backpropagation. The gradient gets increasingly small as the training continues, eventually keeping the network from learning. To get around this problem, the Long Short-Term Memory Network (LSTM) was introduced \cite{LSTM}. \subsection{\textbf{Vanilla LSTM}} The LSTM introduces a cell state that contains a series of gates in order to gain more control about the information that is retained between cells. The LSTM has a forget, input and output gate. The combination of these essentially allows the LSTM cells to extend its short term memory, keeping any information it needs to through the entirety of the learning process. Each gate contains neural networks that serve a specific purpose and contain activation functions such as sigmoid. The forget gate takes in information from the previous cell and current input to decide what to keep or forget. Whatever information is kept goes through the input gate. This determines what values will be updated in the cell. The $tanh$ function is applied on the cell state and current input for regulation. The cell state is then updated according to the combination of forget and input gates. Using the current cell gates and state, the output gate decides what to pass on to the next cell. A diagram outlining the LSTM cell is shown in Fig. \ref{fig:LSTM}. \begin{figure} \centering \includegraphics[width=\columnwidth]{figures/LSTM_arch.pdf} \caption{The Structure of an LSTM Cell} \label{fig:LSTM} \end{figure} \subsection{\textbf{Bidirectional LSTM}} Numerous variants of LSTMs have been introduced to improve performance. We use one such variant - the Bidirectional LSTM or Bi-LSTM - in combination with specialized normalization strategies to predict and improve upon the HDD RUL as predicted by vanilla LSTMs. A bidirectional LSTM is a variant of an LSTM that consists of two LSTMs. These LSTMs run at the same time. One runs on the input sequence and the other runs backwards on the input sequence \cite{guo_wang_chen_ge_chen_2018}. In this way, the LSTM runs in both directions. In this problem, one could think of one direction of the LSTM running on the sequence of hard drive data leading up to failure and another running on the sequence as the hard drive gets further away from failure. This allows the LSTM to better learn the relationship between the features and the remaining useful life. Fig. \ref{fig:BiDirectional} shows the architecture of a bidirectional LSTM. \begin{figure} \centering \includegraphics[width=\columnwidth]{figures/BiDirectional.pdf} \caption{Bidirectional LSTM Architecture} \label{fig:BiDirectional} \end{figure} \section{Data Preprocessing} \label{The Data} Backblaze is a cloud storage company that has over 170,000 HDDs used by customers across the globe. Each quarter, they release snapshots of all of their hard disk drives \cite{backblaze}. In these snapshots, there are daily statistics for each HDD including S.M.A.R.T. features and a few other features for each HDD. Among those is whether or not a HDD failed on a given day. If it failed, it it marked with a 1 and removed from the subsequent snapshots. \subsection{\textbf{Data Collection}} Using the Backblaze data from quarter 4 for 2019 and quarters 1 and 2 for 2020, we programmatically created a dataset containing the S.M.A.R.T. features leading up to failure for one hard drive model. Only one model was selected due to the inconsistency in meanings of S.M.A.R.T. features between models. The model selected was the Seagate ST4000DM000. We target this model because of the high prevalence of disk failures compared to other models. This selection also allows for comparison with several existing state-of-the-art approaches in the literature such as Basak et al. \cite{basak_sengupta_wen_dubey_2021} and Anantharaman et al. \cite{anantharaman_qiao_jadav_2018}. Basak et al. used a spatio-temporal approach to predict the RUL of HDDs combining LSTM and hierarchical clustering. They achieved a mean absolute error (MAE) of 2.4 days for the prediction on Seagate ST4000DM000. Anantharaman et al. used two approaches: (a) a Random Forest model using the current snapshot of S.M.A.R.T. readings and (b) an LSTM which models the historical temporal pattern of the S.M.A.R.T. features. Their results suggest the Random Forest predictions are comparable to or outperforms the LSTM on Seagate ST4000DM000. In order to create our dataset, we first looked for a hard drive with the model ST4000DM000 that had failed. When one was found, the previous 60 and 120 days worth of data were gathered for that same serial number. This was then concatenated onto the dataset in the long format. For each day back, a column for the remaining useful life was also added. For example, if a failed device was found, the column for RUL would have a value of 1 on the previous day, 2 on the day before that, and so on. This allowed us to keep from having to treat this as a binary classification problem. We could instead predict the RUL value using regression. We chose to take a regression approach to this problem because we felt it remained true to the goal of the model. With regression, the model will be able to output a continuous number representing the predicted amount of days until the hard drive fails. Since the data is captured each day, this predicted number could be rounded or truncated. This will lead to a simple way to assess the performance of the model. One approach that was considered for binary classification was to iterate over each day, essentially asking the model the question "Will the hard drive fail on this day?" One could then use the first day where the model gives a value of 1 (hard drive failing) as the remaining useful life, capturing classification statistics along the way. We suspect this is how many previous approaches to RUL prediction handled this dataset, as most statistics provided in the literature are classification statistics (F Score, Precision, Recall, etc.). \subsection{\textbf{Feature Selection}} The Backblaze dataset provides dozens of S.M.A.R.T. statistics for each of its hard drives; however, not all of these are relevant. Some of the features are redundant, do not contain useful information, or are null. To remove these and reduce the complexity of the model, we used two feature selection methods. These were a correlation score and a Decision Tree. Before using any feature selection techniques, we removed all null features and features that were already normalized. Backblaze performs their own data normalization and provides raw and normalized versions of each feature reported. We chose to apply our own normalization techniques, discussed later, and therefore removed all of these features. The first method of feature selection we chose was using a correlation score. We calculated the Pearson product-moment correlation coefficient between each S.M.A.R.T. feature and the feature representing the remaining life of the hard drive. This was calculated for each hard drive instance, averaged, and then the absolute value was taken. This left us with a correlation score for each S.M.A.R.T. feature, shown in Fig. \ref{fig:correlation}. As can be seen, 5 of the features are highlighted in green. These indicate the features that we selected as the final predictors. S.M.A.R.T. 7 was included over S.M.A.R.T. 193 because it was used as a predictor in \cite{basak_sengupta_wen_dubey_2021} and we wanted to make sure a fair comparison was possible. We suspect that 193 had a higher correlation score in our analysis than S.M.A.R.T. 7 due to differences in data, but the scores of S.M.A.R.T. 7 and S.M.A.R.T. 193 were practically the same. \begin{figure} \includegraphics[width=\columnwidth]{figures/feature_correlation.pdf} \caption{Pearson Correlation Score for S.M.A.R.T. Features as bars, Feature importance from Decision Tree as diamonds.} \label{fig:correlation} \end{figure} With concerns about nonlinearity of S.M.A.R.T. feature values, we conducted another method of feature selection. We trained a simple Decision Tree regressor on the dataset using all of the features. A graph demonstrating the importance it gave to each feature is shown on top of the bar plots in Fig. \ref{fig:correlation}. The diamonds represent the importance percentage of the respective feature determined by the decision tree. The sum of each of these importances is equal to one. As can be seen, the decision tree feature importance agrees with the correlation scores. S.M.A.R.T. 7, 240, 193, 242, 9, and 241 are given the most importance and highest correlation scores. Because of this, we felt comfortable taking S.M.A.R.T. 7, 9, 240, 241, and 242 as the features for the LSTM models. As discussed, these are the same features reported in \cite{basak_sengupta_wen_dubey_2021}, which will allow for more comparability in model performance. A brief description of what each selected feature represents \cite{smart} is provided below. \\ \subsubsection{S.M.A.R.T. 7} \textbf{Seek Error Rate}. The rate of seek errors of the magnetic head. \subsubsection{S.M.A.R.T. 9} \textbf{Power-on Hours}. The total number of hours the hard drive has been powered on. \subsubsection{S.M.A.R.T. 240} \textbf{Head Flying Hours}. The amount of time a disk head has spent moving. \subsubsection{S.M.A.R.T. 241} \textbf{Total LBAs Written}. The total number of LBAs written by the hard drive. An LBA is a 512 byte section of memory. \subsubsection{S.M.A.R.T. 242} \textbf{Total LBAs Read}. The total number of LBAs read by the hard drive. \\ It seems to make intuitive sense that each of these features would be highly correlated with hard drive failure. \subsection{\textbf{Data Standardization}} A typical method of standardization would involve scaling all features of all of the data points to some standard range. When done on this data, this led to a few points being more extreme than others, see Fig. \ref{fig:standardization}. As can be seen, a few of the points have values above 10. The standardization makes the points have a mean of 0 and variance of 1. All of the points should ideally be somewhere between -2 and 2 to have an even distribution. The points that are extremely far outside of this range may inhibit the LSTM's training and reduce performance. In order to fix this, a different approach to standardization was taken. Instead of standardizing each feature from every hard drive (the full dataset), each individual hard drive was standardized independently of the other. Each feature from each hard drive was scaled such that they would have a mean of 0 and variance of 1. This heavily reduced the impact of the extreme data points. However, this did come with a cost. We could no longer apply this same scaler to the test set since each scale was dependent on the hard drive. This has potential impacts on 'across-the-board' generalization of the model, a topic which will be discussed further in the paper. Since applying the same scaler to the training and test sets was no longer an option, we took the same approach to scaling the test set and other validation sets as the training set. Each feature for each device was independently scaled to a mean of 0 and variance of 1. This approach can be applied to any hard drive data of the same shape. This means that someone using this model could easily standardize their data and run it through our model without having to apply the exact transformation as us, something one would most likely have to do with typical normalization. An alternative solution to this issue, and one that has been applied in the past \cite{basak_sengupta_wen_dubey_2021}, would have been to perform some kind of outlier detection and removal. However, this comes with the cost of losing potentially valuable data. Some points labled as outliers would be easy to justify as impossible. For example, consider a hard drive that reports its hours active as longer than the hard drive has been manufactured. Other points would not be as easy to justify removing, and there is the potential of removing something useful to the model. It also raises the question of how this would be handled in an actual implementation of the model. Would an end user have to be okay with a model simply being wrong about their hard drive's RUL if it reported one of these extreme points? If a model is trained on a dataset without these extreme points, we cannot expect it to be accurate when it inevitably encounters feature values like this outside of training. For these reasons, we did not use this approach. \begin{figure} \includegraphics[width=\columnwidth]{figures/standardization.pdf} \caption{Values for S.M.A.R.T. 7 when standardized in a traditional way (Note the extreme points)} \label{fig:standardization} \end{figure} \subsection{\textbf{Reclassification of Data}} At this point, we had a set of training data consisting of 78 hard drives with 5 S.M.A.R.T. features reported for each hard drive 60 days up to failure and the day of failure. We had 2 sets of test data. One consisted of 71 hard drives, different than the ones in the training set, with the same 5 S.M.A.R.T. features reported for each drive 60 days up to failure and the day of failure. The second test set consisted of 133 hard drives with the same 5 S.M.A.R.T. features reported 120 days up to failure and the day of failure. After visualizing the data for each day leading up to failure, a pattern begins to emerge (see Fig. \ref{fig:smart7}). It appears that a few of the reported S.M.A.R.T. features have large jumps leading up to the day of failure. This is what would be expected. For example, consider S.M.A.R.T. 7, the rate of seek errors. One would expect these errors to increase dramatically as the hard drive begins to fail. Our model will likely be predicting a lower remaining useful life of the hard drive as each feature has a dramatic change. This will be a problem when trying to predict the RUL accurately using regression. How could the model say that a hard drive has 117 days of RUL instead of 116 when the feature values for these are virtually the same and these dramatic changes do not happen until right before failure? \begin{figure} \includegraphics[width=\columnwidth]{figures/smart7.pdf} \caption{S.M.A.R.T. 7 values 60 days before failure (Notice the jump in values occurring about 15 days before failure)} \label{fig:smart7} \end{figure} To solve this problem, we reclassified every value for the remaining useful life that is over 30 days as 30 days. This created a category where the hard drive is in good working condition. This reclassification of the RUL is also done in \cite{anantharaman_qiao_jadav_2018}. Any day where a hard drive is reporting normal S.M.A.R.T. feature values can be treated as having 30+ days of remaining useful life. We believe this is appropriate given the inspection of the feature values and would still maintain the practicality of the model. A consumer using this model would have about 30 days to back up and replace their hard drive before failure, much better than the last minute notification of failure usually given. \section{Model Training} \subsection{\textbf{LSTM Models}} To train an LSTM model, the data has to be in the shape of [samples x timesteps x features]. The samples are the number of data points. (Given 60 days worth of data, including a 0th day of failure, for 78 hard drives, the number of samples is 4758.) The timesteps are the number of days of data leading up to each sample point. We trained these LSTM models with a variety of parameters for the timesteps. With these timesteps, our models do not have to make their prediction based on the current S.M.A.R.T. feature values. The models can also use the previous $n$ days' S.M.A.R.T. features to better understand the way the data is changing. The final dimension of the shape that LSTM data has to be in is the number of features. In this case, this is simply 5, as we chose 5 S.M.A.R.T. features in the previous section. With the data in the correct shape, the LSTM models could be trained. To train the basic LSTM, we created a model with an LSTM layer consisting of 32 units followed by a densely-connected neural network layer. The Adam optimizer was chosen. The model was trained for 50 epochs with a batch size of 64 and was shuffled during training. A very similar approach was taken to train the bidirectional LSTM. A Bidirectional wrapper was added to the LSTM layer that would return the last output. All of the LSTM models were trained with 5, 10, 15, and 30 timesteps. This was done to see the impact on RUL prediction when the model is given varying amounts of data. An example loss function graph for the LSTM training is provided in Fig. \ref{fig:loss}. \begin{figure} \includegraphics[width=\columnwidth]{figures/loss.pdf} \caption{Loss function for a vanilla LSTM trained with 5 days look back over 50 epochs. Loss curves of other LSTM models follow a similar trend.} \label{fig:loss} \end{figure} \subsection{\textbf{Random Forest}} To provide a baseline performance comparison, a Random Forest model was also trained. The random forest was trained on the same dataset as the LSTM models, split into 80\% training and 20\% testing. The data for the random forest was not standardized and each feature was given to it. Due to the flexibility of random forests, this would have been unnecessary and led to reduced performance when we tried it. Any data point more than 30 days away from failure was still capped at 30 days for comparability. It was trained with 1000 estimators and no max depth. \section{Results} After each model was trained, each model was then evaluated on two test sets. The first included data similar to the data the models were trained on. This test set had the 5 S.M.A.R.T. feature values for the 60 days leading up to a hard drive failure for 71 hard drives. The second test set was included to see how to the trained models would perform when given a more difficult task. Instead of predicting the RUL for data at most 60 days away from hard drive failure, the second test set included data 120 days leading up to each hard drive's failure. This dataset included 133 hard drives. Both of these test sets were standardized in the same way the training sets were. \begin{table}[htbp] \centering \caption{Performance for trained models on test data 60 days before failure.} \begin{tabular}{@{}lllll@{}} \toprule Model & Timesteps & Accuracy & R$^2$ & MAE \\ \midrule LSTM & 5 & 0.910 & 0.992 & 0.287 \\ LSTM & 10 & 0.914 & 0.994 & 0.244 \\ LSTM & 15 & 0.916 & 0.992 & 0.247 \\ Bi-LSTM & 30 & 0.910 & 0.994 & 0.238 \\ Bi-LSTM & 5 & 0.939 & 0.999 & 0.131 \\ Bi-LSTM & 10 & 0.934 & 0.997 & 0.190 \\ \textbf{Bi-LSTM} & \textbf{15} & \textbf{0.964} & \textbf{0.998} & \textbf{0.120} \\ Bi-LSTM & 30 & 0.960 & 0.998 & 0.132 \\ RF & NA & 0.667 & 0.987 & 0.483 \\ \bottomrule \\ \end{tabular} \label{tab:60days} \end{table} In order to evaluate the performance of these models, we needed some quantitative metrics. Because our models would output a continuous number representing the predicted remaining useful life, we chose R$^2$ as one of these metrics. We also collected the mean absolute error (MAE) in the predicted RUL. To concretely represent the usefulness of the models, we also collected accuracy. To determine how many correct predictions the model made, we rounded each prediction. So a prediction of 24.4 days RUL when the hard drive actually had 24 would be deemed a correct prediction. The performance of each LSTM model with 5, 10, 15, and 30 days timesteps for 60 days of data is shown in TABLE \ref{tab:60days}. The basic LSTM network is denoted as LSTM and the bidirectional LSTM is denoted as Bi-LSTM. The performance of each LSTM model with the same timesteps for 120 of data is shown in TABLE \ref{tab:120days}. The random forest model is also added for comparison at the bottom of both tables. As can be seen, the LSTM models achieve high accuracy on data within the same range it is trained on. In TABLE \ref{tab:60days} we see that the Bidirectional LSTM with a timestep of 15 days performs the best on the test set. This model achieves a MAE of 0.12, much lower than most of the state-of-the-art models, including Basak et al. \cite{basak_sengupta_wen_dubey_2021} that achieved a MAE of 2.4 on the same model. Every LSTM model outperforms the Random Forest model. All of the LSTM models are able to generalize very well to the same time frame. \begin{table}[htbp] \centering \caption{Performance for trained models when extrapolating to 120 days away from failure.} \begin{tabular}{@{}lllll@{}} \toprule Model & Timesteps & Accuracy & R$^2$ & MAE \\ \midrule LSTM & 5 & 0.479 & 0.286 & 4.305 \\ LSTM & 10 & 0.471 & 0.219 & 4.589 \\ LSTM & 15 & 0.444 & 0.028 & 5.250 \\ LSTM & 30 & 0.358 & -0.359 & 6.433 \\ Bi-LSTM & 5 & \textbf{0.497} & 0.312 & 4.145 \\ Bi-LSTM & 10 & 0.496 & 0.216 & 4.448 \\ Bi-LSTM & 15 & 0.487 & 0.071 & 4.874 \\ Bi-LSTM & 30 & 0.369 & -0.565 & 6.792 \\ RF & NA & 0.378 & \textbf{0.333} & \textbf{3.647} \\ \bottomrule \\ \end{tabular} \label{tab:120days} \end{table} Fig. \ref{fig:lstm_predictions}, Fig. \ref{fig:lstm_15_predictions}, and Fig. \ref{fig:rf_predictions} demonstrate the difference in performance between the LSTM and random forest models. All of these graphs are sorted by the actual remaining useful life for demonstrative purposes. TABLE \ref{tab:literature_performance} shows performance metrics for related data-driven approaches for hard drive health assessment. While the table is not exhaustive, it should provide some context to the performance of state-of-the-art models. \begin{table}[] \centering \caption{Performance of previous approaches for RUL prediction by various data-driven approaches.} \label{tab:literature_performance} \begin{tabular}{@{}lllll@{}} \toprule Model Type & Precision & Recall & MAE & Citation \\ \midrule Random Forest & 0.95 & 0.67 & - & Aussel et al.\cite{aussel_jaulin_gandon_petetin_fazli_chabridon_2017} \\ Attention LSTM & 0.93 & 0.96 & - & Wang et al.\cite{wang_wang_sun_2021} \\ Random Forest & 0.66 & 0.94 & - & Lu et al.\cite{246172} \\ LSTM & 0.66 & 0.88 & - & Lu et al.\cite{246172} \\ CNN-LSTM & 0.93 & 0.94 & - & Lu et al.\cite{246172} \\ Random Forest & - & - & 6.4 & Anantharaman et al.\cite{anantharaman_qiao_jadav_2018} \\ LSTM & - & - & 8.15 & Anantharaman et al.\cite{anantharaman_qiao_jadav_2018} \\ Clustered LSTM & - & - & 2.4 & Basak et al.\cite{basak_sengupta_wen_dubey_2021} \\ Bi-LSTM & - & - & 0.12 & \textbf{Our Approach}\\ \bottomrule \end{tabular} \end{table} \subsection{\textbf{Observations}} \begin{figure} \includegraphics[width=\columnwidth]{figures/LSTM_predictions.pdf} \caption{Bidirectional LSTM with 15 days lookback predictions. The points are sorted by the actual RUL.} \label{fig:lstm_predictions} \includegraphics[width=\columnwidth]{figures/LSTM_15_predictions.pdf} \caption{LSTM with 15 days lookback predictions. The points are sorted by the actual RUL.} \label{fig:lstm_15_predictions} \includegraphics[width=\columnwidth]{figures/RF_predictions.pdf} \caption{Random Forest predictions. The points are sorted by the actual RUL.} \label{fig:rf_predictions} \end{figure} Some interesting observations can be gained from the graphs in Fig. \ref{fig:lstm_predictions}, Fig. \ref{fig:lstm_15_predictions}, and Fig. \ref{fig:rf_predictions}. First, it is clear that the LSTM models outperform the Random Forest. While Fig. \ref{fig:lstm_predictions} shows almost no separation between the True RUL and the Predicted RUL for the Bi-LSTM architecture, the difference is most clearly visible in Fig. \ref{fig:rf_predictions} for the Random Forest. It is also clear that the Bi-LSTM outperforms the regular LSTM model in Fig. \ref{fig:lstm_15_predictions}. Second, we see that the LSTM models incorrectly predict the RUL more often when the hard drive is further away from failure. Most of the deviations from the actual remaining useful life are when the hard drive is in the category of 30+ days RUL. The LSTMs are more accurate when the hard drive is closer to failure, reinforcing its practical importance. Third, we can see that the Random Forest appears to have an opposite relationship with the data. The Random Forest is much less accurate the closer the hard drive gets to the day of failure. There is not a spot on Fig. \ref{fig:rf_predictions} where the Random Forest appears to consistently predict the RUL, but it is certainly worse when the actual RUL gets below 10 days. It is also worth noting that the Random Forest is appearing to overestimate the remaining useful life. A real user would probably want the model to underestimate the RUL. It is better that they replace their hard drive early than have it fail on them before they can replace it. Every model performs poorly when attempting to extrapolate far into the future. This is a common problem with statistical and machine learning prediction methods in general. From TABLE \ref{tab:120days}, we see that the Bidirectional LSTM has the highest accuracy at predicting the remaining useful life of hard drives that are twice as far away from failing (120 days) as the models were trained on (60 days). This LSTM model gets nearly half of its predictions correct. In contrast, the random forest has a lower accuracy score, but also has a higher R$^2$ and lower MAE. This implies that the random forest predictions may actually be better than the LSTM models, but the random forest does not predict the exact RUL as well. It would be hard to expect a model to be able to perform as well on data that is twice as far away as the data it was trained on, but being able to do so would highly improve the real-world usefulness of the model. \section{Standardization and Generalization} This section is dedicated to more discussion of our novel standardization approach. The benefits and downsides of this method of standardization will be explained. As mentioned in Section \ref{The Data} C, the hard drive data needed to be normalized or standardized to be used by the LSTM models. A traditional standardization approach where the entire features would be standardized as a whole was considered, but not adopted due to the poor LSTM performance. We believe the cause of this to be partially due to extreme data points influencing the weights of the LSTM and difficulty of the problem. To standardize the data, we standardized the data per sample. This means that each feature of each hard drive was essentially treated as its own dataset when applying the scaler. To better explain this, consider two hard drives: hard drive A and hard drive B. Both hard drive A and B are of the same model, but hard drive A has an extreme value for its S.M.A.R.T. 7 feature on 2 of the 60 days of data captured. When all of the S.M.A.R.T. 7 feature values are standardized together, the weight of these extreme values are maintained. The standardization we used made each feature have a mean of 0 and variance of 1. It follows that the more data points that exist, the less the extreme values of S.M.A.R.T. 7 that hard drive A contains will be pulled towards a reasonable number. For some models, such as a Random Forest, this may not be an issue, but because of the nature of recurrent neural networks these extreme values will amplify the weights and reduce the performance of the model. \begin{figure} \centering \includegraphics[width=\columnwidth]{figures/standardization-matrix.png} \caption{Visualizing a potential difference between the regular method of standardization (left) and the per sample standardization (right.)} \label{fig:matrix} \end{figure} By normalizing the S.M.A.R.T. 7 values for hard drive A and B separately, the extreme values for hard drive A will be pulled more towards reasonable values while still maintaining the patterns in their feature values that the LSTM can learn. Fig. \ref{fig:matrix} is included to visualize this process. The data included in this figure is entirely theoretical, but demonstrates the differences in the range of the data for both of the standardization techniques discussed. This method of standardization deals with the extreme data points without risking a loss of data as would be done using an outlier removal. However, this does have the potential downside of not being able to reuse the same standardization function to new data. At first, we assumed that this would cause the model to lose any generalization. From the results, we see that this was not the case. The LSTM models performed exceptionally well at predicting the RUL of hard drives after undergoing this standardization. It outperforms a model, the Random Forest, that was not standardized this way. As was also demonstrated, this method of standardization has the potential of restricting the range of time that the model is useful. We saw that the models did not perform well on 120 days worth of data. Using this standardization technique, the data around day 120 should have around the same values as the data around day 60 for the other test sets. Instead of being able to apply a standardization function that would potentially assign different values to those past 60 days, they are all standardized to a similar range. We believe that this should not discredit this technique of standardization. The performance of the LSTM models were greatly increased by this standardization technique over a traditional one. We attribute this to the complexity of the dataset. Many of the S.M.A.R.T. feature values remain relatively-unchanging until the hard drive is soon to fail. The typical method of standardization may assign a similar value for one of the S.M.A.R.T. features 60 days away from failure to one 120 days away from failure due to the nature of the data (see Fig. \ref{fig:smart7}). This, while still maintaining outliers, would probably make training an accurate LSTM very difficult. \section{Conclusion} In this paper, we attempted to solve the problem of remaining useful life prediction for hard drives. Given a series of hard drive data 60 days before the hard drive fails, we were able to predict the remaining useful life of a hard drive with state-of-the-art accuracy, outperforming previous approaches in the literature \cite{basak_sengupta_wen_dubey_2021} that worked on the same data and the same model, in particular. To accomplish this, we used both Bidirectional and vanilla Long Short-Term Memory networks, or LSTMs, with highly customized pre-processing directives. We provided a cap on the number of days a hard drive could be away from failure, giving our model a category where the hard drive is treated as operating normally. This allowed the model to better handle data where the hard drive is not failing, improving the performance. We implemented a unique method of data standardization that standardized each hard drive independently. This maintained generalization on similar time windows, but came with the cost of reducing performance on time windows much different than trained on. We also implemented a Random Forest model as a baseline to compare our LSTM models to. The random forest model was able to perform as well as the LSTM models on data in a different time window than trained on, but was severely outperformed on the test data from the same time window. \subsection{\textbf{Future Work}} While our work is able to predict the remaining useful life of hard drives well, there is still much room for future work to be done on this complex problem. Most notably, an ideal model would be able to achieve similar performance to our model while still being able to extrapolate well. There is no set number of days that one could select for training the model that would not run into extrapolation issues. Even if one were to train a model on 1,000 days of data, there is still a scenario where someone would have a hard drive that is more than 1,000 days away from failing. We attempted to solve this by implementing the cap on the remaining useful life, but the models still struggled to perform well when the time interval was doubled. Improving the extrapolation performance would be an important milestone towards true generalization and add to the applicability of the model in a real-world deployment scenario. Second, future work could explore a model that is able to predict the remaining useful life for any hard drive model. While we believe our process could easily be reproduced for any hard drive model, it would be worth exploring the possibility of training a model that would work for more than one model. Finally, future work could implement a hard drive RUL prediction model into a real system, testing the performance of the model on real-time hard drive data for hard drives that may not fail for years. \bibliographystyle{./bibliography/IEEEtran}
{'timestamp': '2021-09-14T02:16:02', 'yymm': '2109', 'arxiv_id': '2109.05351', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05351'}
arxiv
\section{Introduction} Named entity recognition (NER) aims at identifying and categorizing spans of text into a pre-defined set of classes, such as people, organizations, and locations. As a fundamental language understanding task, NER is widely adopted in question answering~\citep{molla2006named}, information retrieval~\citep{guo2009named} and other language understanding applications~\citep{nadeau2007survey, ritter2012open, peng2020soloist}. Recent advances with pre-trained language models like BERT~\citep{DBLP:conf/naacl/DevlinCLT19}, GPT-2~\citep{radford2019} and RoBERTa~\citep{DBLP:journals/corr/abs-1907-11692} have shown remarkable success in NER . However, the success of these large-scale models still relies on fine-tuning them on large amounts of in-domain labeled data. Unfortunately, obtaining NER annotations not only is expensive and time consuming, but also may not be feasible in many sensitive user applications due to data access and privacy constraints. This motivates us to study the problem of low-shot NER. Low-shot NER focuses on identifying custom entities in a new domain with only a few in-domain examples or even without any in-domain labeled data, which are refereed to as few-shot NER and zero-shot NER respectively. The success of low-shot NER requires the model to be capable of transferring learned knowledge to recognize new entity classes. Conventional NER models usually treat each class as a one-hot vector (represented by a class label) for training, and thus the trained model cannot capture the semantic meanings of those labels. In fact, the trained model could be highly associated with known classes and it is difficult to transfer learned knowledge to novel entity classes. \begin{figure*}[htb!] \centering \includegraphics[width=0.8\textwidth]{./figs/overview.png} \caption{An overview of the proposed NER system: SpanNER.} \label{fig:framework} \vspace{-0.1in} \end{figure*} To tackle this problem, several recent works~\citep{huang2020few, yang2020simple, hou2020few, Ziyadi2020ExampleBasedNE, wiseman2019label} employ prototype-based method to represent each class by a prototype based on the labeled examples and use nearest neighbor method for NER. {However, each entity class in NER task may include several fine-grained entity classes and has diverse semantic meanings. Correspondingly, the tokens or entities belonging to the same entity class are not necessarily close to each other~\citep{huang2020few}, making it challenging to represent each entity class by a prototype based on a few examples.} For example, \texttt{MISC}, one of the four entity classes in the benchmark dataset CoNLL03~\citep{Tjong2003Intro}, is a collection of {fine-grained entity classes} including events, nationalities, products and works of art. \texttt{FAC} is an entity class in the OntoNotes5~\citep{weischedel2012ontonotes} collection, including buildings, airports, highways, bridges and others. {Thus, prototype-based methods may end up learning noisy representations of prototypes and cannot achieve satisfactory performance.} Moreover, prototype-based methods have unavoidable reliance on labeled examples, thereby making them unable to extend to the zero-shot learning setting, which is also an important and practical scenario in the low-shot NER. In this paper, we propose a simple yet effective method SpanNER which can tackle few-shot as well as zero-shot NER. Instead of deriving the representations of labels purely from a few labeled examples, we propose to directly learn from the natural language descriptions of entity classes. {Such a choice provides a flexible and precise way to obtain the semantic meanings of entity classes and enable zero-shot learning.} Although using natural language as supervision has been explored in the context of zero-shot text classification, it is challenging to be adapted in the NER task. Unlike its use in text classification, natural language cannot provide direct supervision for token classification. { Inspired by machine reading comprehension (MRC) framework, we propose to decompose the NER task into two procedures: span detection and entity class inference, which can be jointly trained together. However, it is challenging to employ MRC framework into NER task especially in the low-resource setting. The MRC framework usually needs a large amount of data for training, which is not available in the low resource scenario. To handle these challenges, we propose a class-agnostic span detection module which is equipped with token sampling mechanism to mitigate the imbalanced class issue and can be trained with limited labeled data. Moreover, to handle the challenging that {several fine-grained classes are included in one entity class}, we develop an entity class attention module to focus on the most relevant information in the given entity class description that corresponds to the extracted span. Compared with direct adaption of MRC framework into NER~\cite{mrc}, the proposed method can bring more than 54\%, 30\% and 26\% improvement in average under few-shot learning, domain transfer and zero-shot learning settings respectively.} Figure~\ref{fig:framework} shows an overview of the proposed framework: the span detection stage aims to identify the span of text, and entity class inference is responsible for categorizing extracted spans based on natural language description of pre-defined entity classes. We perform extensive experiments on 5 benchmark datasets and evaluate the proposed method in the few-shot learning, domain transfer and zero-shot learning settings. The experimental results show that the proposed method brings large improvements over the state-of-the-art methods across different settings. {\noindent\textbf{Contributions.} Our model design is simple but distinguishes from that of the other NER works. To the best of our knowledge, we are the first one to learn entity class via natural language for NER task and the proposed method SpanNER achieves around 10\%, 23\% and 26\% improvement over state-of-the-art NER methods in few-shot learning, domain-transfer and zero-shot learning settings respectively.} \section{Task Formulation} NER is the process of locating and classifying named entities in text into predefined entity categories, such as person names, organizations, and locations. Formally, given a sentence with $N$ tokens $X = \{x_1,..., x_N \}$, an entity or slot value draws from a span of tokens $s = [x_i,..., x_j] (0 \leq i \leq j \leq N)$ associated with an entity class $c \in \mathcal{C}$. The corresponding annotations for given sentence $X$ are denoted as $Y$. \noindent \textbf{Few-shot NER} focuses on the NER task in a low-resource setting, where a system is only provided with a few in-domain labeled examples per entity class and the system needs to learn to identify custom entities in the domain. The task of $K$-shot NER refers to the setting with $K$ labeled input sentences per entity class $c \in \mathcal{C}$, and the training data can be denotes as $\mathcal{D}_\mathrm{train} = \{X_{i}, Y_{i}\}^{|\mathcal{C}|\times K}_{i=1}$. In this work, we leverage given training data $\mathcal{D}_\mathrm{train}$ for model fine-tuning. \noindent \textbf{Zero-shot NER} {focuses on a more challenging setting where a model is trained with a set of entity classes and then tested on a dataset with a different set of entity classes. Towards this end, zero-shot NER systems need to learn to generalize to unseen entity classes without using any labeled example. The training data for zero-shot learning can be denoted as $\mathcal{D}_\mathrm{train}$ associated with an entity class set $\mathcal{C}_\mathrm{train}$, and the test data is denoted as $\mathcal{D}_\mathrm{test}$ associated with an entity class set $\mathcal{C}_\mathrm{test}$. Note that $\exists c_\mathrm{test} \in \mathcal{C}_\mathrm{test}$ but $c_\mathrm{test} \not\in \mathcal{C}_\mathrm{train} $}. \section{Methodology} In this paper, we study how to develop an effective model which can identify custom entities in a novel domain with a small set of labeled data or even without using any labeled data. To this end, we decompose NER task into two sub-tasks: span detection and entity class inference. The span detection module is {class}-agnostic and can transfer knowledge across different entity classes. On top of span detection, the entity class inference module takes extracted spans as input to infer the semantic relationship between the spans with natural language description of entity classes. Learning from natural language has an important advantage over existing categorical label learning methods, which is its ability to capture semantic meanings of labels and enable flexible zero-shot transfer. \subsection{Span Detection} \label{sec:span_detection} Span detection is explored in the machine reading comprehension (MRC) frameworks~\citep{chen2017reading,seo2016bidirectional}, which predict the probability for each token as the starting or ending of the answer span given a question. {However, it is challenging to directly adapt MRC framework for NER task especially in the low-resource setting. First, for each entity class, the model needs to answer its associated natural language question and repeat this procedure until all the questions are answered~\cite{mrc}. Thus, such a method is not scalable when the number of entity classes increases and further exacerbates the imbalanced class issue compared to conventional NER framework. Second, the MRC framework usually needs a large amount of data, which is not available in the low resource scenario. {To handle these challenges, we propose a class-agnostic span detection module which can share the knowledge across classes and develop a token sampling mechanism to mitigate imbalanced issue. The proposed span detection module takes input sequence as input without questions and can be trained with limited labeled data}.} Given an input sequence $X = \{x_1,..., x_N \}$, we first feed $X$ into a pre-trained BERT~\citep{DBLP:conf/naacl/DevlinCLT19} to obtain token representations $\{\mathbf{x}_1,..., \mathbf{x}_N \} \in \mathbb{R}^{h \times N}$. Besides start and end index predictions, we also classify whether a token is a part of the entity span. For example, we get the score for each token being start as follows: \begin{align} s_\mathrm{start}(i) = \mathbf{w}^{\intercal}_\mathrm{start} \cdot \mathbf{x}_{i}, \end{align} where $\mathbf{w}_{\mathrm{start}} \in \mathbb{R}^{h \times 1}$ is the weight of the linear classifier. Correspondingly, the probability of a token being start index is: \begin{align} \small p_\mathrm{start}(i) = \mathrm{sigmoid} (s_\mathrm{start}(i)). \end{align} The probability calculations for end and a part of a span are the same as that of start index prediction. We then compute the probability of a span $[i, j]$ being an entity as: \begin{eqnarray*} \small p_\mathrm{match}([i,j]) &=& \mathrm{sigmoid} \Big(s_\mathrm{start}(i) + s_\mathrm{end}(j) \\ &&+ \sum_{t=i}^j s_\mathrm{span}(t)\Big). \end{eqnarray*} The span detection loss consists of three parts: start prediction loss, end prediction loss and span matching loss. The loss function of start prediction can be represented as: \begin{align} \small \mathcal{L}_\mathrm{start} = \frac{1}{N} \sum_{i=1}^N \mathrm{CE} (p_\mathrm{start}(i), y_\mathrm{start}^i), \end{align} where $\mathrm{CE}$ represents cross-entropy function and $y_\mathrm{start}^i=1$ if token $x_i$ is the start of an entity. The loss of end prediction can be calculated in a similar way. \noindent\textbf{Mitigation of imbalanced class issue.} For an input sequence with length $N$, the number of span candidate is in a $N \times N$ scale, where most of them are negative span candidates. To mitigate the imbalanced class issue, we sample a subset of negative span candidates, denoted as $O^\mathrm{neg}$. The span candidate set which corresponds to gold spans is denoted as $O^\mathrm{pos}$. Instead of using all the negative spans, we propose to sample a subset of negative spans to mitigate imbalance class issue. More specifically, we set the sampling size of negative span candidates as $|O^\mathrm{neg}| = N - |O^\mathrm{pos}|$ to reach a class ratio between positive and negative labels similar to the one in the start and end prediction losses. The role of such a mechanism is justified by an ablation study in Appendix. The span match loss is: \begin{eqnarray*} \small \mathcal{L}_\text{match} &=& -\frac{1}{N} \Big(\sum_{\substack{ (i,j) \in O^\mathrm{pos}}}\log p_\mathrm{match}([i,j]) \\ && + \sum_{\substack{ (i,j) \in O^\mathrm{neg}}}\log{(1 - p_\mathrm{match}([i,j]))}\Big). \end{eqnarray*} The overall span objective consisting of three losses to be minimized is as follows: \begin{align} \mathcal{L}_\mathrm{span} = \mathcal{L}_\mathrm{start} + \mathcal{L}_\mathrm{end} + \mathcal{L}_\mathrm{match}. \end{align} During inference, start and end indexes are first separately predicted. Then we select the consensus span between match predictions and extracted (start, end) indexes to achieve final predictions. \subsection{Natural Language Supervision} \label{sec:adaptive} Learning based on categorical labels only may discard the semantic meanings of labels, and thus it is difficult to transfer knowledge from known classes to new entity classes. To mitigate this limitation, we propose to use natural language description\footnote{In this paper, we use the definitions of entity classes from Wikipedia or annotation guidelines as their language description.} of entity classes to provide supervision for entity class inference and enable zero-shot learning. However, different with zero-shot text classification or entity linking, the entity class description in NER may describe several fine-grained entity classes, making our setup more challenging. \noindent \textbf{Mention Representation.} Upon span detection, we can first obtain the mention span representation of each span candidate $[i, j]$ by averaging the embeddings of the span tokens. However, entity class is usually a high level category including many entities. Thus, we need to add a linear transformation $\mathbf{w}_\mathrm{entity} \in \mathbb{R}^{h \times h}$ to project average span token embedding into the entity class space: \begin{align} \mathbf{e}_{i,j} = \mathbf{w}_\mathrm{entity} \cdot ( \frac{1}{j-i+1} \sum_{t=i}^j \mathbf{x}_t). \end{align} The description of an entity class $c$ is a sequence of tokens, denoted as $X^c=\{x^c_1, ..., x^c_K\}$ . In this paper, we feed entity class description into another pre-trained BERT~\citep{bert} to obtain its representations $\{\mathbf{x}^c_1, ..., \mathbf{x}^c_K\} \in \mathbb{R}^{h \times K}$ . Since there is limited data or even no data for training in the novel domain, we fixed the parameters of this BERT to expedite transferring by maintaining the embedding of entity class description from source and novel domains in the same space. \noindent \textbf{Entity Class Description Attention.} The entity class description may describe several fine-grained entity classes. To focus on the information in the description that corresponds to the extracted span, we propose to construct adaptive entity class representation. More specifically, we use multi-headed attention mechanism~\citep{Transformer}. Each single attention function can be described as mapping a query and a set of key-value pairs to an output. The query, key and value vector are denoted as $\mathbf{Q}$, $\mathbf{K}$ and $\mathbf{V}$ respectively. We use the aggregated mention vector $\mathbf{e}_{i,j} \in R^{ h \times 1}$ as query vector $\mathbf{Q}$ and use entity class description embedding $\mathbf{X}_c =[\mathbf{x}^c_{1},..., \mathbf{x}^c_{K}] \in \mathbb{R}^{ h \times K}$ as key vector $\mathbf{K}$ and value vector $\mathbf{V}$. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by the dot-product function of the query with the corresponding key. Then multiple parallel attention heads can stabilize the learning mechanism. We represent the procedure of obtaining adaptive entity class representation $\mathbf{x}^c(e_{i,j}) \in \mathbb{R}^{ h \times 1}$ as: \begin{align} \mathbf{x}^c(e_{i,j}) = \mathrm{MultiHead}(\mathbf{Q}, \mathbf{K}, \mathbf{V}). \end{align} The role of such a mechanism is empirically justified by the comparison between the proposed model and a reduced model (i.e., the proposed model without attention mechanism) in the experimental section. \noindent \textbf{Entity Class Inference.} The entity class inference is to infer the relationship between entity class and extracted span. We follow the zero-shot text classification~\citep{yin2019benchmarking} to cast this task into binary prediction: whether the extracted span belongs to given entity class or not. The probability of the extracted span being in a given entity class $c$ is based on a matching score between them: \begin{align} p (c | e_{i,j}) = \mathrm{sigmoid}( \mathbf{e}_{i j}^{\intercal} \mathbf{x}^c(e_{i,j})). \end{align} The loss for each extracted span $[i,j]$ is calculated as: \begin{align} \mathcal{L_\mathrm{entity}} ([i, j]) = \frac{1}{|\mathcal{C}|} \sum_{c \in \mathcal{C}} \mathrm{CE}\Big(p (c | e_{i,j}), y\Big), \end{align} where $\mathcal{C}$ is a set of entity classes of interest, and $y$ is binary label which equals to $1$ when extracted span belongs to entity class $c$ and $0$ otherwise. We use $\mathcal{L_\mathrm{entity}}$ to denote the entity class inference loss for all extracted spans. \noindent \textbf{Final Loss.} We jointly train span detection and entity class inference modules by optimizing the sum of their losses. \section{Experiments} \vspace{-0.05in} In this section, we empirically study and compare the proposed method with state-of-the-art methods in few-shot learning, domain transfer and zero-shot learning settings. \subsection{Experimental Setup} \noindent \textbf{Dataset}. We perform large-scale experiments with five different datasets\footnote{https://github.com/juand-r/entity-recognition-datasets} including Named Entity Recognition tasks and user utterances for task-oriented dialog systems as summarized in Table~\ref{tab:dataset}. (a) { CoNLL03}~\citep{Tjong2003Intro} is a collection of news wire articles from the Reuters Corpus with 4 entity classes. (b) { OntoNotes5}~\citep{weischedel2012ontonotes} is in general domain including 18 entity classes. (c) { WNUT} 2017 ~\citep{derczynski2017results} is collected from social media with 6 entity classes. (d) MIT {Movie and Restaurant} corpus~\citep{Liu2013AsgardAP} consist of user utterances for movie and restaurant domains with 12 and 8 classes. \begin{table}[htb!] \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{lcccc} \toprule { Dataset} & Domain & { \# Classes} & { \# Train} & { \# Test} \tabularnewline\midrule CoNLL03 & News & 4 & 14K & 3.6K \tabularnewline OntoNotes5 & General & 18 & 60K & 8.3K \tabularnewline WNUT & Social Media & 6 & 3.4K & 1.6K \tabularnewline Movie & Moive& 12 & 8.8K & 2.4K \tabularnewline Restaurant & Restaurant &8 & 6.9K & 1.5K \tabularnewline \bottomrule \end{tabular} \caption{Dataset summary.} \label{tab:dataset} \end{table} \noindent \textbf{Backbone} We use the the pre-trained BERT$_\mathrm{base}$ uncased model ($\sim$110M parameters) as the backbone network. The inputs during training and inference are lowercased to make them case-insensitive. The implementation details and hyper-parameter configurations are presented in Appendix. \subsection{Few-shot Learning} \textbf{Setting.} In this subsection, we study how the proposed method performs in a few-shot supervision setting, For 5-shot setting, we sample 5 sentences for each entity class from the training set and fine-tune models with sampled sentences. The experiment is repeated for 10 times to report the average F1 score. We also explore the role of distantly supervised learning in few-shot learning and the corresponding details are in Appendix. \noindent \textbf{Baselines} The first baseline we use is a fully supervised BERT model trained on all available training data {(3.4K-60K sentences)} which provides the ceiling performance for every task. Each of the other models are trained on $5$ training sentences per class. We compare our method with BERT (same backbone with ours) with {Beginning-Intermediate-Outside (BIO)} tagging mechanism as a comparison to evaluate the proposed model design besides the backbone choice. {LC} and {Prototype} are abbreviations for linear classifier and prototype-based methods from {a recent few-shot NER work}~\citep{huang2020few}. They use pre-trained model RoBERTa-base as their backbone model. MRC-NER~\citep{mrc} casts NER task into machine reading comprehension and achieves the state-of-the-art performance on several benchmark datasets. To study the role of attention mechanism proposed in subsection~\ref{sec:adaptive}, we propose a reduced model {SpanNER-NoAttn}, which uses average operation instead of attention to aggregate entity class description. \begin{table*}[htb] \centering \resizebox{0.9\linewidth}{!}{% \begin{tabular}{llllllll} \toprule \textbf{Method} & \textbf{CoNLL03} & \textbf{OntoNotes5} & \textbf{WNUT} & \textbf{Movie} & \textbf{Restaurant} & \textbf{Average}\\ \midrule \multicolumn{6}{l}{\textbf{Full-supervision}}\\ BERT & 91.1 & 87.8 & 47.1 & 87.9 & 79.0 & 78.6 \\ \midrule \multicolumn{6}{l}{\textbf{5-shot supervision}}\\ BERT & 61.6&60.1&21.2&61.9&48.6 & 50.7 \\ LC$^\dagger$ & 53.5 &57.7 &25.7&51.3&48.7 & 47.4 \\ Prototype$^\dagger$ &58.5&53.3&\textbf{29.5}&38.0&44.1 & 44.7 \\ MRC-NER & 28.5 & 49.8 &0.4&58.7 & 43.1&36.1\\ SpanNER-NoAttn (ours) & \underline{68.4} (0.5) &\underline{65.1} (0.3)&22.8 (0.4)& \underline{64.8} (0.3)& \underline{48.9} (0.2) & \underline{54.0}\\ SpanNER (ours) & \textbf{71.1} (0.4) & \textbf{67.3} (0.5) & \underline{25.8} (0.3)$^*$ & \textbf{65.4} (0.4) & \textbf{49.1} (0.2) & \textbf{55.7} [$\uparrow$9.9\%]\\ \bottomrule \end{tabular} } \caption{F1 score comparison of models on different datasets. All models (except LC and Prototype) use the same BERT backbone. $^\dagger$ indicates results from \citep{huang2020few}. The highest scores are \textbf{bolded}, while the second highest score is \underline{underlined}. F1 score of our model for each task is followed by standard deviation and percentage improvement [$\uparrow$] is over the best baseline. $^*$Roberta is pre-trained on reddit dataset which is similar to WNUT. We change backbone from BERT to Roberta (same with Prototype's) and F1 of SpanNER on WNUT is \textbf{31.5} (0.3).} \vspace{-0.1in} \label{tab:5_shot} \end{table*} \noindent \textbf{Performance} We report the results of 5-shot supervision and distantly supervising pre-training plus 5-shot supervision in Table~\ref{tab:5_shot}. In the 5-shot supervision setting, we can observe that our methods outperform baseline BERT consistently, which shows the advantage of the proposed model design {in addition to} the benefits from backbone. The baseline Prototype leverages given support examples to conduct NER task and achieves lower performance compared with LC with the same backbone according to average F1. The reason may lie in that the tokens belonging to the same entity class are not necessarily close to each other~\citep{huang2020few}. Prototype achieves better performance on WNUT compared to SpanNER since Prototype is based on Roberta which is pre-trained on social media dataset reddit. We change backbone of the proposed model SpanNER from BERT to Roberta-bas and observe that SpanNER achieves 31.5 in term of F1 score and outperforms Prototype. The MRC-NER framework is a reading comprehension framework whose success relies on training on large-scale data and thus cannot achieve satisfactory performance in a few-shot setting. Overall, we observe that our methods largely outperform all methods including the models with the same BERT encoder as ours across different datasets. The average performance improvement over the best baseline BERT is around 10\%. Moreover, the comparison between SpanNER and SpanNER-NoAttn demonstrates that the improvement brought by attention mechanism is around 3.1\%. {\noindent\textbf{Varying the number of shots.} Table \ref{fig:shot_number} shows the improvement in the performance of SpanNER and BERT when increasing the number of labels for each NER type in the CoNLL03 dataset. As we increase the amount of labeled training instances, SpanNER improves over BERT consistently.} \begin{figure}[htb!] \vspace{-0.1in} \centering \includegraphics[width=0.7\linewidth]{./figs/shot_number.png} \caption{Variation in model performance on varying shots on CoNLL03. ``Full'' indicates full supervision.} \label{fig:shot_number} \end{figure} \subsection{Domain Transfer} We evaluate the proposed model in another common scenario of adapting a NER model to a novel domain~\citep{yang2020simple}. In this setting, we have a fully supervised source domain and a target domain with few-shot supervision. Following \citep{yang2020simple}, we use general domain (OntoNotes5) as a source domain and evaluate models on News (CoNLL) and Social (WNUT) domains. \begin{table} [htb] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{l|lll} \toprule \textbf{Models} & \textbf{CoNLL03} & \textbf{WNUT} & \textbf{Average} \\ \midrule SimBERT $^\dagger$ & 28.6 & 7.7 & 18.2\\ Prototypical Network $^\dagger$ & 65.9 &19.8 & 42.9\\ PrototypicalNet+P\&D $^\dagger$ & 67.1 & 23.8 & 45.4 \\ NNShot $^\dagger$ & 74.3 & 23.9 & 49.1\\ StructShot $^\dagger$ & 75.2 & 27.2 & 51.2 \\ MRC-NER & 64.1 & 32.6 &48.3\\ \midrule SpanNER-NoAttn (ours)& 80.1 (0.4) &42.0 (0.7) & 61.1\\ SpanNER (ours) & \textbf{83.1} (0.5)&\textbf{43.1} (0.6) & \textbf{63.1} [$\uparrow$23.2\%]\\ \bottomrule \end{tabular} } \caption{F1 score comparison of models on CoNLL03 and WNUT datasets with 5-shot supervision for domain transfer. $^\dagger$ indicates results from~\citep{yang2020simple}. } \vspace{-0.1in} \label{tab:domain_transfer} \end{table} \noindent \textbf{Baselines.} We adopt six state-of-the-art methods in the domain transfer setting as baselines. SimBERT is based on a pre-trained BERT encoder and the predictions are conducted by a nearest neighbor classifier ~\citep{yang2020simple}. Prototypical Network~\citep{snell2017prototypical} is a state-of-the-art few-shot classification system and is adopted by~\citep{fritzler2019few} for few-shot NER task. Upon Prototypical Network, PrototypicalNet+P\&D~\citep{hou2020few} adds pairwise embedding and dependency mechanism to gain further improvements. StructShot and NNShot are proposed in \citep{yang2020simple}, which achieve state-of-the-art performance in this domain transfer setting. We include our reduced baseline SpanNER-NoAttn in this task as an ablation study and follow \citep{yang2020simple} to run our models five times and report average performance with standard deviation. \noindent \textbf{Performance} Table~\ref{tab:domain_transfer} shows the results of baselines and the proposed methods on CoNLL03 and WNUT datasets. The proposed models achieve F1 scores 83.1 and 43.1 on CoNLL03 and WNUT respectively, bringing improvements over the best baseline 10.5\% and 32.2\% correspondingly. The proposed model effectively transfers learned knowledge to novel domains by learning from natural language descriptions instead of simple one-hot representation of entity classes. \subsection{Zero-shot NER} \noindent \textbf{Setting} The zero-shot learning setting is motivated by the fact that new types of entities often emerge in some domains and sometimes the annotations in the target domain are not accessible. Following zero-shot text classification setting~\citep{yin2019benchmarking}, we evaluate the proposed model in a common setting: \emph{label-partially-unseen}. In label-partially-unseen setting, a part of labels are unseen, enabling us to check the performance on unseen labels as well as seen labels. \noindent \textbf{Baselines} Zero-shot NER task is rarely studied. The most state-of-the-art model for zero-shot NER is MRC-NER~\citep{mrc}, which conducts NER task by extracting answer spans given the questions of entity classes. Another baseline we use is the reduced model SpanNER-NoAttn. The comparison with this reduced model can demonstrate the role of entity class attention mechanism. \begin{table}[htb] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{lccccc} \toprule \textbf{Method} & \multicolumn{2}{c}{\textbf{CoNLL03}} & & \multicolumn{2}{c}{\textbf{WNUT}} \\ \cline{2-3}\cline{5-6} & Overall & Unseen & & Overall & Unseen \\ \midrule MRC-NER & 39.1 & 14.5 &&24.0 & 7.4\\ SpanNER-NoAttn & 39.0 &0.5&& 31.4 & 16.8 \\ SpanNER & \textbf{53.0} & \textbf{33.5} &&\textbf{35.4} & \textbf{18.8}\\ \bottomrule \end{tabular} } \caption{F1 score comparison of models on CoNLL03 and WNUT datasets. {\em Overall} and {\em Unseen} indicate F1 scores of all entity classes and never-seen entity classes, respectively. } \vspace{-0.1in} \label{tab:0_shot} \end{table} \noindent \textbf{Performance} Table \ref{tab:0_shot} shows the F1 scores of MRC-NER and the proposed methods. MRC-NER based on reading comprehension framework is capable of conducting NER task for never-seen classes. However, the span detection in MRC-NER is tightly coupled with {question} understanding, leading to more difficulty in handling unseen entity classes. In contrast, the proposed framework decomposes the NER task into span detection and entity class inference, avoiding the error propagation between two modules and thus delivering better performance. The comparison between SpanNER-NoAttn and SpanNER indicates the importance of attention mechanism in entity class description understanding, especially for never-seen entity classes. \noindent \textbf{Entity Class Inference} We conduct experiments that disentangle entity class inference module from SpanNER so that the capability of this module can be evaluated. The span detection module cannot be separately evaluated because the span annotations on both datasets are associated with pre-defined entity classes. To demonstrate the capability of entity class inference, we use gold spans to evaluate the performance of entity class inference. Table~\ref{tab:analysis} shows the performance of SpanNER-NoAttn and SpanNER. Comparing these two methods, we can observe that the attention mechanism helps improve the performance of the entity class inference. \begin{table}[htb] \centering \resizebox{0.9\columnwidth}{!}{ \begin{tabular}{lcccc} \toprule & \textbf{CoNLL03} & \textbf{WNUT} \\ \midrule \multicolumn{3}{l}{\textbf{Entity Class Inference}} & \\ SpanNER-NoAttn & 56.2 & 53.7\\ SpanNER & 60.2 & 57.0\\ \midrule \multicolumn{3}{l}{\textbf{Annotation guidelines}} & \\ SpanNER-NoAttn & 31.8 & 11.5 \\ SpanNER & 42.1 & 15.7 \\ \bottomrule \end{tabular} } \caption{Experiments that demonstrate the performance of the entity class inference module and adopt annotating guidelines as entity class descriptions on CoNLL03 and WNUT datasets.} \label{tab:analysis} \end{table} \noindent \textbf{Class Description Construction} We set up experiments to study how the entity class description affects the model performance. In this experiment, we replace Wikipedia description of entity classes by annotation guidelines from CoNLL03 and WNUT datasets in the testing stage. We can observe that the proposed models are still capable of identifying entities belonging to never-seen entity classes even though the descriptions in the testing stage are different from those in the training stage. The F1 scores drop compared to the scores when Wikipedia descriptions are used because training and test stages use different descriptions and the annotation guidelines do not include the semantic explanation of entity classes. \noindent \textbf{Performance per Entity Class} We show F1 score per entity class on CoNLL03 and WNUT datasets in Table~\ref{tab:distribution}. We can observe the various degrees of recognizing different entity classes. First, the person names are easily recognized across different domains. The performance of person entity class on WNUT is worse compared to that on CoNLL03, which may be due to the large domain shift in social media data. It is interesting to see that the performance of seen entity classes \texttt{LOC}, \texttt{location} and \texttt{product} is even worse than that of never-seen entity classes. To explain this interesting phenomenon, we provide a detailed analysis of error cases below. \begin{table}[htb] \centering \resizebox{0.9\columnwidth}{!}{ \begin{tabular}{lrllr} \toprule \multicolumn{2}{c}{\textbf{CoNLL03}} && \multicolumn{2}{c}{\textbf{WNUT}} \\ \cline{1-2} \cline{4-5} Entity Class& F1 && Entity Class& F1 \\ \midrule PER&77.4&& person & 59.1\\ ORG&58.5&& creative-work$^*$& 19.3\\ MISC$^*$&33.5&& corporation$^*$ & 19.1\\ LOC&5.9&& group$^*$& 18.3\\ -&-&& location&14.4\\ -&-&& product &11.0 \\ \bottomrule \end{tabular} } \caption{F1 score of SpanNER per entity class on CoNLL03 and WNUT datasets. $^*$ indicates unseen entity classes. } \vspace{-0.1in} \label{tab:distribution} \end{table} \noindent \textbf{Error Analysis} We manually examine the errors made by the proposed model on the CoNLL03 and WNUT test datasets and categorize these errors into 3 types. The error examples are presented in Appendix. (1) Different annotation guidelines on datasets. For instance, the description of \texttt{location} entity class in the source domain (OntoNotes5) is limited to mountain ranges and bodies of water, excluding countries, cities, states (these are included in the entity class \texttt{GPE}). Such a description is different from entity class \texttt{LOC} on CoNLL03 and \texttt{location} on WNUT. (2) Domain shift. The domain shift leads to the difficulty in recognizing the entities belonging to seen entity classes. (3) Description understanding. Description understanding is a crucial step for the success of zero-shot NER. For example, \texttt{MISC} on CoNLL03 is a collection of diverse fine-grained entity classes including events, nationalities, products and works of art. \section{Related Work} The most related topics are few-shot and zero-shot NER, which are discussed as follows. \noindent\textbf{Few-shot NER} aims to build a model that can recognize a new class with a small number of labeled examples quickly. Recent works~\citep{huang2020few, yang2020simple, hou2020few, Ziyadi2020ExampleBasedNE, wiseman2019label} exploit prototype-based methods to conduct NER tasks. Since tokens or entities belonging to the same entity class are not necessarily close to each other, prototype-based methods usually end up learning noisy prototypes and may not achieve satisfactory performance. To further improve few-shot performance, \citep{hofer2018few, huang2020few} explores different pre-training strategies for few-shot NER, and \citep{wang2020adaptive, huang2020few} propose to leverage self-training to take advantage of additional unlabelled in-domain data. Although aforementioned few-shot NER works show the potential of additional data in improving performance of few-shot NER, they still suffer from the limitations of prototype or one-hot representations of labels in transferring knowledge. Moreover, the aforementioned models cannot be applied in the zero-shot learning setting due to either reliance on labeled support set or the adoption of one-hot label representation. \noindent\textbf{Zero-shot NER} is to build a model that can recognize new classes without using corresponding labeled data. This setting is rarely studied in NER task. Zero-shot NER is important and practical in the real scenario since the annotations may not be accessible due to privacy and compliance restrictions for some sensitive user applications. \citep{rei2018zero} has worked on zero-shot sequence labeling task by using attention to infer binary token-level labels. However, their token level predictions are constrained to being binary and has to rely on sentence labels. These limitations prohibit the use of this method for NER task. MRC-NER~\citep{mrc} formulates NER task as a machine reading comprehension task and enables zero-shot NER. However, the inference of MRC-NER for the single sentence needs to be conducted multiple times to collect results corresponding to all the entity types of interest, incurring expensive inference cost. Moreover, the reading comprehension framework needs to be trained with large-scale dataset and is not effective in the few-shot setting. {\citep{logeswaran2019zero,wu2019scalable} propose to incorporate entity description for zero-shot entity-linking task. Nevertheless, they are different with ours in several aspects. First, the input to this work are sentences with pre-annotated entities while our task takes sentences as input and needs to conduct entity recognition and entity type inference jointly. Second, in the entity linking problem, the mentions in the sentences and Wikipedia descriptions refer to the same entities, while mentions in the sentences are only instances of entity classes in the NER task. Toward those challenges, SpanNER introduces how to capture class description which usually includes many fine-grained classes for a further improvement. } Other zero-shot problems studied in NLP involve text classification~\citep{yin2019benchmarking}, entity typing~\citep{zhou2018zero}, word sense disambiguation~\cite{kumar2019zero} and relation extraction~\citep{levy2017zero}. These problems have different settings and challenges compared to zero-shot NER. \section{Conclusions} \vspace{-0.05in} In this work, we study how to conduct NER in a low resource setting (when there are few or zero labeled data). To this end, we develop a novel NER framework SpanNER that decomposes NER task into span detection and entity class inference. This framework enables zero-shot NER and improves the performance of few-shot NER by capturing semantic meanings of entity classes. Extensive experiments on 5 benchmark datasets and various settings demonstrate the effectiveness of the proposed model, particularly in the low-resource settings. \vspace{-0.1in} \section*{Acknowledgment} \vspace{-0.05in} The authors would like to thank the anonymous referees for their valuable comments and helpful suggestions. This work is supported in part by the US National Science Foundation under grant NSF-IIS 1747614. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation. \vspace{-0.2in} \section{Implementation} \noindent \textbf{Training} We use AdamW~\cite{bert} as the optimizer. The learning rate is selected from $\{6e{-6}, 1e{-5}, 2e{-5}\}$ and batch size is selected from $\{8, 16\}$ according to validation set, coupled with a linear schedule with 1\% warmup. We clip gradients to max norm $1.0$. For all training data sizes, we set the training epoch as 50. The max sequence length for input is 128 and the max sequence length for label description is 32. The dimension $h$ is 768, which is the embedding dimension of BERT. The pre-trained language model for label description is a BERT$_\mathrm{base}$ uncased model. For multi-head attention mechanism, the multi-head number is $4$, the hidden dimension size is $300$ and the Dropout probability is $0.2$. The model is run on 4 NVIDIA Titan Xp GPU servers. \noindent \textbf{Inference} For few-shot NER, the inference of span detection is introduced in Subsection~\ref{sec:span_detection}. Since the entity class inference is binary prediction for each entity class, we use $0.5$ as decision boundary to determine whether the extract span belongs to given entity class or not. During the zero-shot NER, the mentions corresponding to never-seen classes may have lower detection scores compared to seen entity classes. Thus, we calculate the entity inference score using softmax over all the entity classes to get a ``relative'' score. Since many extracted spans may not be associated with the entity classes of interest, we follow ~\cite{li2020efficient} to use a hyper-parameter threshold $\gamma$ to select identified entities based on the joint score of span detection and entity class inference for span $[i, j]$. More specially, the joint score of span $[i ,j]$ can be calculated by $\log(p_\mathrm{match}([i,j])) +\log p (c | e_{i,j})$. The thresholds of zero-shot are selected as $-0.4$ and $-0.5$ for CoNLL03 and WNUT respectively according to validation set. We investigate the effect of $\gamma$ in the Figure~\ref{fig:threshold}. \begin{figure}[hbt!] \vspace{-0.1in} \subfloat[CoNLL03]{ \begin{minipage}{.49\linewidth} \includegraphics[height=1.22in]{./figs/conll03_threshold.eps} \label{subfig:conll03} \end{minipage}} \subfloat[WNUT]{ \begin{minipage}{.49\linewidth} \includegraphics[height=1.22in]{./figs/wnut_threshold.eps} \label{subfig:wnut17} \end{minipage}} \caption{F1 score changes of our model w.r.t. varying threshold $\gamma$ values.}\label{fig:threshold} \end{figure} \noindent \textbf{Threshold $\gamma$} We show the F1 score changes of the proposed method on test datasets of CoNLL03 and WNUT with respect to varying $\gamma$ values in Figure~\ref{fig:threshold}. Similar trends can be observed on both datasets. The F1 scores first increase as threshold $\gamma$ values increase and then reach the peak in the middle points. \section{Token Sampling} Token sampling is introduced into the proposed model to mitigate the imbalance class issue, which degrade the efficiency and effectiveness of training especially in the low-resource scenario. To explore the role of token sampling, we conduct ablation study by removing the token sampling. The proposed baseline is denoted as SpanNER-NoSampling. We show the results on CoNLL03 and OntoNoets5 with 5-shot supervision in Table.~\ref{tab:ablation_study}. Table.~\ref{tab:ablation_study} shows that the token sampling mechanism is effective and brings improvements around 4.7\% and 2.3\% on CoNLL03 and OntoNotes5 respectively. \begin{table}[htb] \centering \resizebox{\columnwidth}{!}{ \begin{tabular}{lll} \toprule & \textbf{CoNLL03} & \textbf{OntoNotes5} \\ \midrule SpanNER-NoSampling & 67.9 (0.2) & 65.8 (0.3)\\ SpanNER & \textbf{71.1} (0.4) & \textbf{67.3} (0.5)\\ \bottomrule \end{tabular} } \caption{F1 score comparison of models on CoNLL03 and OntoNotes5 with 5-shot supervision. Overall highest scores are \textbf{bolded}. F1 score of models is followed by standard deviation.} \vspace{-0.2in} \label{tab:ablation_study} \end{table} \section{Distant Supervision} \label{sec:distant_supervision} \begin{table*}[htb] \centering \label{tab:main_result} \resizebox{0.9\linewidth}{!}{% \begin{tabular}{llllllll} \toprule \textbf{Method} & \textbf{CoNLL03} & \textbf{OntoNotes5} & \textbf{WNUT} & \textbf{Movie} & \textbf{Restaurant} & \textbf{Average}\\ \midrule \multicolumn{6}{l}{\textbf{Full-supervision}}\\ BERT & 91.1 & 87.8 & 47.1 & 87.9 & 79.0 & 78.6 \\ \midrule \multicolumn{6}{l}{\textbf{Distantly Supervised Pretraining + 5-shot supervision}}\\ BERT & 65.9 &64.9 &36.2&64.1&50.7 & 56.4\\ LC$^\dagger$ & 61.4 &68.8& 34.2 & 53.1 & 49.1 & 53.3 \\ Prototype$^\dagger$ &60.9 & 57.0 & 35.9 & 43.8 & 48.4 & 49.2 \\ MRC-NER & 69.4 & 63.4 &36.3 & 64.6 & 48.7 & 56.5\\ SpanNER-NoAttn (ours) & 74.4 (0.3) & 66.5 (0.3) & 35.8 (0.6) & 65.2 (0.2) & 49.3 (0.2) &58.3 \\ SpanNER (ours) & {\textbf{75.6}} (0.4)& {\textbf{71.6}} (0.2) & {\textbf{38.5}} (0.4) & {\textbf{67.8}} (0.3) & {\textbf{51.2}} (0.1) & {\textbf{60.9}}[$\uparrow$7.8\%]\\ \bottomrule \end{tabular} } \caption{F1 score comparison of models on different datasets. All models (except LC and Prototype) use the same BERT backbone. $^\dagger$ indicates results from \citep{huang2020few}. The overall highest scores are \textbf{bolded}. F1 score of our model for each task is followed by standard deviation. Percentage improvement [$\uparrow$] is over the best baseline in the corresponding setting.} \vspace{-0.12in} \label{tab:5_shot} \end{table*} We are also interested in the role of distantly supervised pre-training in the few-shot NER task, which is studied in a recent work~\citep{huang2020few}. We construct a Wikipedia distantly supervised dataset which contains 20 entity classes and around 1 million sentences. In this setting, we first pre-train NER models with distantly supervised data and then fine-tune the pre-trained models with 5-shot supervision. To construct the training data, we use the May 2019 English Wikipedia dump and use the anchor text as the mention. We select 20 popular entity types from the fine-grained entity typing dataset Figer~\cite{ling2012fine} including Locations, Organization, Person, City, Artist, Country, Author, Actor, Company, Event, Government, Sports team, Athlete, Title, Cemetery, Musician, Province, Building, Language, Politician. We retrieved entities belonging to those entity types by querying from Wikidata using SPARQL. Then we use string matching to assign entity types to anchor text. We use a subset of the wikipedia data around 1M examples for training and 10K hold-out examples for validation. The distantly supervised pre-training generally improves the performance for all the methods, confirming its potential in the low-resource NER task. Our model achieves 60.9 in average F1 and its average performance is improved by around 9.3\% compared to that in the setting of 5-shot supervision. Overall, the proposed model achieves the best performance on all the datasets and the improvement of SpanNER over the best baseline is around 7.6\% in average terms of F1. \section{Error Cases} we show error examples made by our model in Table~\ref{tab:errors}. In the first example on CoNLL03, ``Japan'' is annotated as \texttt{LOC}. However, the entity class \texttt{location} on OntoNotes5 (source domain) does not include countries and thus SpanNER does not classify this span into \texttt{LOC}. We also observe some incorrect predictions made by our model look reasonable. For instance, ``Outagmie County Circuit Court'' is identified as an entity belonging to \texttt{ORG}. Moreover, we find that our model correctly identifies ``Luebke'' as a \texttt{PER} entity which is not annotated in the dataset. On WNUT dataset, we find that many entities are difficult to identify especially that its context is very different with that of our source domain (OntoNotes5). For instance, ``Watch What Else is Making News'' only includes limited context words ``Watch''. \begin{table*}[bt] \centering \resizebox{0.85\linewidth}{!}{% \begin{tabular}{lp{14cm}} \toprule \textbf{Dataset} & \textbf{Example Error} \\ \midrule CoNLL03 & \red{Japan} then laid siege to the \red{Syrian} penalty area for most of the game but rarely breached the \red{Syrian} defence. \\ &Gold: \red{Japan} $\to$ LOC \\ &Gold: \red{Syrian} $\to$ MISC\\ &Gold:\red{Syrian} $\to$ MISC \\ CoNLL03 & {Japan} then laid siege to the \blue{Syrian} penalty area for most of the game but rarely breached the \blue{Syrian} defence. \\ &Pred: \blue{Syrian} $\to$ MISC \\ &Pred:\blue{Syrian} $\to$ MISC \\ \midrule CoNLL03 & In sentencing \red{Darrel Voeks}, 38, to a 10-year prison term on Thursday, \red{Outagmie County} Circuit Court Judge \red{Dennis Luebke} said he was ``a thief by habit."\\ & Gold: \red{Darrel Voeks} $\to$ PER\\ & Gold:\red{Outagmie County} $\to$ LOC\\ & Gold: \red{Dennis Luebke} $\to$ PER \\ CoNLL03 & In sentencing \blue{Darrel Voeks}, \blue{38}, to a 10-year prison term on Thursday, \blue{Outagmie County Circuit Court} Judge \blue{Dennis Luebke} said he was ``a thief by habit."\\ & Pred: \blue{Darrel Voeks} $\to$ PER\\ & Pred:\blue{38} $\to$ MISC\\ & Pred: \blue{Outagmie County Circuit Court} $\to$ ORG \\ & Pred: \blue{Dennis Luebke} $\to$ PER \\ \midrule CoNLL03 & You are narcissitic, Luebke said at the sentencing, adding \red{Voeks} should pay restitution of more than \$100,000 to the farming family who had hired him. \\ & Gold: \red{Voeks} $\to$ PER\\ CoNLL03 & You are narcissitic, \blue{Luebke} said at the sentencing, adding \blue{Voeks} should pay restitution of more than \$100,000 to the farming family who had hired him. \\ & Pred: \blue{Luebke} $\to$ PER\\ & Pred: \blue{Voeks} $\to$ PER\\ \midrule CoNLL03 & This cannot endure, ``\red{Marlow} told \red{BBC} television's \red{Newsnight} programme on Thursday." \\ & Gold: \red{Marlow} $\to$ PER\\ & Gold: \red{BBC} $\to$ ORG\\ & Gold: \red{Newsnight} $\to$ MISC \\ CoNLL03 & This cannot endure, ``\blue{Marlow} told \blue{BBC television's} Newsnight programme on Thursday." \\ & Pred: \blue{Marlow} $\to$ PER\\ & Pred: \blue{BBC television's} $\to$ ORG\\ \midrule WNUT & Visuals of the avalanche site in \red{Gurez sector}.\\ &Gold: \red{Gurez sector} $\to$ location\\ WNUT & Visuals of the avalanche site in \blue{Gurez} sector.\\ & Pred: \blue{Gurez} $\to$ location \\ \midrule WNUT& Watch \red{What Else is Making News } \\ & Gold: \red{What Else is Making News } $\to$ creative-work \\ WNUT& Watch {What Else is Making News } \\ \midrule WNUT& [Rip \red{Chad}] (https://www.reddit.com/r/soccer/comments/5mi9bl/granada\_and\_ ...) \\ &Gold: \red{Chad} $\to$ person \\ WNUT& [\blue{Rip Chad}] (https://www.reddit.com/r/soccer/comments/5mi9bl/granada\_and\_ ...) \\ &Pred: \blue{Rip Chad} $\to$ person \\ \midrule WNUT&Step 2: [\red{Google}] (http://www.google.co.nz) \\ &Gold: \red{Google} $\to$ creative-work \\ WNUT&Step 2: [\blue{Google}] (http://www.google.co.nz) \\ &Gold: \blue{Google} $\to$ corporation \\ \bottomrule \end{tabular} } \caption{Error examples made by our model SpanNER in zero-shot NER setting. \red{} denotes gold spans and \blue{} denotes predicted spans.} \label{tab:errors} \end{table*}
{'timestamp': '2021-09-14T02:16:36', 'yymm': '2109', 'arxiv_id': '2109.05357', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05357'}
arxiv
\section{Introduction} In recent years, the amount of digital data created and stored by humanity is rapidly growing. Current data storage technologies are limited in their ability to support the growing demand, and thus the need for alternative storage media is rising. The durability and high information density of DNA make it an appealing medium for future data storage systems \cite{Church2012,Goldman2013}. A single gram of DNA can potentially store 100s of petabytes and expected to last and remain readable for centuries. In comparison, standard storage media such as optical discs, hard drives and magnetic tapes, only enable data lifetime of a few years with an information density which is lower by orders of magnitude \cite{chandak2020overcoming,char:19}. DNA based storage systems are comprised of three main components. First, the input information is encoded into a set of DNA sequences (\textit{i.e.} sequences over the four letter alphabet $\{A,C,G,T\}$). Next, the sequences are ``transmitted" over a DNA based channel including synthesis, storage, and sequencing. Finally, the sequencing output is reconstructed and decoded. Figure \ref{fig:dna_Storage_Pipeline} presents an overall view of DNA based storage. The encoding step involves adjustments to technological and biological constrains, such as adding error-correction codes to the sequences. Standard synthesis technologies generate thousands to millions of copies for every 100-200 base sequence \cite{char:19}. Moreover, all the synthesized DNA molecules are stored together in a single container as an unordered set. These properties, among others, impose different limitations on the encoding step including sequence length limitation, inedxing, controlled GC content, and run-length constrains. The output of the sequencing process is a set of noisy sequences, usually referred to as reads, representing the synthetic DNA molecules. Retrieving the information from this read set involves sequence reconstruction, ordering, and decoding. Despite the promising potential, many challenges prevent DNA based storage from becoming a viable solution, even for archival purposes. The synthesis and sequencing processes are costly and result in erroneous reads that include insertion, substitution and deletion errors \cite{char:19}. Furthermore, as the number of sequenced molecules is considerably lower than the number of available molecules, only a small sample is sequenced, thus some sequences are read multiple times while others might not be read at all. Some recent work on DNA based storage systems presented end-to-end solutions including molecular implementations \cite{Organick2018random,df:17,organick2020probing}. Others tackled certain components: error correction schemes \cite{nguyen2021capacity, lenz2020coding} or read clustering and sequence reconstruction algorithms \cite{ccc:19,Sabary:2020,chandak2019improved}. All the algorithms suggested for the reconstruction step, which is the task of predicting the original sequences from the noisy read set, use multiple copies for reconstruction. Obtaining enough sequences with sufficient read coverage requires excess reading which entails higher costs. For more information regarding DNA data storage, common challenges, and recent work, we refer the reader to \cite{Ceze2019}. During the past few years, Transformers \cite{vaswani2017attention} have become the most dominant architecture for many sequence-to-sequence tasks as it showed to be superior to methods that have been used before (mainly CNNs and RNNs). Although initially developed for language modelling tasks, Transformers are now widely used in other areas including audio processing \cite{dong2018speech} and image processing \cite{parmar2018image}. More recently Transformers also achieved significant impact on one of the cornerstones of computational biology, the problem of protein folding prediction \cite{jumper2021highly}. A Transformer is a neural network with permutation equivalence composed of attention mechanisms and residual blocks. In the Transformer’s architecture, position embeddings are generally added into the embedding layer with token embedding, since Transformers cannot distinguish the input’s position. In this work, we focus on reconstructing the original DNA sequences from only a single noisy read of each sequence. We address the problem as a sequence-to-sequence task and use an ensemble of three encoder-decoder Transformer models for the reconstruction. Our model relies solely on self-supervised learning using noise injection on reads from the decoded file that are presumed to be error free with high probability \cite{lewis2019bart}. We evaluate our method on files from three different data domains, to which we simulate reads with realistic error rates. With average error rate reductions of $63\%$ (edit error), and $97\%$ (hamming error) using only a single read, our model outperforms state-of-the-art algorithms using 2-3 copies. Furthermore, the advantage of our method becomes more significant when tested over files with higher noise levels. \textbf{Our contributions}: This work is the first to use a single-read for sequence reconstruction in DNA based storage. We demonstrate that our approach outperforms state-of-the-art algorithms that use two and three reads for reconstruction. Additionally, this work is the first attempt to incorporate deep learning models for sequence reconstruction in DNA based storage systems. Furthermore, our approach requires no training on external data, making it adjustable for the storage of different file types. Lastly, our approach represent a paradigm shift in sequence reconstruction as we focus on correcting the errors by learning the representation of the sequences rather than learning the error patterns. \section{Problem Definition} The DNA channel takes a binary input message $\mathbf{m}$ and encodes it into a sequence of DNA codewords which is broken into $n$ sub-sequences of length $l$ each, $\mathbf{x_1},\mathbf{x_2},...\mathbf{x_n}$ where $\mathbf{x_i}\in \Sigma^l$ and $\Sigma = \{A,C,G,T\}$. For each $l$-bases sequence $\mathbf{x}$, $t>0$ independent copies are transmitted through a Deletion-Insertion-Substitution (DIS) channel yielding $\mathbf{y_1},\mathbf{y_2},...\mathbf{y_t}$. These, in turn are being decoded back to receive the binary output message $\hat{\mathbf{m}}$. A general \emph{DNA reconstruction} algorithm is a mapping $R:\left (\Sigma^* \right)^t \rightarrow \Sigma^*$ which receives $\mathbf{y_1},\mathbf{y_2},...\mathbf{y_t}$ and produces $\hat{\mathbf{x}}$. The goal in a DNA reconstruction problem is to minimize either the edit distance or the Hamming distance between the original sequence $\mathbf{x}$ and the inferred sequence $\hat{\mathbf{x}}$, $d_e(\hat{\mathbf{x}},\mathbf{x})$ and $d_H(\hat{\mathbf{x}},\mathbf{x})$ respectively (See definitions below). In this work we tackle the case for which $t=1$. For that purpose we generalize the problem definition by taking into account the entire message transmitted through the DNA channel. Formally, a reconstruction algorithm will be a mapping $R:\left (\Sigma^* \right)^n \rightarrow \left (\Sigma^l \right)^n$. That is, given a single noisy copy $\mathbf{y}$ for every sequence $\mathbf{x}$ we infer $\hat\mathbf{x}$. Moreover, the algorithm is aware of the overall encoding process of $\mathbf{m}$ to $\left ( \mathbf{x} \right )^n$ and can also enforce constraints on this encoding. This is sometimes referred to as \emph{coded reconstruction}. The purpose remains to minimize either $d_e(\hat{\mathbf{x}},\mathbf{x})$ or $d_H(\hat{\mathbf{x}},\mathbf{x})$. \subsection{Performance Measures} The edit distance between two sequences $x,y \in \Sigma^n$, denoted $d_e(x,y)$, is the minimum number of insertions, deletions and substitutions required to transform x into y. The Hamming distance between $x$ and $y$, denoted $d_H(x,y)$ when $|x|=|y|$, is the number of substitutions required to transform $x$ into $y$. \section{Related Work} \subsection{DNA Based Storage Error Characterization} \citeauthor{heckel2019characterization} studied the errors in a DNA storage channel by analyzing experimental data. They characterized deletion, insertion and substitution rates and the conditional error probabilities. \citeauthor{organick2020probing} examined the limits of DNA dilution and extensive PCR amplification on the overall reliability of DNA based storage systems. They showed that this is affected not only by the quality of the DNA synthesis and sequencing process, but also by the overall size of the files being stored together. \citeauthor{sabary2021solqc} performed an extensive analysis of the error patterns using experimental data from various DNA synthesis and sequencing technologies. They analyzed the error rates, including base specific and position specific rates. They also published SOLQC, a tool designed for the analysis of the error patterns in synthetic DNA libraries. \subsection{Reconstruction Algorithms} \citeauthor{BMA:18} extended the Bitwise Majority Alignment reconstruction algorithm suggested by \citeauthor{batu2004reconstructing} to support the DIS channel of DNA based storage. They aligned all reads by considering a majority vote per symbol, and for any read that its current symbol did not match the majority voting, they examined the next two symbols to determine the error type. \citeauthor{Organick2018random} used this reconstruction algorithm for a large scale implementation of an end-to end DNA based storage system. \citeauthor{Sabary:2020} presented several reconstruction algorithms for DNA based storage channel, designed to minimize the edit distance between the original sequence and the estimated sequence. Their algorithms examine the entire read and use the shortest common super-sequence and the longest common sub-sequence of a given set of reads. The suggested algorithms achieved reduced edit-error rates compared to previously published algorithms while using less copies. However, their results are based on using 10 reads or more of each sequence, and in the case of a single read, the algorithm would simply return the read as is. \subsection{Sequence Reconstruction Using Deep Learning} \citeauthor{chandak2020overcoming} integrated classical error-correction algorithms and a recurrent neural network (RNN) to reduce error rates introduced in nanopore basecalling in DNA based storage. They significantly reduced error rates achieving a $3\times$lower reading costs than compared works. However, their approach is specific to nanopore sequencing as it operates directly on the raw signal of the sequencer rather than on the obtained reads. \citeauthor{Pan2021.02.22.432304} showed how data can be stored in DNA both in the strand and in its backbone structure, to create a rewriteable DNA storage system and used ML for correction of stored image files. In a work parallel to this work, \citeauthor{Barlev2021DL}. presented a scalable and robust end-to-end solution for DNA storage systems that is based on coding theory and DNN. To retrieve the erroneous data, their method exploits the error behavior of the DNA storage channel, instead of the inherent redundancy of the files. \section{DNA Encoder-Decoder Transformer} In this section we describe our model. Essentially, it is a sequence-to-sequence model that performs error correction by mapping a corrupted sequence to the original one. \subsection{Pre-Processing} \subsubsection{Overlapping k-mer Sequence Representation} Each input sequence $\mathbf{s} \in \Sigma^n$ is represented using an overlapping k-mer representation. The k-mer representation is generated using a k-mer transformation: $$K: \Sigma^n \to (\Sigma^k)^{n-k+1}$$ such that for a sequence $s=s_1s_2 \dots s_n \in \Sigma^n$, $$\mathbf{K(s)} = [s_1\dots s_k, s_2\dots s_{k+1}, \dots s_{n-k+1}\dots s_{n}]$$The result is a vector of $n-k+1$ overlapping fixed length k-mers by a sliding window of stride one across the sequence. Overlapping k-mer sequence representation is widely used in computational biology for various sequence related tasks including classical sequence alignment algorithms and modern machine learning tasks \cite{ng2017dna2vec,Yanrong2021dnabert,ng2017dna2vec,orenstein2016kmers}. \subsubsection{Tokenization} The k-mer representation vector undergoes tokenization before it is fed to the encoder-decoder model. Tokenization is done using a word-piece tokenizer \cite{wu2016google} with vocabulary size of 261 tokens representing all 256 codewords in addition to the 5 special tokens: padding token, unused token, end-of-sentence token, classifier token, and a masking token. Note that while the tokenization deployment is done by word-piece tokenizer, the actual tokenization scheme represents a byte-level encoding, since every token represents a byte, much like \cite{xue2021byt5}. \subsection{Architecture} Figure \ref{fig:encoder} depicts the encoder-decoder Transformer composed of two paired BERT models \cite{devlin2018bert} used in this work. As suggested by \cite{rothe2020leveraging}, two main variations are made for the second BERT model, making it a decoder. First, in order to comply with auto-regressive generation, BERT’s bi-directional self-attention layers are changed to uni-directional self-attention layers. Second, since the decoder has to be conditioned on the contextualized encoded sequence, randomly cross-attention layers are added between the self-attention layer and the two feed-forward layers in each block. Apart from the aforementioned alterations, both models have the same configuration as the DNABERT 4-mer model from \citeauthor{Yanrong2021dnabert} with 12 layers, vocabulary size of 261, a hidden size of 768, filter size of 3072, and 12 attention heads. The weights are not shared between models, and are all randomly initialized. Note that this separation is necessary since the input for our model is a k-mer representation of the sequence, yet the output is the original sequence. At every training stage, for a sequence of length $n$, the model is fed with it’s k-mer vector of size $n-k+1$. The model outputs a prediction sequence of constant size $l$, which is the length of the originally encoded sequence. During training, we use a cross-entropy loss between the decoder's output and the original input. \begin{figure}[h] \centering \includegraphics[scale = 0.4]{Figure_2.png} \caption{\textbf{Transformer Encoder-Decoder Architecture.}} \label{fig:encoder} \end{figure} \begin{figure*}[h] \centering \includegraphics[scale = 0.55]{Figure_3.png} \caption{\textbf{Our proposed Single-Read Reconstruction Algorithm (SRR).} \textbf{Stage 1} includes byte-level encoding, DNA based storage and retrieval. \textbf{Stage 2} includes a rule based extraction of Correct Length Good Codewords ($CLGC$) reads as soft labeled data, synthetic noise injection producing $\widetilde{LL},\widetilde{SL},\widetilde{CLBC}$ that are used as training samples for training three reconstruction models. \textbf{Stage 3} includes reconstruction of the Long, Short and Erroneous reads ($LL$, $SL$, and $CLBC$ respectively) using constrained beam search predictions of the trained models. Finally, the original binary file is decoded.} \label{fig:overall_Method} \end{figure*} \section{Single-Read Reconstruction Using Transformers} In this section we describe the end-to-end pipeline of our proposed Single-Read Reconstruction (SRR) scheme. The input to the pipeline is a given data file which undergoes encoding to DNA. After retrieval of the erroneous data sequences, we inject synthetic noise to a subset of ``quality" sequences, thus creating a training dataset for self-supervised learning which is tailor-made for the file. We use 3 trained models to predict and reconstruct the original data file. As presented in Figure \ref{fig:overall_Method}, our process is described in 3 main stages: \textbf{Stage 1:} Encoding to DNA and retrieval of noisy reads. \textbf{Stage 2:} Self-supervised training by synthetic noise injection. \textbf{Stage 3:} Data reconstruction using model prediction. \subsection{Stage 1 - Encoding and Retrieval} A given data file $m$ is encoded to DNA by mapping every 8-bits to a codeword of 4 DNA bases: $$E:\{0,1\}^8 \rightarrow \{A,C,G,T\}^4$$ yielding a set of 256 codewords. Namely, the encoding of the data file $m$ is given as: $$\hat{E}(m) = \{E(m_1m_2\dots m_8),E(m_9m_{10}\dots m_{16}),\dots\}$$This byte-level encoding fits commonly used data representations (bmp, UTF-8, etc.) and guarantees that the codewords also serve as semantic building blocks and thus hold meaningful information. This encoding provides us with a meaningful and expressive vocabulary on one hand (compared to a naive 2 bits per base encoding with only 4 codewords), but robust and generic that relies only on the byte-level encoding scheme, and is therefore compatible for various domains and file types. The complete DNA encoded data file is split to DNA sequences of a fixed length $l$. Together with the data, we store the set of codewords used by the encoder $E$ to encode the stored file. Note that the overhead for storing this set of valid codewords is limited by the number of available codewords $r\leq256$, which is negligible in large files. The set of DNA sequences are then synthesized and stored. We retrieve noisy sequences with deletion, insertion and substitution errors. \subsection{Stage 2 - Self-Supervised Learning} \subsubsection{Noise Injection} We divide the retrieved noisy reads into 3 sets: short sequences with length $<l$ ($SL$), long sequences with length $>l$ ($LL$) and sequences of a correct length $l$ ($CL$). Certainly, reads in $SL$ and $LL$ are the result of at least one deletion/insertion event, and possibly other errors as well. The $CL$ set is divided again into 2 subsets: sequences in which all codewords are valid ($CLGC$), meaning they contain only codewords that were used to encode the data file, and sequences containing invalid codewords ($CLBC$). Note that since we stored each data file together with the set of codewords used to encode it, we are able to distinguish the $CLGC$ from the $CLBC$ sets. Reads in $CLBC$ include some errors (most likely substitutions). The reads in $CLGC$ are treated as a set of sample sequences assumed to be correct and used to generate a training set for a self-supervised learning model. $t$ noisy copies of each sequence in the $CLGC$ set are produced with errors introduced with a random DIS channel. We again divide the noisy copies to 4 subsets: $\widetilde{SL}$, $\widetilde{LL}$, $\widetilde{CLBC}$, and $\widetilde{CLGC}$. We discard the $\widetilde{CLGC}$ set as it probably contains very few erroneous reads. \subsubsection{Self-Supervised Training} The generated $\widetilde{SL}$, $\widetilde{LL}$, and $\widetilde{CLBC}$ sets are then pre-processed and used to train three different encoder-decoder models: Model$_{SL}$, Model$_{LL}$, and Model$_{CLBC}$ respectively, with the original $CLGC$ sequences as soft labels. The three models all share the same architecture described in the previous section. The term soft labels is due to the fact that the reads in $CLGC$ are not necessarily error-free. Intuitively, each of the three models is used to correct the error type most likely to occur in the corresponding training data. \subsection{Stage 3 - Prediction and Reconstruction} \subsubsection{Model Prediction} Each of the 3 trained models, Model$_{SL}$, Model$_{LL}$, and Model$_{CLBC}$, is used to predict the corresponding sequence sets: $SL$, $LL$, and $CLBC$ respectively. Reads in $CLGC$ are assumed correct and are therefore predicted using the identity mapping. \subsubsection{Constrained Beam Search} Standard encoder-decoder models usually use beam search to improve model prediction quality. In a beam search strategy, every stage of the prediction saves the best $B$ (which is the beam size) candidates. We leverage the information regarding the expected output that is known from the encoding scheme to impose constraints to the basic beam search strategy. First, only output sequences of the correct length $l$ containing only valid codewords are allowed. In addition, out of the $B$ predicted output sequences, we select the one with the minimal edit distance to the erroneous input sequence. \begin{table*}[h] \begin{tabular}{ll|lll|lll|lll} & & \multicolumn{3}{c|}{Darwin text} & \multicolumn{3}{c|}{Apollo code-script} & \multicolumn{3}{c}{Torres image} \\ & Algorithm & S & E & H & S & E & H & S & E & H \\ \hline \multirow{2}{*}{Single copy} & Natural error & $73.2\%$ & $0.34\%$ & $7.39\%$ & $72.6\%$ & $0.34\%$ & $7.60\%$ & $72.7\% $ & $0.34\%$ & $6.80\%$ \\ & SRR (\textit{Ours}) & $92.5\%$ & $0.10\%$ & $0.15\%$ & $91.9\%$ & $0.11\%$ & $0.13\%$ & $88.1\%$ & $0.18\%$ & $0.23\%$ \\ \hline \multirow{2}{*}{2 copies} & HRA & $85.7\%$ & $0.23\%$ & $0.64\%$ & $85.2\%$ & $0.25\%$ & $0.69\%$ & $87.9\%$ & $0.23\%$ & $0.71\%$ \\ & DBMA & $84.6\%$ & $0.29\%$ & $0.83\%$ & $83.2\%$ & $0.32\%$ & $0.89\%$ & $87.4\%$ & $0.29\%$ & $0.72\%$ \\ \hline \multirow{2}{*}{3 copies} & HRA & $96.3\%$ & $0.07\%$ & $0.33\%$ & $96.3\%$ & $0.06\%$ & $0.29\%$ & $97.0\%$ & $0.05\%$ & $0.22\%$ \\ & DBMA & $95.9\%$ & $0.09\%$ & $0.28\%$ & $95.8\%$ & $0.09\%$ & $0.27\%$ & $95.9\%$ & $0.09\%$ & $0.30\%$ \end{tabular} \caption{\textbf{Overall comparison of reconstruction algorithms on the three data files.} Success Rate (S), Mean Edit Error Rate (E), and Mean Hamming Error Rate (H) of the three reconstruction algorithms - our Single-Read Reconstruction Algorithm (SRR), Hybrid Reconstruction Algorithm (HRA) from \cite{Sabary:2020} and the Divider Bitwises Majority Alignment Algorithm (DBMA) which is an adjustment of the algorithm from \cite{BMA:18} done by \citeauthor{Sabary:2020}. SRR is tested on a single read while results of the other two algorithms are shown for 1,2, and 3 reads. For HRA and DBMA, Using a single read is equivalent to the natural error rate.} \label{table:OverallPerformanceComparison} \end{table*} \section{Experimental Results} To evaluate the performance of our reconstruction method, we performed three experiments with different types of data files. The first is a 948KB text file consisting of Darwin's ``On the Origin of Species" book \cite{darwin1909origin}. The second is a 3076KB text file containing the original code-script of the Apollo 11\footnote{Downloaded from https://github.com/chrislgarry/Apollo-11 on September 1, 2021}. This serves as a more complex case as the semantic structure of a code-script file is harder to identify than that of a text file from the English language. The third data file is a 4688KB color $1600\times1000$ image file of ``Torres del paine"\footnote{Image downloaded from https://www.travelandleisure.com on September 1, 2021}. The text and code-script files are UTF-8 encoded, and the image is encoded in the standard 8-bit color map bmp encoding. Namely, each pixel is represented by 3-bytes, one byte per color channel. We read the image file in $5\times5$ pixel squares. In all experiments, we assigned a codeword of 4 DNA bases to every byte of information, and encoded the data to DNA sequences of length $l=100$, each consisting of 25 encoded bytes. The encoding resulted in 38,183, 125,977, 192,000 DNA sequences representing the Darwin, Apollo, and Torres files respectively. We simulated 1,2, and 3 noisy reads for each sequence using a simulator from \cite{dnasimulatorgadi} that introduces deletion, insertion and substitution errors according to the DIS channel. We reconstructed the original sequence from a single noisy read using our Single-Read Reconstruction Algorithm (SRR) and compared the result to the reconstruction results of running the Hybrid Reconstruction Algorithm (HRA) from \citeauthor{Sabary:2020} and their variation of the Divider Bitwise ajority Alignment Algorithm (DBMA) by \citeauthor{BMA:18} using one, two, and three reads. The implementations of HRA and DBMA are taken from \cite{dnasimulatorgadi,Sabary:2020}. Since both HRA and DBMA failed to run on the complete data files, the comparison is presented on a sample of 5,000 sequences from each file. For all algorithms, we evaluated success rates, edit error rates, Hamming error rates, and edit error distributions. For the noise injection step of the SRR algorithm we used error schemes representing standard DNA based storage conditions. Details of the experimental setting are available in the Technical Appendix. \subsection{Overall Performance Comparisons} To test the overall performance of the three algorithms we used the DNA channel simulator with an error scheme of synthesis by TWIST Bioscience and sequencing using Illumina MiSeq, representing standard conditions in DNA based storage studies \cite{organick2020probing,chandak2019improved,srinivasavaradhan2021trellis,anavy2019composite}. Table \ref{table:OverallPerformanceComparison} details the success rates, edit error rates and Hamming error rates for the three data files. Mean error rates are reported. For a detailed report including standard deviation, refer to the Technical Appendix. Evidently, our algorithm outperforms both HRA and DBMA using one and two reads in all three measures across the different data files. We reduced the mean natural edit error rates from $0.34\%$ to $0.1\%,0.11\%,0.18\%$ and successfully reconstructed $92.5\%,91.94\%,88.1\%$ of the sequences in the Darwin, Apollo, and Torres files respectively. The mean hamming error rates were reduced by $97\%$ from $7.26\%$ to $0.17\%$ on average on all files. We also achieve better results on the Hamming error rate compared to DBMA using three reads on all three files and on two out of the three files compared to HRA. Figure \ref{fig:Cumm_Edit_Error} depicts the cumulative distribution of the edit errors of SRR, HRA using two reads and DBMA using two reads. Clearly SRR shows lower error rates. Moreover, while SRR saturates on reconstruction of 100\% of the sequences with up to seven edit errors, HRA and DBMA contain a long tail of a small number of sequences with up to 32 and 28 edit errors respectively. (See inset). This implies that when combined with error correction (EC) codes in an end-to-end DNA based data storage, SRR will require adding less redundancy in the EC scheme. \begin{figure}[t] \centering \includegraphics[scale = 0.5]{Figure_4.png} \caption{\textbf{Cumulative edit error histogram.} Edit errors frequencies tested in the Darwin text file using one and two reads. Presented as a cumulative histogram, the X-axis presents the number of edit errors while the Y-axis depicts the fraction of sequences with up to the number of edit error. The inset shows the distribution for the higher error values.} \label{fig:Cumm_Edit_Error} \end{figure} \subsection{Performance Comparison in High-Noise Regimes} To assess the performance of our algorithm on data containing higher error rates we used the encoded Darwin text file and simulated input data with error rates that are $0.9-4$ times higher than the standard error rate in the previous experiment. Figure \ref{fig:Noise_Analysis} shows the mean edit error of SRR and HRA using two and three reads as a function of the added noise factor. The error rates are normalized by the natural error rate. While both HRA-2 and HRA-3 performance deteriorate as the noise level increases, SRR manages to reduce the natural error rate by a relatively constant fraction of about 65\%. To illustrate the effect of different reconstruction performance on data with different noise levels, we performed a similar experiment on the Torres del paine image file. The results of this experiment are visualized in Figure \ref{fig:Images}. This visualization clearly demonstrates the quality of the SRR algorithm. Even with a noise level four times higher than the standard error levels, the reconstruction using a single read is very successful while HRA with three reads suffer from high error rates. \begin{figure}[t] \centering \includegraphics[scale = 0.5]{Figure_5.png} \caption{\textbf{The effect of increased noise levels.} Normalized mean edit error of HRA using two and three reads and of SRR as a function of the added noise factor.} \label{fig:Noise_Analysis} \end{figure} \begin{figure*}[h] \centering \includegraphics[scale = 0.4]{Figure_6.png} \caption{\textbf{The effect of increased noise levels.} Image reconstruction results of HRA using three reads and of SRR as a function of the added noise factor. Image downloaded from https://www.travelandleisure.com on September 1, 2021} \label{fig:Images} \end{figure*} \section{Discussion} In this paper, we proposed a novel approach for utilizing deep learning Transformers to perform single-read reconstruction for DNA based storage. We modeled the error correction process as a sequence-to-sequence task and designed an encoder-decoder model to correct deletion, insertion, and substitution errors. Our approach is based on self-supervised training using only the decoded file with injected noise to produce training samples. We demonstrated our approach by encoding three file types and performing single-read reconstruction on simulated noisy data with different noise levels. Our single-read reconstruction algorithm achieves better performance than the current state-of-the-art reconstruction algorithms operating on two reads and in some measures also three reads. This is the first example of single-read reconstruction for DNA based storage. Traditional algorithms treat the reconstruction problem of each sequence independently and are thus limited when operating on single-read sequences. Our approach is the first, to our knowledge, to offer a reconstruction algorithm that is both \emph{holistic} (\textit{i.e.} reconstructs all sequences simultaneously) and \emph{context-aware}. Our suggested approach is thus able to successfully reconstruct single-read sequences. The common approach for using machine learning models for sequence reconstruction relies heavily on the availability of high-quality labeled data. This is used to try and learn the error pattern to allow the prediction of the original sequences. Dataset generation of synthetic DNA libraries requires extensive investments and labor and thus these datasets are scarce. Moreover, DNA synthesis and sequencing technologies, as well as the subsequent molecular biology procedures, produce diverse error patterns that are affected from various exogenous factors making the learning task implausible. On the contrary, our model relies solely on self-supervised learning using noise injection on samples that are presumed to be error free. Our model does not require any external samples for training, making it applicable for use on diverse data files. While we use a certain error distribution for noise injection, it does not need to represent the same error distribution as the decoded data file. This is demonstrated in the noise level experiment where our model outperformed the two and three reads reconstruction algorithms on data with noise levels much higher than those used for noise injection. We are able to achieve these results because our reconstruction model does not learn the error pattern in the data but rather it learns the \emph{underlying structure of the data file} in hand. Learning the underlying structure of the decoded file requires the identification of error-free reads that are assumed to be a representing sample of the original file. We use our knowledge of the error model (\textit{i.e.} errors are the result of some DIS channel) and a limited amount of redundant information added to the file in the encoding step (\textit{i.e.} the set of valid codewords in the file and the designed length $l$) to generate a set of reads that are error-free with high probability. The possibility of obtaining a high quality set of probably-correct reads that adequately represent the input file is affected by three factors: file size, noise level, and the number of valid codewords in the file. Larger files allow for a larger and more diverse training set which is crucial for model training. Alternatively, high noise levels and larger sets of valid codewords result in a limited training set. An extreme case of the latter is demonstrated in the image encoding experiment as the set of valid codewords contains all 256 options. This makes the distinction between correct and erroneous reads impossible and results in lower success rate and higher error rates compared to the text file experiments. Exploring ways to improve the construction of this read set is a major focus for future studies. While most DNA based storage systems aim for an average read coverage of 10 reads or more, some sequences will inevitably be represented by only a single read. Salvaging those poorly represented sequences to extract more information will allow for the reduction of the overall coverage required for a successful decoding and the use of error correction schemes with less redundancy. Moreover, single-read reconstruction can be combined with standard multi-read reconstruction algorithms. For instance, after reconstructing each read using a single-read reconstruction model, reads can be clustered and used to reconstruct the sequence with higher confidence. In the past decade, the use of deep learning (DL) models has revolutionized many fields, including Computer Vision, Natural Language Processing, Cyber security, and others. Often, the introduction of DL models required rethinking central dogmas and traditional methodologies. DNA data storage is a fast growing field which gained a lot of attention in the past few years. However, despite its promise, the field seems to be limited in scale. This work represents a first step towards the incorporation of DL models in the DNA encoding-decoding pipelines. Similar to other domains, this may require a paradigm shift in the field. Replacing the traditional reconstruction algorithms and error correction schemes, that are focused on understanding the error patterns on the single sequence level, by a holistic, context-aware approach that tries to reconstruct the entire data file by modeling its underlying structure is a step in that direction.
{'timestamp': '2021-10-12T02:20:03', 'yymm': '2109', 'arxiv_id': '2109.05478', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05478'}
arxiv
\section{Conclusions} \label{sec:conclusions} We presented distributed-memory, GPU-accelerated, algorithms and implementations for two key operations on $\mathcal{H}^2${} matrices. The first is the matrix-vector (and multi-vector) multiplication and the second is the algebraic matrix re-compression to reduce the memory footprint consistent with a desired accuracy. The algorithms are supported by distributed data structures for representing, accessing, and operating on hierarchical matrices with nested bases, and the inter-process MPI communication is optimized to hide much of the data transfer cost with local compute phases of the algorithms. Both algorithms exhibit $O(N)$ behavior and near-ideal weak-scalability for a large number of GPUs; high performance on individual GPUs is achieved through the use of batched dense linear algebra kernels. The algorithms are incorporated in the open source library H2Opus and have interfaces to the PETSc library. The performance and usefulness of the library is demonstrated through the solution of a variable diffusivity integral fractional diffusion problem in 2D. Algorithmic and implementation scalability are demonstrated on grids of size up to $4096\times 4096$ on 64 GPUs, using the facilities of the PETSc library for the Krylov solver and the construction of an algebraic multigrid preconditioner. Future work is planned on three fronts. The first is the development of distributed-memory multi-GPU versions of additional $\mathcal{H}^2${} matrix algorithms, including their construction from randomized sampling. This will open the door for matrix-matrix multiplication and inversion via Newton-Schulz iterations. The second is the development of interfaces to BEM++ \cite{smigag15} and related high-productivity software libraries for integral equations that handle discretization tasks. H2Opus can provide highly effective core solvers for such libraries and will allow their use for large scale problems. The last front entails portability, and we plan to extend the H2Opus library to run on AMD GPUs. \section{Algebraic Matrix Compression} \label{sec:compression} $\mathcal{H}^2${} algebraic matrix compression is an operation that takes as input an $\mathcal{H}^2${} matrix and produces another $\mathcal{H}^2${} matrix of lower rank that approximates the input to a desired target accuracy. Compression is akin to the truncation operation that is commonly used to approximate dense matrices or dense matrix blocks by low rank approximations. Recompression is a core operation when working with $\mathcal{H}^2${} matrices. In particular, it is common in the discretization of integral equations to generate an initial $\mathcal{H}^2${} matrix from a kernel and an admissibility condition by approximating the kernel with Chebyshev polynomials for well separated clusters. The ranks produced by this approximation are not optimal however, resulting in increased storage and increased arithmetic costs for operations such as the matrix-vector multiplication. A recompression step, purely algebraic, is then performed to generate an optimal basis in which the ranks are as small as possible. Another context where recompression is essential arises when adding matrices, performing low rank updates, or implementing BLAS3-like operations. When matrix blocks get added there is an increase in the apparent rank of the resulting blocks. The matrix would then need to be recompressed in order to maintain the linear asymptotic rate for storage and operations. The key task of recompression is to generate a new nested compressed basis in which the matrix blocks are expressed. This may be done by a pair of downsweep and upsweep operations that we describe next. \subsection{Downsweep for Generating a New Basis} Consider how a new basis for a block row $A_i^q$ at the finest level $q$ would be generated. $A$ here denotes only the low rank portions of the hierarchical matrix, since the dense blocks are not compressed. $A_i^q$ consists of $b$ low rank blocks expressed at level $q$ as $U_i^q S_{ij}^qV_{j}^{q T}$ with $j=j_1 \cdots j_b$, and additional pieces representing the restriction of blocks from coarser levels to their ``i'' rows. \begin{equation} A_i^q = U_i^q \begin{bmatrix} \substack{\text{subblocks from} \\ \text{coarser levels}} \quad S_{ij_1}^q V_{j_1}^{q T} \cdots S_{ij_b}^q V_{j_b}^{q T} \end{bmatrix} = U_i^q B_i^{qT} \end{equation} A new more efficient basis can be generated by computing the SVD of $U_i^q B_i^{qT}$, and using the left singular vectors as the new basis. This would however require an expensive SVD of the $O(N)$-sized $B_i^q$. In order to avoid it, we first compute the QR decomposition of $B_i^q$ and then perform the SVD on the small $R$ factor. \begin{equation} A_i^q = U_i^q {B_i^q}^T = U_i^q (Q_i^q R_i^q)^T = \underbrace{U_i^q {R_i^q}^T}_{\text{new basis}} {Q_i^q}^T = \overline{U}^q_i {Q_i^q}^T \end{equation} The new basis for level $q$, $\overline{U}^q_i$ is effectively a reweighing of the columns of the previous basis $U_i^q$. The task of computing $R_i^q$ of the QR decomposition of $B_i^q$ can be done efficiently by exploiting the nestedness of the bases. Let us assume that the QR decomposition of $B_{i^+}^{q-1}$, the parent block $i^+$ at level $q-1$, is available as $Q_{i^+}^{q-1} R_{i^+}^{q-1}$. Then, \begin{equation} \begin{split} A_i^q &= \begin{bmatrix} \substack{\text{$i$-portion of} \\ U_{i^+}^{q-1} {B_{i^+}^{q-1}}^T} \quad U_i^q S_{ij_1}^q V_{j_1}^{q T} \cdots U_i^q S_{ij_b}^q V_{j_b}^{q T} \end{bmatrix} \\ & = U_i^q \begin{bmatrix} E_i^q (Q_{i^+}^{q-1} R_{i^+}^{q-1})^T \quad S_{ij_1}^q V_{j_1}^{q T} \cdots S_{ij_b}^q V_{j_b}^{q T} \end{bmatrix} = U_i^q B_i^{qT} \end{split} \end{equation} with $B_i^q$ conveniently expressible as: \begin{equation} \label{eq:Btq} B_i^q = \begin{bmatrix} Q_{i^+}^{q-1} \; R_{i^+}^{q-1} E_i^{q T} \\ V_{j_1}^l S_{ij_1}^{q T} \\ \vdots \\ V_{j_b}^q S_{ij_b}^{q T} \end{bmatrix} = \textbf{diag}(Q_{i^+}^{q-1}, V_{j_1}^q, \cdots, V_{j_b}^q) \begin{bmatrix} R_{i^+}^{q-1} E_i^{qT} \\ S_{ij_1}^{q T} \\ \vdots \\ S_{ij_b}^{q T} \end{bmatrix}. \end{equation} Assuming the $V^q$ bases are orthogonal, the block diagonal matrix in Eq.~\ref{eq:Btq} is orthogonal and the QR of $B_i^q$ simply reduces to the QR of the small stack at the end of Eq.~\ref{eq:Btq} which involves only $b+1$ blocks, each being a small $k \times k$ coupling/transfer matrix. Since this QR uses the $R^{q-1}$ matrix from level $q-1$, the overall computation starts from the root and goes down the tree computing all the $R^l_i$ matrices for all levels in a downsweep traversal. As with previous operations, all blocks at a given level can be processed in parallel, and importantly for the distributed setting, all the processes owning the subtrees below the C-level can proceed independently. Therefore, the computational pattern is identical to the distributed downsweep of the matrix-vector multiplication. Above the C-level, a single GPU is responsible for processing the top levels of the basis tree. The leaves of the top subtree, which hold the $R^l$ factors at level $l$, are then scattered to all GPUs and seed the roots of the individual subtrees, which continue the downseep independently all the way to the leaf level of the basis. The computational work at every level being, for every block row, a QR decomposition of the small stack at the end of Eq.~\ref{eq:Btq}. Batched QR operations \cite{boukaram18} are used within every GPU to achieve high performance. \subsection{Upsweep for Truncating the New Basis} Once the new reweighed basis is generated for all levels, it can then be truncated to the desired accuracy to generate the optimal basis $U^{\prime q}_i$. The coupling blocks are then compressed by projecting them on the new truncated basis. The truncation operation has to preserve the nestedness property. This can be accomplished by starting the truncation at the leaf level and sweeping up the basis tree. Given the reweighed basis $\overline{U}$ ($\overline{U}_t$ at the leaves and $\overline{E}_t$ at nodes in the tree), we seek a basis $U'$ ($U'_t$ at leaves and $E'_t$ at nodes in the tree) that spans the same subspace as $U$ to the desired accuracy. At the leaf level, this may be done through an SVD of the explicitly available basis \[ \overline{U}_t = U \Sigma V^T \approx U'_t T_t \] $U'_t$ is a subset of columns of the left singular vectors $U$. $T_t$ is a transformation matrix (which may be computed as $U'^T_t \overline{U}_t$) used to compute the new transfer matrix from a node to its parent as described next. For non-leaves, the truncated basis is expressed in terms of new compressed transfer operators: \[ \overline{U}^{l-1}_t = \begin{bmatrix} \overline{U}^l_{t_1} & \\ & \overline{U}^l_{t_2} \end{bmatrix} \begin{bmatrix} \overline{E}^l_{t_1} \\ \overline{E}^l_{t_2} \end{bmatrix} = \begin{bmatrix} U'^l_{t_1} & \\ & U'^l_{t_2} \end{bmatrix} \begin{bmatrix} T^l_{t_1} \overline{E}^l_{t_1} \\ T^l_{t_2} \overline{E}^l_{t_2} \end{bmatrix} \approx \begin{bmatrix} U'^l_{t_1} & \\ & U'^l_{t_2} \end{bmatrix} \begin{bmatrix} E'^l_{t_1} \\ E'^l_{t_2} \end{bmatrix} \begin{bmatrix} T^{l-1}_t \end{bmatrix} \] $E'_{t_1}$ and $E'_{t_2}$ are the new transfer matrices for the children of a non-leaf node $t$, and $T_t$ is a transformation that will be used to compute the new transfer matrix from $t$ to its parent, in a similar fashion. $\left[ \begin{smallmatrix} E'^l_{t_1} \\ E'^l_{t_2} \end{smallmatrix} \right]$ are computed by first computing an SVD of the matrix $\left[ \begin{smallmatrix} T^l_{t_1} \overline{E}^l_{t_1} \\ T^l_{t_2} \overline{E}^l_{t_2} \end{smallmatrix} \right]$. The left singular vectors corresponding to singular values below the target compression threshold are truncated, and the remaining subset is partitioned to generate the new transfer matrices $E'_{t_1}$ and $E'_{t_2}$. $T_t$ is computed as $\sum_{t_i} E'^{lT}_{t_i} T^l_{t_i} E^l_{t_i}$. The structure of the truncation algorithm is identical to that of the upsweep phase in the matrix-vector multiplication. All GPUs start the truncation operations concurrently, each on its subtree, with no interprocess communication required. The computational work at every level being, for every block row, an SVD involving the leaf basis at the leaf level, or the stacked transfer operators for non-leaf levels. Within a GPU, batched SVDs are used \cite{boukaram19a}. Once all GPUs reach the C-level, a gather operation communicates the new transfer operators from the roots of the subtrees to the leaves of the root tree that is stored on a single GPU. This bootstraps the last phase of the upweep which proceeds on the root GPU. Two details remain to be discussed. First, in the downsweep phase, the algorithm relied on the basis $V$ being orthogonal. When this is not the case, a pre-processing step is needed to orthogonalize the $\mathcal{V}$ basis tree. A basis is orthogonal if $V_j^{lT} V_j^l$ is the identity matrix for all levels $l$. Orthogonalizing a basis involves performing QR on the finest level basis and then going up the tree to compute new transfer matrices that allow higher level nodes to satisfy the orthogonality condition. This is also done in an upsweep pass that is very similar to the one described above for truncation, but replacing the SVD operations by QR operations. The distributed implementation therefore also proceeds independently on all GPUs up until the C-level. A gather operation is then performed to bootstrap the orthogonalization of the top levels of the basis tree which reside on a single GPU. Finally, once a new compressed basis $U'$ is computed, it remains to approximate the coupling blocks in it. Since $U'$ is an orthogonal basis, the best approximation of a block is obtained by an orthogonal projection. Therefore, we can obtain the approximation $A'$ by projecting every low rank block $A_{ts} = U_{t} S_{ts} V_{s}^T$ on the new basis to obtain: \[ A'_{ts} = U'_{t} U'^T_{t} A_{ts} V'_{s} V'^T_{s} = U'_{t} U'^T_{t} ( U_{t} S_{ts} V_{s}^T) V'_{s} V'^T_{s} = U'_{t} (P_{Ut} S_{ts} P_{Vs}^T) V'^T_{s} = U'_{t} S'_{ts} V'^T_{s} \] The new $S'_{ts}$ coupling blocks are computed via batched matrix multiplication operations. In this step, there is parallelism across all GPUs and across all levels. In addition, The GPUs are particularly efficient in GEMM operations, and in practice this projection step consumes much less time that the other operations, particularly those involving batched SVDs. \section{Distributed-memory Matrix-Vector Multiplication} \label{sec:dist_hgemv} \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{figs/dist_hgemv.pdf} \caption{The three phases of the distributed vector product with the low rank part of the hierarchical matrix on 8 GPUs: upsweep, tree multiplication and downsweep. MPI communication is shown in the red, green, and blue arrows. Black arrows represent local operations. The gather of the root nodes of the branches of $\widehat{x}$ into the grey leaf nodes of $\pp{\widehat{x}}{r}$ is shown as the green arrow. Similarly, the blue arrow shows the scatter of the leaves $\pp{\widehat{y}}{r}$. The red arrows indicate the selective gathers of the off-diagonal data from $\widehat{x}$ into each GPU. } \label{fig:distrbuted_hgemv} \end{figure} This section describes the overall structure of the distributed multiplication operation with $nv$ vectors concurrently. We use this structure to highlight the interprocess communication bottlenecks, that are then optimized in Section \ref{sec:dist_hgemv_opt}. The input multi-vector $x$ of size $N\times nv$ is distributed among $P$ GPUs, where each sub-vector $\pp{x}{p}$ is extracted from the index set defined by the root node of $\pp{\mathcal{U}}{p}$. The hierarchical matrix-vector product operation requires a standard block sparse multiplication $A_{de} x$ for the dense blocks of the matrix, which can be overlapped with the low rank multiplication $A_{lr} x = <\!{\cal U}, {\cal S}, {\cal V}^T\!\!> x$. The low rank portion of the product is a generalization to the hierarchical tree setting of a regular dense low rank matrix $USV^T$ by a vector, and is illustrated in Figure \ref{fig:distrbuted_hgemv}. In a first phase, we perform an upsweep of the basis tree ${\cal V}$ and compute $\widehat{x} = {\cal V}^T x$, which contains the products of the matrices $V_s^{lT}$ of all block columns $s$ at all levels $l$ with the corresponding pieces $x_s$ of $x$. In a second phase, a tree $\widehat{y} = {\cal S} \widehat{x}$ is computed. $\widehat{y}$ also consists of multilevel data corresponding to the products of $\widehat{y}^l = S^l \widehat{x}^l$ for every level $l$. In the third phase, a downsweep phase through the basis tree ${\cal U}$ accumulates the multilevel $\widehat{y}$ tree data into the output vector $y$, an operation we may symbolically write as $y = {\cal U} \, \widehat{y}$. \subsection{Distributed Upsweep} \begin{figure} \includegraphics[width=\columnwidth]{figs/upsweep.pdf} \caption{Distributed Upsweep \vspace*{-10pt}} \label{fig:dist_upsweep} \end{figure} The upsweep phase is illustrated in Figure \ref{fig:dist_upsweep} and summarized in Algorithm \ref{alg:naive_dist_upsweep}. It proceeds from the leaf level where the explicitly stored block row bases, each of size $m \times k$, are simply multiplied by $x$. At every higher level, $\widehat{x}^{l-1}$ can be computed from the children at level $l$ using the transfer operators \cite{borm10}. For a parent node $s$ with children $s_1$ and $s_2$ we have \[ \widehat{x}^{l-1}_{s} = \begin{bmatrix} F_{s_1}^{l\,T} & {F_{s_2}^{l\,T}} \end{bmatrix} \begin{bmatrix} {V_{s_1}^{l\,T}} & \\ & {V_{s_2}^{l\,T}} \\ \end{bmatrix} \begin{bmatrix} x_{s_1}\\ x_{s_2} \end{bmatrix} = {F_{s_1}^{lT}} \widehat{x}^{l}_{s_1} + {F_{s_2}^{lT}} \widehat{x}^{l}_{s_2}. \] \begin{algorithm} \caption{Single GPU Upsweep for forming local $\pp{\widehat{x}}{p}$} \label{alg:upsweep2} \begin{algorithmic}[1] \Procedure{upsweep}{$V$, $F$, $x$, $\widehat{x}$} \State $q$ = depth$( \widehat{x} )$ \Comment{{\small \emph{leaf level, log$(\pp{N}{p}/m)$}}} \State $\widehat{x}^{q} = $ gemvBatched $(\pp{N}{p}/m, V^T, x)$ \Comment{{\small \emph{$\widehat{x}^{q}=V^T x$}}} \For{$l$ = $q \rightarrow {}1$} \Comment{{\small \emph{up the $\cal{V}$ tree}}} \State $nb$ = $\pp{N}{p} / m / 2^{q-l+1}$ \State $[\batch{F^l}, \batch{\widehat{x}^l}, \batch{\widehat{x}^{l-1}}]$ = marshalUpsweep$(F^{l}, \widehat{x}^{l}, \widehat{x}^{l-1})$ \vspace{0pt} \For{$j$ = $1 \rightarrow 2$} \Comment{{\small \emph{binary tree}}} \State $\batch{\widehat{x}^{l-1}}(j)\mathrel{+}= $ gemvBatched $(nb, \batch{F^l}(j)^T, \batch{\widehat{x}^l}(j))$ \EndFor \EndFor \EndProcedure \end{algorithmic} \end{algorithm} \begin{algorithm} \caption{Distributed Upsweep} \label{alg:naive_dist_upsweep} \begin{algorithmic}[1] \Procedure{DistUpsweep}{$P$, $p$, $\pp{x}{p}$, $\pp{\mathcal{V}}{r}$, $\pp{\mathcal{V}}{p}$, $\pp{\widehat{x}}{r}$, $\pp{\widehat{x}}{p}$} \State upsweep$(\pp{\mathcal{V}}{p}.V, \pp{\mathcal{V}}{p}.F, \pp{x}{p}, \pp{\widehat{x}}{p} )$ \If $p = 0$ \vspace*{-1pt} \State $l = $ depth$( \pp{\mathcal{V}}{r} )$ \Comment{{\small \emph{C-level}}} \LineComment{{\small \emph{Gather the roots of $\pp{\widehat{x}}{p}$ into the leaf level of $\pp{\widehat{x}}{r}$}}} \vspace*{-0.5pt} \State $\pp{\widehat{x}^l}{r} = $ gather$( \pp{\widehat{x}^0}{p} )$ \LineComment{{\small \emph{Ignore the leaves by passing \texttt{null}}}} \vspace*{-0.5pt} \State upsweep$\left( \text{null}, \pp{\mathcal{V}}{r}.F, \text{null}, \pp{\widehat{x}}{r} \right)$ \EndIf \EndProcedure \end{algorithmic} \end{algorithm} In the distributed setting, the upsweep on each GPU $p$ can proceed in parallel on each of the local branches $\pp{\mathcal{V}}{p}$ independently, using the kernel shown in Algorithm \ref{alg:upsweep2}. Once the upsweep reaches the roots of each branch, the data from all root nodes of the $\pp{\widehat{x}}{p}$ trees are gathered on the master process to populate the leaf level of the root branch $\pp{\mathcal{V}}{r}$, allowing the upsweep to complete. The regular upsweep Algorithm \ref{alg:upsweep2} can be used for the branch upsweep as well as the root upsweep by simply omitting the first batched operation on the leaves of the root branch, since that step is replaced by the gathering of the data. From an efficiency perspective, the primary challenge in the upsweep comes from the fact that the individual operations in the basis tree nodes involve small matrix operators that do not possess a sufficient amount of data parallelism for effective GPU utilization. We overcome this problem by marshaling the appropriate level data to allow batched GPU kernels to be invoked, allowing $\widehat{x}$ to be computed with only $O(\log N)$ batched kernel executions. Except for the top few levels of the root process $r$, these executions happen concurrently on the $P$ GPUs. The marshaling GPU kernel is shown for a step of the upsweep operation in Algorithm \ref{alg:hgemv_marshalupsweep}. The marshaling kernel essentially plays the role of a fast static scheduler for all operations performed on a given level $l$ of the tree. It prepares for the execution of the operations by efficiently gathering data from the basis tree. Marshaling involves no data movement and therefore has very little overhead and in practice consumes only a tiny fraction of total execution time. \begin{algorithm} \caption{GPU Upsweep Marshaling Kernel} \label{alg:hgemv_marshalupsweep} \begin{algorithmic}[1] \Procedure{marshalUpsweep}{$F^{l}$, $\widehat{x}^{l}$, $\widehat{x}^{l-1}$} \vspace*{-2pt} \LineComment{{\small \emph{uses the arrays of a flattened tree data structure }}} \State $n_p$ = levelptr$[l-1]$, $k_p$ = levelrank$[l-1]$ \State $n_c$ = levelptr$[l]$, $k_c$ = levelrank$[l]$ \ForAllp{$p = n_p \rightarrow n_c$} \vspace*{-1pt} \State $i = p - n_p$ \Comment{{\small \emph{Batch index}}} \State $c$ = head$[p]$, $c_i = 0$ \While {$c \neq \text{empty}$} \vspace*{-1pt} \LineComment{{\small \emph{Extract level pointer data}}} \State $\batch{F^l}(c_i)[i] = $ ptr$(F^{l}) + (c - n_c) \times k_c \times k_p$ \State $\batch{\widehat{x}^l}(c_i)[i] = $ ptr$(\widehat{x}^{l}) + (c - n_c) \times k_c$ \State $\batch{\widehat{x}^{l-1}}(c_i)[i] = $ ptr$(\widehat{x}^{l-1}) + i \times k_p$ \State $c = $ next$[c]$, $c_i = c_i + 1$ \EndWhile \EndForAllp \EndProcedure \end{algorithmic} \end{algorithm} \vspace*{-4pt} \subsection{Distributed Intermediate Multiplication} The second phase of the operation builds a vector tree $\widehat{y}$, where each node $t$ in a level $l$ is the product of the block row $t$ of level $l$ of the coupling matrix tree with the corresponding nodes in $\widehat{x}$. This operation can be expressed as \[ \vspace*{-3pt} \widehat{y}_t^{l} = \sum_{s \in \{b_t\}} S_{ts}^l \widehat{x}_s^{l} \] where $b_t$ is the set of column indices of the matrix blocks in the block row $t$. This is a block sparse matrix-vector multiplication at every level, and is illustrated in the middle portion of Figure \ref{fig:distrbuted_hgemv}, where the block-row, multi-GPU decomposition of each level is also highlighted. The scalar version of this problem is a well-studied computational kernel that has many possible high quality solutions \cite{guo16,merrill16,bienz19,elafrou19} which may be adapted to the block-sparse version. While we could rely on vendor kernels, their relatively low performance and lack of support for non-uniform blocks necessitates a different approach. Our solution relies on a key result regarding hierarchical matrices which puts a bound on the sparsity constant $C_{sp}$, the maximum number of blocks in any block row $t$ at any level $l$ of the matrix tree. Such constant is bounded by a dimension-independent $O(1)$ value that only depends on the specific structure of the matrix and the admissibility criterion\cite{grasedyck03,borm10}. During the construction of the matrix tree, we generate conflict-free batches of matrix products that can then be executed by a series of non-uniform batched matrix-vector and matrix-matrix kernels. A conflict-free ordering of the batch indices can be obtained by assigning a batch index based on the position within the block row or column that increases from left to right, allowing us to marshal all the batches in a single marshaling kernel. While there will potentially be some kernels that perform little work, the bounded sparsity constant guarantees that there will be few of them, and they will thus represent a small portion of the total runtime. This could be optimized further by running those small batches on a separate low priority stream and then combining the results with the main execution stream. The boundedness of the sparsity constants $C_{sp}$ also guarantees that the block row local to a GPU will require input from $\widehat{x}$ nodes belonging to a limited number of remote GPUs: we therefore consider a standard approach in distributed memory sparse matrix vector products, and split the block row into diagonal and off-diagonal parts. The contributions of these two parts can be overlapped with the needed communication as described in Section \ref{sec:fastgather}. Once the needed parts of $\widehat{x}$ are assembled, the multiplication phase can proceed on each GPU independently on the coupling matrices of $\pp{\mathcal{S}}{p}$ using the \texttt{treeMultiply} routine of Algorithm \ref{alg:mult}. Processing the multiplication of the root branch $\pp{\mathcal{S}}{r}$ on the master process to produce the root branch $\pp{\widehat{y}}{r}$ finalizes the phase as shown in Algorithm \ref{alg:naive_dist_mult}. The \texttt{selectiveGather} routine communicates and assembles the needed portion of the $\widehat{x}$ tree from the remote branches to use in the local \texttt{treeMultiply}. This is described in Section \ref{sec:fastgather}. \newlength{\textfloatsepsave} \setlength{\textfloatsepsave}{\textfloatsep} \setlength{\textfloatsep}{-20pt \begin{algorithm} \caption{GPU Matrix Tree Multiplication for $\widehat{y}$} \label{alg:mult} \begin{algorithmic}[1] \Procedure{treeMultiply}{$S$, $\widehat{x}$, $\widehat{y}$} \State $q$ = depth$( \widehat{y} )$ \ForAllp{ $l$ = $1 \rightarrow q$} \State $\widehat{y}^{l}$ = blockSparseMV$( S^{l}, \widehat{x}^{l})$ \Comment{{\small \emph{conflict-free batches}}} \EndForAllp \EndProcedure \end{algorithmic} \vspace*{-2pt} \end{algorithm} \begin{algorithm} \caption{Distributed Multiplication} \label{alg:naive_dist_mult} \begin{algorithmic}[1] \Procedure{DistTreeMult}{$P$,$p$, $\pp{\widehat{x}}{r}$, $\pp{\widehat{x}}{p}$, $\pp{\mathcal{S}}{r}$, $\pp{\mathcal{S}}{p}$, $\pp{\widehat{y}}{r}$, $\pp{\widehat{y}}{p}$} \State $\widehat{x} = $ selectiveGather$( \pp{\widehat{x}}{p}, P )$ \Comment{{\small \emph{See section} \ref{sec:fastgather} }} \State treeMultiply$\left( \pp{\mathcal{S}}{p}, \widehat{x}, \pp{\widehat{y}}{p} \right)$ \vspace*{-1pt} \If $p = 0$ \State treeMultiply$\left( \pp{\mathcal{S}}{r}, \pp{\widehat{x}}{r}, \pp{\widehat{y}}{r} \right)$ \EndIf \EndProcedure \end{algorithmic} \vspace*{-2pt} \end{algorithm} \setlength{\textfloatsep}{\textfloatsepsave} \subsection{Distributed Downsweep} The vector tree $\widehat{y}$ now contains, at every level $l$, a partial contribution to the output vector $y$ expressed in terms of the bases $U^l$, and it could be computed as $U_t^l \widehat{y}_t$ if the bases at level $l$ were explicitly available. However, since we only store interlevel transfer operators, we express $\widehat{y}_t^l$ in terms of bases of the children of node $t$ and accumulate them in a downsweep phase through the ${\cal U}$ tree from root to leaves. This partial accumulation takes the form \[ U^{l-1}_{t} \widehat{y}^{l-1}_{t} + \begin{bmatrix} U^l_{t_1} \widehat{y}^l_{t_1} \\ U^l_{t_2} \widehat{y}^l_{t_2} \end{bmatrix} = \begin{bmatrix} U^l_{t_1} & \\ & U^l_{t_2} \end{bmatrix} \begin{bmatrix} E^l_{t_1} \hat{y}^{l-1}_{t} + \widehat{y}^l_{t_1}\\ E^l_{t_2} \hat{y}^{l-1}_{t} + \widehat{y}^l_{t_2} \end{bmatrix} \] between a parent node at level $l-1$ and children $t_1$ and $t_2$ at the finer level $l$. The downsweep procedure, pictured in the left part of Figure \ref{fig:distrbuted_hgemv}, is summarized in Algorithm \ref{alg:naive_dist_downsweep}. A downsweep through the root subtree $\pp{\widehat{y}}{r}$ is first performed. Once the leaf level of $\pp{\widehat{y}}{r}$ has been updated, it can be scattered from the master process to all other GPUs and added to the roots of local trees $\pp{\widehat{y}}{p}$ containing data from the previous phase of the multiplication. When the roots of the local branches $\pp{\widehat{y}}{p}$ on the $P$ GPUs have their proper accumulation, obtained from the leaves of the tree $\pp{\widehat{y}}{r}$, we can sweep down $\pp{\widehat{y}}{p}$ independently on all GPUs setting each node to $\pp{\widehat{y}}{p}_{t_i}^{l} = \pp{\widehat{y}}{p}_{t_i}^{l} + \pp{E_{i}^{l}}{p} \ \pp{\widehat{y}}{p}_{t}^{l-1} $; the level $l$ at each step now also contains the partial sum of $\pp{y}{p}$ for all levels above $l$ expressed in the basis of $U^l$. The leaf level will then contain the complete sum which is finally expanded into $\pp{y}{p}$ through a multiplication by the explicitly stored leaf level bases. We follow the same approach used for the upsweep, where each level is also processed in parallel by first marshaling the operations and then executing using a batch matrix vector product. This leads us to Algorithm \ref{alg:downsweep} for computing $\pp{y}{p}$, i.e., the distributed vector $y$. The downsweep marshaling algorithm is structurally similar to the one described in Algorithm \ref{alg:hgemv_marshalupsweep} and is omitted for brevity. \begin{algorithm} \caption{Single-GPU downsweep for forming local $\pp{y}{p}$} \label{alg:downsweep} \begin{algorithmic}[1] \Procedure{downsweep}{$U$, $E$, $\widehat{y}$, $y$} \State $q$ = depth$( \widehat{y} )$ \Comment{{\small \emph{leaf level, log($\pp{N}{p}/m)$}}} \For{$l$ = $1 \rightarrow q$} \Comment{{\small \emph{down the $\cal{U}$ tree}}} \State $nb$ = $\pp{N}{p} / m / 2^{q-l}$ \State $[\batch{E^l}, \batch{\widehat{y}^{l-1}}, \batch{\widehat{y}^l}]$ = marshalDownsweep$(E^{l}, \widehat{y}^{l-1}, \widehat{y}^{l})$ \State $\batch{\widehat{y}^{l}} \mathrel{+}= $ gemvBatched$(nb, \batch{E^l}, \batch{\widehat{y}^{l-1}})$ \EndFor \State $y = $ gemvBatched $\left( \pp{N}{p}/m, U, \, \widehat{y}^{q} \right)$ \EndProcedure \end{algorithmic} \end{algorithm} \begin{algorithm} \caption{Distributed Downsweep} \label{alg:naive_dist_downsweep} \begin{algorithmic}[1] \Procedure{DistDownsweep}{$P$, $p$, $\pp{y}{p}$, $\pp{\mathcal{U}}{r}$, $\pp{\mathcal{U}}{p}$, $\pp{\widehat{y}}{r}$, $\pp{\widehat{y}}{p}$} \If $p = 0$ \Comment{{\small \emph{Ignore the leaves by passing \texttt{null}}}} \State downsweep$( \text{null}, \pp{\mathcal{U}}{r}.E, \pp{\widehat{y}}{r}, \text{null})$ \EndIf \State $l = $ depth$( \pp{\mathcal{U}}{r} )$ \Comment{{\small \emph{C-level}}} \LineComment{{\small Scatter the leaf level of $\pp{\widehat{y}}{r}$ into the roots of $\pp{\widehat{y}}{p}$}} \State $\pp{\widehat{y}^0}{p} = \pp{\widehat{y}^0}{p} + \text{scatter}( \pp{\widehat{y}^l}{r} )$ \State downsweep$\left(\pp{\mathcal{U}}{p}.U, \pp{\mathcal{U}}{p}.E, \pp{y}{p}, \pp{\widehat{y}}{p} \right)$ \EndProcedure \end{algorithmic} \end{algorithm} \section{Optimizing Communication} \label{sec:dist_hgemv_opt} \subsection{Optimizing Communication Volume} \label{sec:fastgather} We first discuss a communication-optimized parallel block sparse matrix-vector multiplication for a given level matrix $S^l$ of $A_{lr}$, the low rank portion of the hierarchical matrix; the same logic applies to $A_{de}$ and it is omitted for brevity. The matrix tree is first split into two distinct trees: a diagonal matrix tree $\pp{S^l}{p}_p$ and an off-diagonal matrix tree $\pp{S^l}{p}_{\comp{p}}$. While the off-diagonal portion could simply be represented as a set of trees, with one tree for every interaction $\pp{S^l}{p}_{q}$ with a GPU $q$, it is far more efficient to have them all in a single flattened one to allow marshaling operations on the off-diagonal blocks to be completed with a single kernel call. Once the trees are split, the list of basis nodes that interact with $\pp{S^l}{p}_{\comp{p}}$ can be generated by iterating through its $(t, s)$ pairs and determining all unique $s$ values. Given the boundedness of the sparsity constant $C_{sp}$, on a given level $l$, a GPU $p$ will receive data only from a few other GPUs; we thus determine the list of GPUs that need to send data to $p$, as well as the list of nodes that should be received, and store such information in a compressed-storage format as representatively shown in Figure \ref{fig:compressed_vnodes}. The data needed from process \texttt{pid}$[i]$, corresponding to global indices listed in \texttt{nodes} from \texttt{nodes\_ptr}$[i]$ to \texttt{nodes\_ptr}$[i+1]$, is communicated among GPUs during the setup phase. A list of unique entries of \texttt{nodes} represents the compressed storage for the offiagonal block. \begin{figure} \vspace*{-12pt} \centering \includegraphics[width=0.8\columnwidth]{figs/block_row_compressed.pdf} \def1.0{1.0} \newcolumntype{C}{>{\centering\arraybackslash}p{2.5ex}} \begin{tabular}{|c|C|C|C|C|C|C|C|C|C|C|C|C|C|C|C|} \hline \texttt{pid} & 1 & 3 & & & \\ \hline \texttt{nodes\_ptr} & 0 & 2 & 5 & & \\ \hline \texttt{nodes} & 5 & 6 & 12 & 13 & 14 \\ \hline \end{tabular} \caption{The compressed node data for $\pp{S^l}{0}_{\comp{p}}$ of a hierarchical matrix distributed to 4 GPUs. Process 2 has no corresponding basis tree data and it is not listed in \texttt{pid}. \vspace*{-10pt}} \label{fig:compressed_vnodes} \end{figure} The diagonal multiplication phase can proceed without any communication while the off-diagonal phase needs input from other GPUs. The nodes at a level $l$ of the local $\pp{\widehat{x}}{p}$ branch which are needed by other GPUs are packed into a single buffer using a marshaling kernel and a single batched copy kernel populates a send buffer $B_s^l$, which is then used to issue non-blocking sends to the neighboring GPUs. Non-blocking receives are issued to populate a receive buffer $B_r^l$, which can then be directly used for the off-diagonal level of the tree, since the column basis indices have already been updated to use the compressed node format. Algorithm \ref{alg:optimized_dist_mult} summarizes the overall communication-optimized multiplication phase. The \texttt{exchangeData} routine executes the non-blocking MPI sends and receives using the compressed off-diagonal data that is marshaled using the \texttt{marshalOffdiag} routine and copied using a batch kernel. \begin{algorithm} \caption{Optimized Multiplication Phase} \label{alg:optimized_dist_mult} \begin{algorithmic}[1] \Procedure{optTreeMult}{$\pp{\mathcal{S}}{p}, \pp{\widehat{x}}{p}, \pp{\widehat{y}}{p}$, $\text{recv}$, $\text{send}$} \State $nv = $ vectors($\pp{\widehat{x}}{p}$) \State $d = $ depth($\pp{\widehat{x}}{p}$) \For $l = 0 \rightarrow d$ \State $[\batch{B}, \batch{x}]$ = \text{marshalOffdiag}$\left( B_s^l, \widehat{x}^l, \text{send}, nv \right)$ \State batchCopy $(\batch{B}, \batch{x})$ \LineComment{{\small \emph{non-blocking Isends and Irecvs}}} \State \text{exchangeData}($B_s^l$,$B_r^l$, $\text{recv}[l]$,$\text{send}[l]$,$nv$) \EndFor \State treeMultiply$(\pp{\mathcal{S}}{p}_p, \pp{\widehat{x}}{p}, \pp{\widehat{y}}{p})$ \Comment{{\small \emph{Diagonal mult}}} \State waitAll(\,) \Comment{{\small \emph{Wait for all transfers to complete}}} \label{alg:optimized_dist_mult:wait_all} \State treeMultiply$(\pp{\mathcal{S}}{p}_{\comp{p}}, B_r, \pp{\widehat{y}}{p})$ \Comment{{\small \emph{Off-diagonal part}}} \EndProcedure \end{algorithmic} \end{algorithm} \subsection{Achieving Communication and Computation Overlap} While the communication volume has been reduced and a portion of the communication can be hidden by overlapping it with the diagonal multiplication, there are still a few challenges left that hold back performance. Assuming the lack of hardware support for more advanced memory transfer features such as GPUDirect RDMA, transferring the data from the GPU to the host adds some overhead to the execution, as well as synchronization points that impact GPU usage. Moreover, not all MPI distributions guarantee that communication can progress in the background without explicit intervention from the process. The effectiveness of overlapping the diagonal multiplication phase with the needed communication depends on the structure of the tree, the capabilities of the communication network, and the compute capabilities of the GPU. For a tailored, fine-grained control of the communications involved in the algorithm at hand, we explicitly create communication threads that queue up asynchronous copies on separate streams to overlap the transfers with the processing of each level of the local branch upsweep. The transfers can then be carried out on the same thread without interrupting or forcing synchronizations with the main execution stream, allowing communication and computation to overlap. When the diagonal block kernels have been queued up on the stream, the communication thread can then join the main thread. The multiplication of the root branch on the master process can also be hidden, to some extent, by overlapping it with the main stream of work, and scheduling it on a low priority stream. This will allow the work to be completed during phases of low GPU utilization, such as the smaller top levels of the basis and matrix tree. Finally, by adding the dense block multiplication phase to a low priority stream, GPU utilization on all GPUs can be increased as well. Figure \ref{fig:streaming_distributed} shows the effect of overlapping communication with computation on the timeline of the overall distributed matrix-vector multiplication. As expected, the gaps in the timeline due to communication are significantly smaller when it is overlapped with the computation. \begin{figure*}[ht] \setlength{\fboxsep}{0pt} \raggedright \fbox{\includegraphics[height=.72cm]{figs/no_overlap_timeline.pdf}} \\ \vspace*{2pt} \raggedright \fbox{\includegraphics[height=.72cm]{figs/overlap_timeline.pdf}} \caption{Execution timeline for $P=8$ of GPU $p=0$ without (top) and with (bottom) overlapping communication with computation. The first row in each figure is the main computation stream, the second is the secondary communication stream, and the third is the low priority stream. Computational kernels are in blue, purple and cyan. Transfers to and from the CPU and GPU are in gold. Large gaps represent MPI communication.} \label{fig:streaming_distributed} \end{figure*} \section{Distributed Data Structures for $\mathcal{H}^2${} Matrices} \label{sec:hrep} \subsection{$\mathcal{H}^2${} Matrix Structure} The representation of an $\mathcal{H}^2${} matrix exploits two kinds of hierarchies: a hierarchy of blocks at different levels of granularity and a hierarchy of bases that is used to represent the data in the blocks. At every level of the hierarchy the low rank blocks essentially form a block sparse matrix. In addition, there is a block sparse matrix that stores the dense blocks of the matrix that are not amenable to low rank representations. \begin{figure}[!ht] \begin{subfigure}{\columnwidth} \centering \hspace*{-8pt} \includegraphics[width=0.8\textwidth,clip,trim={4.3cm 16.7cm 22.2cm 0}]{figs/matrix_trees.pdf} \vspace*{-4pt} \caption{Leaves of the matrix tree: (left) in the $\mathcal{H}${} format, leaf blocks such as the one labeled at level 2 of the tree, $A^2_{ts}$, are stored as low rank factorizations; (right) in the $\mathcal{H}^2${} format, low rank blanks are represented by much smaller coupling blocks $S^2_{ts}$.} \label{fig:hmatrix_leaves} \end{subfigure} \begin{subfigure}{\columnwidth} \centering \includegraphics[height=2cm]{./figs/hmatrix_level_0.pdf} \includegraphics[height=2cm]{./figs/hmatrix_level_1.pdf} \includegraphics[height=2cm]{./figs/hmatrix_level_2.pdf} \includegraphics[height=2cm]{./figs/hmatrix_level_3.pdf} \includegraphics[height=2cm]{./figs/hmatrix_level_4.pdf} \vspace*{-5pt} \caption{Levels of the matrix tree. Inner nodes are in cyan, low rank leaves in green, and dense leaves in red.} \label{fig:hmatrix_levels} \end{subfigure} \caption{General partitioning of a hierarchical matrix.} \label{fig:hmatrix_levels_and_leaves} \end{figure} \emph{Hierarchy of Blocks.} Let $\mathcal{I}$ and $\mathcal{J}$ be the sets of indices of the rows and columns of a matrix, and $T_{\mathcal{I}}$ and $T_{\mathcal{J}}$ be hierarchical clusterings of these index sets, respectively. All blocks within the matrix can then be defined by cluster pairs $(t, s) \in T_{\mathcal{I} \times \mathcal{J}}$. Define an admissible block as a block that is either small enough to be stored in dense form of size $m \times m$, with $m$ denoting the so-called leaf size, or can be well approximated by a low rank matrix. A matrix $A$ in the $\mathcal{H}$-variant of hierarchical matrices can be partitioned into admissible blocks of various sizes that are organized hierarchically as the leaves of a \emph{matrix tree}. A low rank matrix $A^l_{ts}$ on level $l$ of the tree and defined by the cluster pair $(t, s)$ is represented as the outer product of two tall matrices $B^l_{ts}$ and $C^l_{ts}$ of rank $k^l$: $A^l_{ts} = B^l_{ts}{C^l_{ts}}^T$. The left panel of Figure \ref{fig:hmatrix_leaves} shows the leaves of this matrix tree which define a complete partitioning of the matrix into blocks, with dense leaves colored red and low rank leaves colored green. Figure \ref{fig:hmatrix_levels} shows the various levels of the tree, where inner nodes are in cyan. The structure of this matrix tree depends on the application. For example, in problems involving a spatial discretization, we can leverage data from the particles or nodes generated by the discretization to generate it with the aid of a geometric admissibility condition \cite{hackbusch15}. Other applications might rely on the available algebraic data or heuristics to determine which blocks of the matrix are admissible as low rank blocks. \emph{Hierarchy of Bases.} The $\mathcal{H}^2${} representation uses block low rank factorizations of the form $A^l_{ts} = U^l_t S^l_{ts} {V_s^{l}}^T$ for every $ts$ block at every level $l$, where $U^l_t$ and $V^l_s$ are bases for the block rows $t$ and block column $s$ of level $l$, respectively. $S^l_{ts}$ is a small $k_t^l \times k_s^l$ coupling matrix representing the interaction between the row and column cluster pairs. These coupling matrices are organized in the matrix tree $\cal{S}$ defined by $T_{\mathcal{I} \times \mathcal{J}}$. In our implementation, we currently use a fixed rank per level that we refer to as $k^l$, or even simply $k$ when the context is clear, which allows us to use higher-performing fixed-size batch linear algebra kernels when executing basis operations. \begin{figure} \centering \vspace*{-5pt} \includegraphics[width=\linewidth]{figs/basis_tree.pdf} \caption{Basis tree $\cal{U}$ of an $\mathcal{H}^2$-matrix. Leaf nodes are stored explicitly, whereas inner nodes are represented implicitly using interlevel transfer matrices $E$. } \label{fig:hmatrix_basis} \end{figure} An additional hierarchy is introduced in the row and column basis trees, where a basis node is expressed in terms of the bases of its children. Basis nodes are only stored explicitly at the leaves of the tree, and inner nodes can be computed from their children using small $k^l \times k^{l-1}$ interlevel transfer matrices. For example, one can compute an inner node $U^{l-1}_i$ from its two children, $U^l_{i_1}$ and $U^l_{i_2}$, and their corresponding transfer matrices $E^l_{i_1}$ and $E^l_{i_2}$ as \begin{equation*} \label{eq:transfer} U^{l-1}_i = \begin{bmatrix} U^l_{i_1} & \\ & U^l_{i_2} \end{bmatrix} \begin{bmatrix} E^l_{i_1} \\ E^l_{i_2} \end{bmatrix}. \end{equation*} The explicit bases at the leaves and the interlevel transfer matrices are organized in a \emph{basis tree}. Figure \ref{fig:hmatrix_basis} shows an example of the nested basis $\cal{U}$, with the implicitly represented inner nodes shaded. Putting it all together, the $\mathcal{H}^2$-matrix representation may be succinctly written as \[ A = A_{de} + A_{lr} = A_{de} + <{\cal U}, {\cal S}, {\cal V}^T \!> \] where $A_{de}$ is a block sparse matrix with dense blocks of size $m \times m$, shown as the red leaves at the finest level of the matrix tree in Figure \ref{fig:hmatrix_leaves}. $\cal{S}$ is a matrix tree of $k^l \times k^l$ coupling matrices, whose leaves, which appear at different levels, are shown as the cyan blocks in the right panel of Figure \ref{fig:hmatrix_leaves}, and $\cal{U}$ and $\cal{V}$ are the block row and block column basis trees, each consisting of $m \times k$ explicitly stored bases $U, V$ at the leaf level, and $k^l \times k^{l-1}$ interlevel transfer matrices $E$ and $F$, as shown in Figure \ref{fig:hmatrix_basis} for basis tree $\cal{U}$. The triple-tree product notation $<{\cal U}, {\cal S}, {\cal V}^T\!>$ is defined as the assembly of all blocks $ts$ of all levels $l$ where every block may be computed as $U^l_t S^l_{ts} {V_s^{lT}}$. \subsection{Distributed Representation and Construction} \label{sec:dist_construction} \begin{table} \begin{tabular}{l l} \hline Symbol & Description \\ \cline{1-1} \cline{2-2} % $P$, $p$ & Total number of GPUs, and index of the local GPU \\ $\mathcal{U},\mathcal{V}$ & Complete basis trees \\ $\mathcal{S}$ & Complete matrix tree \\ $\pp{\mathcal{U}}{p}$ & Local branch of the basis tree on GPU $p$ \\ $\pp{\mathcal{U}}{r}$ & Root branch of the basis tree on the master process \\ $\pp{\mathcal{S}}{p}$ & Local branch of the matrix tree on GPU $p$ \\ $\pp{\mathcal{S}}{r}$ & Root branch of the matrix tree on the master process \\ $\pp{\mathcal{S}}{p}_q$ & Matrix tree branch, from dual tree traversal of $\pp{\mathcal{U}}{p}$ and $\pp{\mathcal{U}}{q}$\\ $\batch{E}$, $\batch{x}$, etc. & Marshaled $E$, $x$, etc.~arrays for batched execution \\ $x, y$ & Input and output vectors \\ $\pp{\widehat{x}}{p}, \pp{\widehat{y}}{p}$ & Local branches of vector trees $\widehat{x}$ and $\widehat{y}$ on GPU $p$ \\ $\pp{x}{p}, \pp{y}{p}$ & Local sub-vectors of the input $x$ and output $y$ on GPU $p$ \\ \hline \end{tabular} \caption{Notation used. \vspace*{-6pt}} \label{table:dist_notation} \end{table} \begin{figure}[b] \centering \vspace*{-6pt} \includegraphics[width=0.9\columnwidth]{figs/dist_hmatrix.pdf} \caption{A hierarchical matrix distributed on 8 GPUs with the block rows of the dense and coupling leaves having the same color residing on the same GPU. Root branch is in grey. \vspace*{-6pt} } \label{fig:distrbuted_hmatrix} \end{figure} The description of the parallel distribution of the matrix and the algorithms operating on it uses the notation in Table \ref{table:dist_notation}. We use a left subscript to refer to local data owned by a GPU, and a triple bar subscript to refer to data that has been marshaled to allow batched GPU kernels to be invoked on it. Treating each level of the matrix tree of the hierarchical matrix as a block sparse matrix, we decompose the levels into block rows, with each block row stored on a single GPU, as illustrated in Figure \ref{fig:distrbuted_hmatrix}. The basis trees are similarly decomposed by level, assigning the nodes corresponding to the stored block rows/columns to the same GPU. This decomposition allows much of the upsweep and downsweep to be carried out independently as described in Section \ref{sec:dist_hgemv} for matrix-vector multiplication and in Section \ref{sec:compression} for matrix compression. Above a critical C-level, the decomposition stops and a single root GPU owns all top levels. The interlevel transfer operators at the roots of each of the local branch basis trees $\pp{\mathcal{U}}{p}$ are duplicated at the leaf level of $\pp{\mathcal{U}}{r}$ (see Figure \ref{fig:distrbuted_hmatrix}) to allow upsweep and downsweep operations to begin and end at the C-level. We construct the distributed matrix by first splitting the row cluster tree $T_\mathcal{I}$ into $P$ independent branches at level $l = \log P$ and a local branch $\pp{\mathcal{U}}{p}$ of the basis tree on GPU $p$ is generated for each $p \in \left\lbrace 0 \ldots P-1 \right\rbrace$. The top $l$ levels of the basis tree are kept on a master process and could potentially be split further if $P$ becomes large enough. The root branch of the matrix tree $\pp{\mathcal{S}}{r}$ can be generated on the master process in any number of ways, such as general admissibility dual tree traversal \cite{hackbusch15}. Once this matrix tree is constructed, a list of the basis nodes $L_p$ from $\pp{\mathcal{U}}{r}$ can be extracted for each GPU $p$ corresponding to the inadmissible nodes of the block row $p$ at level $l-1$ of the matrix tree. As an example, consider the distribution on $P=8$ GPUs of the fourth level of the matrix tree in Figure \ref{fig:hmatrix_levels}. The column indices corresponding to the cyan nodes are extracted for GPU $p=1$, setting $L_1=[0,1,4]$ from the second block row. Once the list for each process has been compiled, they are scattered from the master process to all other processes. Since the nodes $q$ in $L_p$ were generated from the inadmissible nodes of the matrix tree $S^{l-1}_{pq}$ that have to be subdivided further, the structure of the matrix tree $\pp{\mathcal{S}}{p}$ on each GPU can then be generated independently using multiple dual tree traversals of the root node of $\pp{\mathcal{U}}{p}$ with the nodes $q$ in $L_p$, where each traversal generates a local branch $\pp{\mathcal{S}}{p}_q$. Once the structure has been determined, the entries of the transfer and leaf matrices of the basis trees, together with the entries of the matrix tree can be populated independently on each GPU using established techniques \cite{borm10}. \section{Introduction} \label{sec:intro} Many of the large dense matrices that appear in scientific computing, machine learning, integral equations, and other applications are in fact \emph{data sparse}. They may be approximated, to arbitrary accuracy, with a memory footprint that is much smaller that the prohibitive $O(N^2)$ cost of the dense representation. Data sparsity is a consequence of the fact that certain blocks of the matrix may be represented by factorizations whose ranks are smaller than the block dimensions. These low rank blocks of the matrix may be of different sizes and may appear in general position in the matrix. The resulting representations are known as hierarchical matrices. Hierarchical matrices are often used to compress kernel matrices, where a general point set and an explicit kernel function are given. This is a natural setting for N-body problems, boundary and volume integral methods, spatial statistics, regression and discretizations of fractional and non-local operators among others. Hierarchical matrices are also effective in settings where explicit kernels do not exist. Inverses of discretization of differential operators, Schur complements, and Hessians of PDE-constrained optimization problems also result in matrices that have a structure with many low rank blocks. General linear algebraic operations are possible in the compressed representations, presenting opportunities for tackling challenging computations and provide scalable solutions for operations that would be otherwise computationally infeasible with the dense format. Hierarchical matrices come in different variants. A basic version uses a fixed blocking of the matrix (so-called weak admissibility partitioning), where every block touches the diagonal and is stored as a separate low rank factorization. The asymptotic memory footprint of this representation is $O(k N \log N)$, where $k$ is a representative rank of the blocks. Unfortunately, this basic representation requires substantial memory in practice due to both the $\log$ factor and the large ranks $k$ generally needed to reach reasonable target accuracy, as a result of the rigid partitioning of the matrix. This can be improved on in two ways. The first eliminates the logarithmic factor in the complexity estimates by expressing the block factorizations in a nested basis. The second improvement, which allows a substantial reduction in the effective $k$, allows both dense and low rank blocks of different granularity to appear in general position in the matrix, essentially allowing the matrix structure itself to be adapted to a given problem (strong admissibility partitioning). The hierarchical matrix variant with these two improvements is referred to as the $\mathcal{H}^2${} format, and reaches the optimal asymptotic memory footprint $O(k N)$. Given that memory is often the primary constraining resource in high performance computing environments, the representation of choice for large scale problems is a general, nested basis, strong admissibility, $\mathcal{H}^2${} representation. $\mathcal{H}^2${} matrices were originally motivated primarily by the needs of integral equations \cite{hackbusch02}, but their algebraic nature has allowed their application in a variety of other contexts, including, for example, the representation of Dirichlet-to-Neumann operators \cite{gillman14,gillman15}, particulate flows in periodic geometries of arbitrary shapes \cite{marple16}, Hessians of PDE-constrained problems \cite{boukaram20b}. There is tremendous interest in the development of high-performance software libraries for constructing and operating on hierarchical matrices, driven naturally by their compelling small memory footprint and lower asymptotic operational complexity. Much like quality libraries such as FMM3D \cite{fmm3d} have made it possible to spread the use of FMM technology to broad classes of problems, similar libraries for $\mathcal{H}^2${} matrices---which are algebraic generalizations of FMM---would also allow a broader use of this technology for tackling dense matrix problems that might otherwise be prohibitively expensive. Software packages that are not performance-oriented but more oriented towards readability and conciseness include \cite{ho20,massei20,ambikasaran19,h2lib}. A shared-memory high-performance package for $\mathcal{H}^2${} matrices is presented in \cite{hua21}. A high quality software for distributed-memory environments that targets large scale problems is STRUMPACK \cite{strumpack}. Distributed memory algorithms for constructing and operating on these matrices were proposed in \cite{ida14,borm08,yamazaki19}. Dynamic run-time systems to manage the scheduling of the operations of the irregular hierarchical matrix structure in a more convenient fashion through explicit task graphs are presented in \cite{aliaga17, borm19}. Manycore algorithms were presented in \cite{ohshima18,zaspel19}, and BiCG solvers on GPU clusters were demonstrated in \cite{yamazaki18}. Multicore and manycore methods for operating on hierarchical matrices including matrix-vector multiplication are discussed in \cite{biros16,biros17,erlandson20}. Algorithms for high performance computing environments suitable for large scale problems are presented in \cite{rouet16,ghysels17,yu18,rebrova18,yu19}. \begin{figure}[ht] \begin{center} \includegraphics[width=0.6\textwidth]{figs/arch.pdf} \caption{Functionality of the H2Opus library} \label{fig:arch} \end{center} \end{figure} H2Opus \cite{h2opus} is an open source, GPU-accelerated, package for hierarchical matrix computations in the $\mathcal{H}^2${} format. It supports a number of core operations (see Figure \ref{fig:arch}) for constructing these matrices from a kernel and admissibility conditions, performing BLAS-like operations including matrix-vector multiplication, basis orthogonalization, and recompression. It also provides facilities for adding a (globally) low rank matrix to an $\mathcal{H}^2${} matrix, as well as the ability to construct an $\mathcal{H}^2${} matrix from randomized sampling operations, essentially generalizing the construction of globally low rank matrix decomposition \cite{halko11} to the hierarchically low rank case. These core operations form the building blocks for higher level operations that perform matrix-matrix multiplication, generate approximate inverses iteratively, and compute Schur complements in various applications \cite{boukaram19b,boukaram20b}. The package runs on CPUs (with explicit optimizations for Intel and AMD CPUs) as well as on GPUs with the portability enabled by a lower level layer that either uses batch BLAS operations specialized to run directly on the GPUs when manycore hardware is available, or alternatively uses OpenMP to obtain batch parallelism in multicore environments. In addition, the library also supports running on the NEC-SX Vector Engine. H2Opus has interfaces to the PETSc \cite{petsc-user-ref,petsc-web-page} package, allowing the use of the extensive facilities of the latter for manipulating distributed-memory (sparse) matrices arising from the discretization of PDEs. Efficient solvers are also available in the so called Tile Low Rank format \cite{boukaram21}. In this paper, we extend the H2Opus package with distributed-memory multi-GPU operations for two of its core capabilities: matrix-vector multiplication (and the related multiplication of a hierarchical matrix by multiple vectors), and matrix recompression. Single-GPU versions of these algorithms were presented in \cite{boukaram19a}. Matrix-vector multiplication is a key building block of Krylov-type iterative solvers, appearing in the inner loops of nonlinear and eigenvalue solvers. Therefore improving its performance can substantially reduce overall time to solution. The multi-vector case is also a performance critical kernel in many contexts such as randomized hierarchical matrix-matrix multiplication, and block-Krylov methods, such as those exposed by PETSc \cite{jolivet2021ksphpddm}. The core matrix-vector multiplication can benefit from processing multiple vectors concurrently; the additional arithmetic intensity made available, relative to looping over the bandwidth-limited operation of single vector multiplication, allows substantially higher absolute performance to be achieved. Matrix recompression is also another key building block for $\mathcal{H}^2${} matrix operations, closely resembling the truncation operations on dense matrices and matrix blocks. Recompression is needed when an initial $\mathcal{H}^2${} matrix approximation is generated using a polynomial interpolation or other non-optimal bases, and algebraic recompression step is relied on to produce a storage-optimal representation for the desired accuracy. It is also needed when BLAS3 operations are performed on $\mathcal{H}^2${} matrices. These operations generally increase the apparent rank of various blocks, which would then need to be recompressed to maintain the optimal complexity. We present high performance and scalable $O(N)$ implementations of these algorithms that demonstrate near-ideal scalability on up to 1024 NVIDIA V100 GPUs, with performance exceeding 2.3 Tflop/s per GPU. At this scale, a dense kernel matrix of size 536M$\times$536M, represented as a hierarchical matrix to an accuracy of $\epsilon=10^{-7}$ can be multiplied by a single vector in $17$ ms and by 64 vectors concurrently in $66$ ms, achieving 85\% of the peak efficiency of batched GEMM operations. This pushes the state of the art beyond the results of \cite{yu18,yu19,rouet16}. The compression operation also achieves near-optimal scalability with number of GPUs, with matrices of size 67M$\times$67M compressed by a factor of 6 in their low rank memory (from an accuracy of $10^{-6}$ to an accuracy of $10^{-3}$) in around $320$ ms on 64 GPUs. The algorithms are supported by distributed data structures for representing, accessing, and operating on hierarchical matrices with nested bases. These data structures have elements similar to those found in parallel multigrid representations, with analogous restriction and prolongation transfer operators, since the low rank blocks and their bases appear at different levels of granularity and are naturally stored at multiple levels of a hierarchy. The data structures also have patterns similar to those of parallel sparse matrix representations because at every level of the hierarchy, the low rank blocks appear in general locations forming essentially a block sparse matrix whose block sizes are on the order of the block ranks, $k$. The matrix structure has a bounded sparsity constant~\cite{grasedyck03,borm10} which is exploited to optimize overall inter-process communication volume and to hide much of the MPI communication cost with concurrent local compute phases of the algorithms. Single node performance is obtained by marshaling the tree data structures in a way to allow optimized batched dense linear algebra kernels to be invoked. We finally demonstrate the use of the algorithms in the scalable solution of a 2D variable-coefficient integral fractional diffusion equation. We use the distributed-memory algorithms to construct and compress the dense operator to an accuracy of $10^{-6}$. The solution uses a Krylov method with the matrix-vector multiplication done by our distributed algorithm and the preconditioning done by a classical (non-fractional) diffusion equation which is solved by a distributed-memory algebraic multigrid method in PETSc. The results show that all aspects of the solver, including the setup of the hierarchical representation of the dense operators, the computation of the volume ``Dirichlet'' conditions, the setup of the preconditioner, and the work per iteration, scale linearly with problem size. The solver also exhibits a dimension-independent number of iterations and results in near-ideal weak scalability up to grids of size $4096\times4096$ on 64 GPUs. The rest of this paper is organized as follows. Section \ref{sec:hrep} describes the distributed representation of the data structures of an $\mathcal{H}^2${} matrix. Section \ref{sec:dist_hgemv} describes the basic distributed matrix-vector multiplication operations and Section \ref{sec:dist_hgemv_opt} presents the key optimizations to minimize inter-process communication volume and hide latencies. Section \ref{sec:compression} describes the recompression algorithms which shares many of the algorithmic structures of the matrix-vector multiplication algorithms but relies on batch QR and SVD instead of batch GEMM in lower level linear algebra. Section \ref{sec:results} presents the distributed multi-GPU scalability results for the matrix-vector multiplication and recompression algorithms as well as the integral fractional diffusion solver. We conclude with future potential directions in Section \ref{sec:conclusions}. \section{Performance Results} \label{sec:results} In this section, we report performance results for the distributed-memory matrix-vector multiplication and algebraic compression operations, as well as performance on a complete application involving the setup and solution of an integral equation. \subsection{Experimental Setup} The H2Opus library as well as the code to generate and run all examples below is open source and is available at {\tt https://github.com/ecrc/h2opus}. Batched kernels for GEMM operations are executed using MAGMA \cite{baboulin08,magma}, while SVD and QR batches are performed using the algorithms shipped with the open-source library KBLAS, available at {\tt https://github.com/ecrc/kblas-gpu}. The marshaling GPU kernel and various other utility routines use Thrust \cite{thrust19}. All tests are conducted on Summit, the IBM Power System AC922 supercomputer installed at Oak Ridge National Laboratory. Individual nodes on Summit have 6 NVIDIA V100-SXM2 GPUs with 16GB of HBM2 memory each, but we only used 4 GPUs per node (2 per socket) in our runs. Summit has a fast host-to-device bandwidth which can deliver up to 50 GB/s over PCIe 4.0; in our application, we were able to use a significant portion of it, 40 GB/s, as measured by {\tt nvprof}. It also has a fat-tree topology network for internode communication that delivers 200Gb/s of bandwidth. To assess the efficiency attained by our algorithms, we measure the performance of the single GPU batched GEMM implementation from MAGMA, with batch elements of size $64\times64$. All computations are done in double-precision and every point in every plot has been generated as the average of 10 runs after discarding the fastest and slowest timings. To test the performance and scalability of the matrix-vector multiplication and matrix compression implementations, we performed numerical experiments on two sample matrix sets with different structural characteristics. The first matrix set comes from a spatial statistics application using a point set placed on a 2D grid of side length $a$, and an exponential kernel with a correlation length of $0.1a$. The hierarchical matrix representation of this covariance matrix uses $m=64$ as the finest block size and size of the dense leaves. A geometric admissibility condition $\eta ||C_t - C_s|| \ge (D_t + D_s)/2$ is used, where $C$ and $D$ refer to the center and diagonal size of a bounding box of the corresponding point set. We use a value of $\eta = 0.9$ and set a rank $k=64$ in the low rank blocks, resulting in an approximation with relative accuracy better than $10^{-7}$ for all problem sizes. This accuracy is computed by sampling $10\%$ of the rows and computing $||Ax - A_{\mathcal{H}^2} x|| / ||Ax||$ with randomly generated vectors with entries from a uniform distribution. The resulting sparsity constant of the matrix, which is a proxy for how finely refined the matrix is in its off-diagonal portions, is $C_{sp} = 17$. At the largest size, the matrix has 23 levels, with the top 10 levels on a single master GPU, and the bottom 13 levels on separate 1024 GPUs for a matrix size of 536M. The second matrix set comes from a 3D Gaussian process and is intended to show the effect of memory pressure---due to a finer refinement in the off-diagonal blocks---on scalability. The matrices are constructed using a set of points on a 3D grid of side length $a$ and uses an exponential kernel with correlation length $0.2a$ \cite{ambikasaran16}, a similar admissibility condition to the previous case, and a rank $k=64$ for the low rank blocks. The resulting relative accuracy is now $10^{-3}$ for all problem sizes considered in this section, and the resulting matrix tree has many more leaves than in the 2D case with a larger sparsity constant $C_{sp} = 30$. \subsection{Matrix-Vector Multiplication} \subsubsection{Weak Scalability} We first report on the weak scalability of the implementation, using a number of vectors $nv$ ranging from 1 to 64. Both 2D and 3D test sets were scaled using a local matrix size of $\pp{N}{p} = 2^{19}$ per GPU. Results are summarized in Figure \ref{fig:summit_results}, with the top and bottom rows showing the results from the 2D and 3D test sets, respectively. We observed no significant variability in the timings, with the highs and lows within 1--3\% of reported average. There is a slight jitter in the plots as the problems are scaled up, due to small changes in the structure of the matrix tree affecting the amount of actual computations performed, which do not grow exactly at the same rate as the problem size. The relative efficiency was computed as $(G_P/G_{P_0}) / (P/P_0)$, the ratio of the relative flops performed and the scaling factor relative to a base case of $P_0 = 2$ GPUs. \begin{figure}[ht] \includegraphics[width=0.32\textwidth]{./figs/SUMMIT/weak_scaling_gflops.pdf} \includegraphics[width=0.32\textwidth]{./figs/SUMMIT/weak_scaling_time.pdf} \includegraphics[width=0.32\textwidth]{./figs/SUMMIT/vector_effect_on_efficiency.pdf} \includegraphics[width=0.32\textwidth]{./figs/SUMMIT/3D/weak_scaling_gflops.pdf} \includegraphics[width=0.32\textwidth]{./figs/SUMMIT/3D/weak_scaling_time.pdf} \includegraphics[width=0.32\textwidth]{./figs/SUMMIT/3D/vector_effect_on_efficiency.pdf} \caption{Scalability and efficiency of HGEMV on Summit, using matrices constructed from 2D (top) and 3D (bottom) exponential kernels.} \label{fig:summit_results} \end{figure} For the 2D tests, the scalability is near ideal up to 512 GPUs across all multiple vector sizes, $nv = 1 \dots 64$. For the single vector case, a bandwidth-limited operation, the throughput is about 150 Gflop/s per GPU. With $nv = 64$, the additional arithmetic intensity pushes the computation into a compute-bound regime and achieves 2.6 Tflop/s per GPU, more than 95\% of the sustained peak of the batched GEMM operation measured at 2.7 Tflop/s. Even with the larger data volume being communicated, corresponding to various parts of 64 vectors, the communication is essentially hidden by the local computations. Only with 1024 GPUs, the plots show a slight degradation in performance and a deviation from ideal scalability, particularly for the $nv = 64$ case, with performance dropping to 2.3 Tflop/s per GPU. The primary reason for this is that the root tree on the master GPU is now 10 levels deep and is of size $2^{16}$. The computations on this sizeable top tree become a bottleneck. In order to scale up to this number of GPUs or larger, we will need to coarsen to a single top GPU more smoothly than the $P$-to-$1$ ratio used in the current implementation. For example, the trees above a first C-level can be distributed on multiple GPUs, and back to a single GPU after a second C-level, so that the top level work is small enough to be overlapped with other parts of the computation. The results of the 3D problem test set display a similar behavior, but the communication overhead appears earlier. For the single vector case, results scale reasonably well with problem size and the relative efficiency is about 90\% with 1024 GPUs, with a performance of about 130 Gflop/s per GPU. As the number of vectors $nv$ increases however, the communication needed for transferring all the relevant portions of the $\pp{\widehat{x}}{p}$ vectors to the GPUs that need those data becomes substantial. This is in addition to the larger root tree difficulty mentioned above. The compute part of the operation grows sub-linearly with problem size because of the favorable increase in arithmetic intensity; however, the communication volume grows linearly and can no longer be hidden by the now relatively faster compute phases. While a performance of 2.6 Tflop/s per GPU is reached for 2 GPUs, the performance at 1024 GPUs reaches only 1.1 Tflop/s, an efficiency less than 45\%. \subsubsection{Strong Scalability} \begin{figure} \includegraphics[width=.49\columnwidth]{./figs/strong_scaling_2d.pdf} \includegraphics[width=.49\columnwidth]{./figs/strong_scaling_3d.pdf} \caption{ Strong scalability results for 2D (left) and 3D (right) test data.} \vspace*{-8pt} \label{fig:ss} \end{figure} We report, in Figure \ref{fig:ss}, strong scalability results of the matrix-vector multiplication for the 2D and 3D test data described above, for different numbers of test vectors. In all cases, the problem size is $N = 2^{19}$ to fit on a single GPU of Summit and is executed on an increasingly larger number of GPUs. As expected, the more arithmetically intensive multiplication involving a larger set of vectors scales better than the single vector operation. In all cases however, the limits of strong scalability is reached around 32 GPUs. This is not unexpected, since at this scale the local problem size is now only $\pp{N}{p} = 2^{14}$. There is very little local work to do to hide communication, and the whole computation takes only few milliseconds. \subsection{Matrix Compression} To test the performance and scalability of the algebraic compression routines, we used the same sets of matrices described earlier. For the 2D tests, we start with the matrix defined as above, with point clusters of size $m = 64$, and admissibility parameter $\eta = 0.9$. Its low rank blocks are initially constructed using a Chebyshev polynomial approximation of the kernel in the bounding boxes of the point clusters. A $6 \times 6$ grid is used, resulting in all low rank blocks having a uniform rank $k = 36$. Compression seeks to reduce these ranks to maintain an accuracy of $\tau = 10^{-3}$. The 2D test set was scaled using a local matrix size $\pp{N}{p} = 2^{20}$, reaching a matrix size of 67M on 64 GPUs. For the 3D tests, a point cluster size $m = 64$ and an admissibility parameter $\eta = 0.95$ are used in the matrix construction. The low rank blocks are initially computed using a tri-cubic Chebyshev polynomial approximation of the kernel in the bounding boxes of the point clusters, resulting in all low rank blocks having a uniform rank $k = 64$. Compression seeks to reduce these ranks to maintain an accuracy of $\tau = 10^{-3}$. The test test was scaled using a local matrix size $\pp{N}{p} = 2^{18}$, reaching a matrix size of 16M on 64 GPUs. \begin{figure}[ht] \includegraphics[width=.325\textwidth]{plots/weak_2d_gflops.pdf} \includegraphics[width=.325\textwidth]{plots/weak_2d_time.pdf} \includegraphics[width=.325\textwidth]{plots/weak_2d_memory.pdf} \includegraphics[width=.325\textwidth]{plots/weak_3d_gflops.pdf} \includegraphics[width=.325\textwidth]{plots/weak_3d_time.pdf} \includegraphics[width=.325\textwidth]{plots/weak_3d_memory.pdf} \caption{Scalability of algebraic compression for 2D (top) and 3D (bottom) test sets.} \label{fig:compression} \end{figure} \subsubsection{Weak Scalability} Figure \ref{fig:compression} shows the weak scalability and effectiveness of the compression operation. Compression starts with an initial phase to orthogonalize the (non-orthogonal) bases constructed by Chebyshev interpolation without modifying their ranks. We time and report the orthogonalization phase separately. This is followed by a pair of downsweep/upsweep passes to construct a new reweighed basis and truncate it, finalized with a projection of the low rank blocks on the new bases. These steps are reported together under the compression phase label. The orthogonalization phase involves fewer floating point operations and as a result it executes faster than the compression phase. In 2D, the scaling is near ideal for up to 64 GPUs, with a slight bump when moving beyond a single GPU, because of inter-GPU communication. However for $P > 1$, the execution time is essentially flat indicating that all communication has been hidden by the computational steps. In 3D, we note a slight deviation from ideal scalability when $P = 64$, because the communication volume is larger than the 2D case and it can no longer be totally hidden by local computations. The orthogonalization phase executes at around 2.1 Gflop/s/GPU (near the practically-achievable peak of 2.7 Gflop/s per GPU, as measured by the batched GEMM operation). The compression phase, featuring QR on stacks of $C_{sp}$ blocks and SVD kernels, is not able to reach that level of performance, but this limitation comes purely form the single GPU performance of the corresponding batched routines for these operations, and would be directly improved when more performant batch kernels are implemented. Nonetheless, we should note that even with our current batch kernels, the 67M and 16M matrices in 2D and 3D respectively, are compressed in just a fraction of a second, as reported in the central column of Figure \ref{fig:compression}. In the rightmost column of Figure \ref{fig:compression}, we report on the effectiveness of the compression operation in reducing the memory footprint of the low rank blocks. In the 2D case, there is a factor of $6\times$ reduction between pre-compression low rank memory (with all blocks having a uniform rank $k = 36$) and post-compression to an accuracy of $\tau = 10^{-3}$. In the 3D case, the compression is a factor of $3\times$ for the low rank data, primarily because the starting matrix was generated with a relatively small footprint (all blocks have rank 64, generated from tri-cubic polynomials) and not much reduction is possible to maintain an accuracy of $\tau = 10^{-3}$. In all cases however, we note the $O(N)$ ideal growth in memory. \subsubsection{Strong Scalability} Strong scalability results are shown in Figure \ref{fig:compression_strong_scaling}. Deviation from ideal scalability becomes noticeable as soon as the local problem size is small enough where there are not enough computations to perform locally and communication time dominates. For the 2D tests, the problem size is $2^{20}$. With $P = 8$ GPUs, the local problem size is only $\pp{N}{p} = 2^{17}$ and results in an efficiency reduction to near $50\%$. On 32 GPUs, the local problem size is $\pp{N}{p} = 2^{15}$ and the limit of strong scalability is essentially reached: there is very little local work to do and the whole operation takes a few ms, spent mostly in communications. For the 3D tests, the problem size is $2^{18}$. On $P = 4$ GPUs, the local problem size is already only $\pp{N}{p} = 2^{16}$, and the resulting efficiency drops below $50\%$. With 16 GPUs, the strong scalability limit is essentially reached as the problem size is now only $2^{14}$, with very little local work available for each GPU. \begin{figure}[ht] \begin{center} \includegraphics[width=.45\textwidth]{plots/strong_2d_time.pdf} \includegraphics[width=.45\textwidth]{plots/strong_3d_time.pdf} \end{center} \caption{Strong scalability of algebraic compression for 2D (left) and 3D (right) test sets.} \label{fig:compression_strong_scaling} \end{figure} \subsection{Integral Fractional Diffusion Equation} We consider the performance of a Krylov solver for the solution of the integral equation $\mathcal{L}[u(\mathbf{x})] = b(x)$ where $\mathcal{L}$ is the fractional diffusion operator defined as: \begin{equation} \mathcal{L}[u(\mathbf{x})] = -2 \int_{\Omega \cup \Omega_0} \frac{u(\mathbf{y}) - u(\mathbf{x})}{|\mathbf{y} - \mathbf{x}|^{n + \beta(x) + \beta(y)}} a(\mathbf{x}, \mathbf{y}) d\mathbf{y} \label{eq:integral_nd} \end{equation} The spatially varying diffusivity $a(\mathbf{x}, \mathbf{y})$ is defined as the geometric mean of the usual diffusion coefficient, $a(\mathbf{x}, \mathbf{y}) = \kappa(\mathbf{x})^{1/2} \kappa(\mathbf{y})^{1/2}$, $\beta$ is the fractional order ($0.5 < \beta < 1$) and we assume it to be constant in this experiment, $\Omega \in R^n$ is the region in which the solution $u$ is sought, and $\Omega_0 \in R^n$ is a surrounding region in which volume constraints, somewhat analogous to the Dirichlet boundary conditions in the classical diffusion equations, are imposed on the solution, $u(\mathbf{x}) = 0$ for $\mathbf{x} \in \Omega_0$. We solve the problem with $\Omega = [-1, 1]^2$, $\Omega_0 = [-3, 3]^2 \setminus [-1, 1]^2$, and constant fractional order $\beta = 0.75$. We use a diffusivity field of the form \begin{equation} \kappa(\mathbf{x}) = 1 + f(\mathbf{x}_1; 0, 1.5) ~f(\mathbf{x}_2; 0, 2.0) \end{equation} with the bump function $f$ defined as: \begin{equation} f(x; c, \ell) = \begin{cases} \mathrm{exp}\big(\! - \! \frac{1}{1-r^2}\big), \, r = \frac{x - c}{\ell /2}, & |r| < 1 \\ 0, & |r| \ge 1 \end{cases} \end{equation} and a right hand side $b(x) = 1$ in $\Omega$. The singularity of the kernel in (\ref{eq:integral_nd}) requires that the discretization of the integral be done carefully to allow standard quadrature rules to attain their theoretical convergence rate. To this end, we rewrite the integral as: \begin{align} & \int_{\Omega \cup \Omega_0} \left[ \frac{-2\left[u(\mathbf{y}) - u(\mathbf{x})\right] \, a(\mathbf{x},\mathbf{y})}{|\mathbf{y}-\mathbf{x}|^{n+2\beta}} + \frac{p_{\mathbf{x}}(\mathbf{y})}{|\mathbf{y}-\mathbf{x}|^{n+2\beta}} \right] d\mathbf{y} \, - \int_{\Omega \cup \Omega_0} \frac{p_{\mathbf{x}}(\mathbf{y})} {|\mathbf{y}-\mathbf{x}|^{n+2\beta}} \, d\mathbf{y} \label{eq:regularized} \end{align} where $p_{\mathbf{x}}(\mathbf{y})$ is a function with local support around $\mathbf{x}$ chosen to remove the singularity of the integrand and allow a trapezoidal rule to achieve its quadratic convergence. The first integral in (\ref{eq:regularized}) can be then discretized on a regular grid while the second integral involves terms that can be integrated analytically. The details are derived in \cite{alzahrani21}, which generalizes the treatment of \cite{minden20} to the variable coefficient case. This correction has the property that it allows the hierarchical matrix treatment of the kernel to remain as is, similarly to the FMM-compatible treatment of integral equations on curves \cite{hao14,wu21} and other locally-corrected quadrature schemes \cite{greengard21}. In 2D, using a regular grid of $N$ points with spacing $h$ in $\Omega$, the final discretization results in a system of the form: \begin{equation} h^2(D + K + C) u = b \end{equation} where $D$ is an $N \times N$ diagonal matrix with entries \begin{equation} D_{ii}= \sum_{\substack{j \ne i \\ \mathbf{y}_j \in \Omega \cup \Omega_0}} \frac{2 a(\mathbf{x}_i,\mathbf{y}_j)}{|\mathbf{y}_j-\mathbf{x}_i|^{2+2\beta}}, \end{equation} $K$ is an $N \times N$ formally-dense matrix with zero diagonals and entries \begin{equation} K_{ij} = -\frac{2 a(\mathbf{x}_i,\mathbf{y}_j)}{|\mathbf{y}_j-\mathbf{x}_i|^{2+2\beta}}, \ \text{for } i \ne j, \end{equation} while $C$ is a sparse matrix resulting from the regularization of the integral. $C$ is essentially the discretization of an inhomogeneous, but non-fractional, diffusion operator, and we use it to construct a preconditioner for (\ref{eq:regularized}). Its footprint on a regular grid is the same as a 5-point Laplacian discretization, for an $O(h^2)$ accuracy. (Note however that when the solution does not have sufficient regularity, only first-order convergence in solution error can be expected). The matrix $K$ is constructed and compressed as an $\mathcal{H}^2${} matrix using the H2Opus facilities described above. A $k$-d tree partitions the $N$ grid points into clusters that are distributed to the different GPUs. An admissibility condition defines the structure of the matrix. Dense blocks are generated by evaluating the kernel directly. The low rank blocks are first approximated using polynomial Chebyshev approximations of the kernel on bounding boxes of the point clusters, and they are then algebraically compressed to generate the matrix that is used during the solution phase. The diagonal matrix $D$ is constructed by noting that its entries can be recast as the product $\hat{K} \mathbf{1}$, where $\hat{K}$ is a matrix similar to $K$, but defined on the larger region $\Omega \cup \Omega_0$, discretized with the same $h$, and $\mathbf{1}$ is a vector of ones. We therefore use the distributed-memory facilities of H2Opus to generate $\hat{K}$, perform the matrix-vector multiplication, to compute the diagonal entries of $D$. $\hat{K}$ is then discarded. Finally, the sparse matrix $C$ is distributed among the processors using the same blockwise row partitioning of the matrix $K$, and its entries computed explicitly. The Krylov solver uses the facilities of the PETSc library. The operator to be inverted is symmetric positive definite, and we thus employ a preconditioned conjugate gradient method as solver. For the preconditioning step, we consider a smoothed aggregation algebraic multigrid method constructed on the matrix $C$, using a diagonally preconditioned Chebyshev method as a smoother. The setup of the preconditioner runs partly on the CPU and partly on the GPU, while the Krylov solver, including the preconditioner application, runs entirely on the GPU \cite{mills2020toward,zhang2021petscsf}. The weak scalability of the solver is shown in Figure \ref{fig:solver} on grids of size $512 \times 512$, $1024 \times 1024$, $2048 \times 2048$, and $4096 \times 4096$ using 1, 4, 16, and 64 GPUs respectively. Setup times are shown in the left panel as a function of the size of the problem $N$, and they include all the necessary steps to assemble the operator to be inverted together with the setup of the preconditioner. The only setup computation not included in the timing is the construction of the $k$-d tree for the matrix structure generation. This is an $O(N \log^2 N)$ computation that is currently performed sequentially on the CPU. In the right panel, we report the total time for the Krylov solver, and the time per iteration as the problem size $N$ is scaled up. \begin{figure}[ht] \includegraphics[width=.45\textwidth]{plots/weak_petsc_setup.pdf} \label{fig:ws_setup} \includegraphics[width=.45\textwidth]{plots/weak_petsc_time.pdf} \label{fig:ws_solve} \caption{Performance of integral fractional diffusion solver in 2D} \label{fig:solver} \end{figure} Perfect weak scaling can be observed for the operators' setup; the increase in total solving time can be attributed to a slight increase in the number of Krylov iterations being 24, 26, 30 and 32 using 1, 4, 16, and 64 GPUs respectively. Since the domain $\Omega$ is kept fixed in the above tests while the discretization step is reduced, these results confirm the algorithmic scalability of the solver as well as of its parallel implementation. We are not aware of other software libraries that can readily handle variable coefficient fractional diffusion problems at this scale.
{'timestamp': '2021-09-14T02:20:04', 'yymm': '2109', 'arxiv_id': '2109.05451', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05451'}
arxiv
\section{Discussion on settings without Assumption~\ref{assump:commonness} (commonness assumption)}\label{sec:discussion} Recall that Theorem~\ref{result:waiting-time-priority} is based on Assumption~\ref{assump:commonness} (commonness assumption). More generally, we have a bound on the mean waiting time of P-Priority without requiring commonness, although in that case the order-wise optimality of P-Priority is not guaranteed. We first define the necessary notation, and then state the general bound. Define $ i^*_1 \triangleq \min\left\{i\in[I] \;\middle|\; \delta_i = \Obrac{\sqrt{n\ell_i}\log n}\right\}$, and $i^*_2 \triangleq \indexmain = \min\left\{i\in[I]\;\middle|\; \delta_i=\obrac{\sqrt{\sigma^2_i}/\log n}\right\} $. Because of Assumption~\ref{assump:traffic}, the two sets are non-empty so $i^*_1$ and $i^*_2$ are well-defined. Because by definition $n\ell_i \geq \sev_{\min} \sigma^2_i$ and $\delta_i$'s are monotonically decreasing, we have $i^*_1 \leq i^*_2$. Moreover, $\sigma^2_i$ and $\ell_i$ are monotonically increasing, so for any $i^*_2 \leq i \leq I$, $\delta_i = \obrac{\sqrt{\sigma^2_i}/\log n}$; for any $i^*_1 \leq i < i^*_2$, $\delta_i = \Obrac{\sqrt{n\ell_i}\log n}\cap \Wbrac{\sqrt{\sigma^2_i}/\log n}$; for any $1\leq i < i^*_1$, $\delta_i = \wbrac{\sqrt{n\ell_i}\log n}$. \begin{thm}[Waiting times of P-Priority without Assumption~\ref{assump:commonness}] Consider the multiserver-job system with $n$ servers satisfying Assumption~\ref{assump:traffic} and \ref{assump:lm-bound}. Under P-Priority, for each $i\in[I]$, the expected waiting time for type $i$ jobs and the mean waiting time satisfy:\\ \begin{equation}\label{eq:discuss:individual-waiting-time-priority-case1} \mathbb{E}\big[T^w_i(\infty)\big]^\textnormal{P-Priority} \leq \frac{1}{\lambda_i} \frac{\sev_{\max}\sigma^2_i}{\ell_i (\delta_i - \ell_i)} \cdot \left(1+o(1)\right)\quad \text{ for $i\geqi^*_2$}; \end{equation} \begin{equation}\label{eq:discuss:individual-waiting-time-priority-case2} \mathbb{E}\big[T^w_i(\infty)\big]^\textnormal{P-Priority} \leq \Obrac{ \frac{1}{\lambda_i} \frac{\sqrt{\sigma^2_i}\log n}{\ell_i}}\quad \text{ for $i^*_1\leq i<i^*_2$}; \end{equation} \begin{equation}\label{eq:discuss:individual-waiting-time-priority-case3} \mathbb{E}\big[T^w_i(\infty)\big]^\textnormal{P-Priority} \leq \exp\left(-\Wbrac{\frac{\delta_i^2}{n\ell_i}}\right)\quad \text{ for $1\leq i<i^*_1$}. \end{equation} Thus, the mean waiting time satisfies \begin{equation}\label{eq:discuss:mean-waiting-time-priority} \E\big[T^w(\infty)\big]^\textnormal{P-Priority} \leq \frac{1}{\lambda} \sum_{i=i^*_2}^I \frac{\sev_{\max}\sigma^2_i}{\ell_i (\delta_i - \ell_i)} \cdot \left(1+o(1)\right) + \sum_{k=i^*_1}^{i^*_2-1} \Obrac{ \frac{1}{\lambda} \frac{\sqrt{\sigma^2_k}\log n}{\ell_k}}. \end{equation} \end{thm} When we have the commonness assumption, the second term on the right of \eqref{eq:discuss:mean-waiting-time-priority} has a strictly smaller order than the first term (see the proof of Theorem~\ref{result:waiting-time-priority} in Section~\ref{sec:proof:priority}), so the upper bound matches the lower bound asymptotically in order. Without the commonness assumption, it is unclear whether P-Priority achieves the optimal order. We leave a tighter bound on the mean waiting time under P-Priority for future work. \section{Conditions for applying drift method}\label{sec:app:drift-cond} \subsection{Drift method in general markov chain}\label{sec:app:drift-cond-general} In this subsection, we consider a continuous-time Markov chain $\{\ve{S}(t)\}_{t\geq 0}$ on a countable state space $\mathcal{S}$ with generator $G$. Let $r_{ss'}$ denote the transition rate from state $\ve{s}$ to $\ve{s}'$, and let $r(\ve{s}) = -r_{ss}\triangleq\sum_{\ve{s}'\in\mathcal{S},\ve{s}'\neq \ve{s}} r_{ss'}.$ Then for any function $f\colon \mathcal{S}\to\mathbb{R}$, the drift of $f$ is equal to: \begin{equation} G f(\ve{s}) = \sum_{\ve{s}'\in \mathcal{S}} r_{ss'} \left(f(\ve{s}') - f(\ve{s})\right). \end{equation} We assume that $\{\ve{S}(t)\}_{t\geq 0}$ has a stationary distribution and let $\ve{S}(\infty)$ denote a random element that follows the stationary distribution. We give a justification of the frequently used condition: \begin{equation} \mathbb{E}[G f(\ve{S}(\infty))] = 0. \label{eq:bar} \end{equation} Lemma~\ref{lem:bar-master-condition} below, which is a restatement of the Proposition~3 of \cite{GlyZee_08}, gives rigorous conditions under which the relation in \eqref{eq:bar} holds. \begin{lem}\label{lem:bar-master-condition} Consider the Markov chain $\{\ve{S}(t)\}_{t\geq 0}$ and a function $f\colon\mathcal{S}\to\mathbb{R}$. If for all $\ve{s}\in\mathcal{S}$, \begin{equation*} \mathbb{E}[r(\ve{S}(\infty))\cdot\abs{f(\ve{S}(\infty))}] < \infty, \end{equation*} then the relation $\mathbb{E}[G f(\ve{S}(\infty))] = 0$ holds. \end{lem} Lemma~\ref{lem:bar-master-condition} implies that if \begin{gather*} \sup_{\ve{s}\in\mathcal{S}} r(\ve{s}) < \infty,\\ \mathbb{E}[\abs{f(\ve{S}(\infty)}] < \infty, \end{gather*} then the relation $\mathbb{E}[G f(\ve{S}(\infty))] = 0$ holds. Lemma~\ref{lem:hajek} below, which is a continuous-time analogue of a result in \cite{haj_82}, provides some functions $f$ that satisfy $\mathbb{E}[\abs{f(\ve{S}(\infty))}] < \infty$. \begin{lem}\label{lem:hajek} Consider the Markov chain $\{\ve{S}(t)\}_{t\geq 0}$ and let $V:\mathcal{S}\to\mathbb{R}_+$ be a Lyapunov function. Assume that \begin{align*} &\sup_{\ve{s}\in\mathcal{S}} r(\ve{s}) < \infty,\\ &\sup_{\ve{s},\ve{s}'\in\mathcal{S}: r_{ss'} > 0} \abs{V(\ve{s}') - V(\ve{s})} < \infty, \end{align*} and that there exists $\gamma>0$ and $B\geq 0$, such that when $V(\ve{s}) \geq B$, \begin{equation*} G V(\ve{s}) \leq -\gamma. \end{equation*} Then for any positive integer $m$, \begin{equation*} \mathbb{E}[V(\ve{S}(\infty))^m] < \infty. \end{equation*} \end{lem} \subsection{Multiserver-job system}\label{sec:app:drift-cond-msj} We return to the multiserver-job system. For $f\colon\mathbb{R}^I \to \mathbb{R}$, we want to find conditions under which $E[G f(\ve{X},\ve{Z})] = 0$. Recall that \begin{equation} G f(\ve{x}, \ve{z}) = \sum_{i=1}^I \lambda_i \left(f(\ve{x}+ \ve{e}_i) - f(\ve{x})\right)+ \sum_{i=1}^I \sev_i z_i \left(f(\ve{x}-\ve{e}_i) - f(\ve{x})\right), \end{equation} where $\ve{x}, \ve{z}$ are possible realizations of $\ve{X}, \ve{Z}$, $\ve{e}_i \in \mathbb{R}^I$ is the vector whose $i$th entry is $1$ and all the other entries are $0$. Therefore, the transition rate of any multiserver-job system is bounded by $\sev_{\max} n$. By Lemma~\ref{lem:bar-master-condition}, it suffices to have $\mathbb{E}[\abs{f(\ve{X})}] < \infty$. This lemma implies that for any test function $f$ with polynomial increasing rate, the relation $\mathbb{E}[Gf(\ve{X}, \ve{Z})] = 0$ holds. \begin{lem}\label{lem:polynomial-zero-drift} Consider the multiserver-job system with $n$ servers under a $\wst$-work-conserving policy with $\wst \leq \epsilon_0 \delta$, where $\epsilon_0 \in (0,1)$ is the parameter used in Assumption~\ref{assump:lm-bound}. Then for any positive integer $m$, we have \begin{equation} \mathbb{E}\left[\left(\sum_{i=1}^I \frac{\ell_i}{\sev_i}X_i(\infty)\right)^m\right] < \infty. \end{equation} \end{lem} \begin{proof}[Proof of Lemma~\ref{lem:polynomial-zero-drift}] We prove this lemma by applying Lemma~\ref{lem:hajek}. Let $V(\ve{x}) = \sum_{i=1}^I \frac{\ell_i}{\sev_i} x_i$. We first show that the drift $GV(\ve{x},\ve{z})$ is negative when $V(\ve{x})$ is larger than a threshold. Observe that the drift is bounded as \begin{align*} G V(\ve{x},\ve{z}) &= \sum_{i=1}^I \left(\frac{\lambda_i\ell_i}{\sev_i} - \ell_i z_i\right)\\ &\leq \sum_{i=1}^I \frac{\lambda_i\ell_i}{\sev_i} - \min\left(\sum_{i=1}^I \ell_i x_i, n-\wst\right)\\ &\leq -\min\left(\sum_{i=1}^I \ell_i x_i - n + \delta, \delta - \wst\right), \end{align*} where the second inequality is due to the use of $\wst$-work-conserving policy. For any state such that $V(\ve{x}) > n/\sev_{\min} + 1$ where $\sev_{\min} = \min_{i\in[I]} \sev_i$, we have \[ \sum_{i=1}^I \ell_i x_i \geq \sev_{\min} V(\ve{x}) > n, \] so $G V(\ve{x},\ve{z}) < -\delta + \wst \leq -\epsilon_0 \delta < 0$. Moreover, any transition in the system at most changes $V(\ve{x})$ by $\max_i \ell_i/\sev_i$, which is also a finite number. Applying Lemma~\ref{lem:hajek}, we get $\mathbb{E}\left[\left(\sum_{i=1}^I \frac{\ell_i}{\sev_i} X_i\right)^m\right] < \infty$ for any positive integer $m$. \end{proof} \section{State-space concentration by coupling with infinite server systems}\label{sec:mminf-proof} In this section, we prove Lemma~\ref{lem:mminf-bounds}, the state-space concentration result needed in Section~\ref{sec:workload-bounds}. We start by defining a sequence of infinite-server systems. Consider a sequence of systems where each system has an infinite number of servers. For the $n$th system in the sequence, we let it have the same job characteristics as the original $n$-server system; i.e., there are $I$ job types and job type $i\in[I]$ has arrival rate $\lambda_i$, server need $\ell_i$, and service rate $\sev_i$. We refer to this system as the \emph{$n$th infinite-server system}. The $n$th infinite-server system serves as a lower bound system for the original $n$-server system through the following coupling. Let the $n$th infinite-server system have the same arrival sequence as the original $n$-server system; i.e., whenever the $n$-server system has a job arrival, let the infinite-server system have a job arrival with the same server need and service time. Since every job in the infinite-server system enters service immediately upon arrival, the job leaves the infinite-server system no later than the corresponding job does in the original system. Therefore, the infinite-server system always has no more jobs than the $n$-server system. Specifically, let $\sysinf{X}_i(t)$ be the number of type~$i$ jobs in the infinite-server system at time $t$. Recall that $X_i(t)$ denotes the number of type~$i$ jobs in the original $n$-server system. Then by the construction of the coupling, $\sysinf{X}_i(t) \leq X_i(t)$ almost surely for all $t\geq 0$ and $i\in [I]$. Therefore, in steady-state, $\sysinf{X}_i(\infty)$ is stochastically smaller or equal to $X_i(\infty)$, i.e., $\mathbb{P}(\sysinf{X}_i(\infty)\geq x) \leq \mathbb{P}(X_i(\infty) \geq x)$ for any $x\in \mathbb{R}$. We denote this relationship by $\sysinf{X}_i(\infty) \leq_{st} X_i(\infty)$. Next, we restate Lemma~\ref{lem:mminf-bounds} and give it a proof. \mminfbounds* \begin{proof}[Proof of Lemma~\ref{lem:mminf-bounds}] Consider the infinite-server system defined at the beginning of this section. Based on the coupling argument, we have $\sysinf{X}_i(\infty) \leq_{st} X_i(\infty)$ for any $i\in[I]$. We define \[ \sysinf{\Phi} =\sum_{i=1}^I c_i \ell_i\left(\sysinf{X}_i(\infty)-\frac{\lambda_i}{\sev_i}\right). \] Because $c_i \ell_i\geq 0$, we have \begin{equation}\label{eq:app:proof:mminf-yc-coupling} \sysinf{\Phi} \leq_{st} \Phi. \end{equation} Therefore, we can first prove the various lower bounds for $\sysinf{\Phi}$, and then apply \eqref{eq:app:proof:mminf-yc-coupling}. We first prove the bound in (a). Since $\sysinf{X}_i(\infty)$ is the number of jobs in steady-state in a M/M/$\infty$ system with arrival rate $\lambda_i$ and service rate $\sev_i$, $\sysinf{X}_i(\infty)$ follows Poisson$\left(\frac{\lambda_i}{\sev_i}\right)$ distribution by classic results (see e.g., \cite{BolGreMeeTri_06} p.249). By the independence of $\sysinf{X}_i(\infty)$'s, we have \begin{equation*} \mathbb{E}[e^{-t \sysinf{\Phi}}] = \exp\left( \sum_{i=1}^I \frac{\lambda_i}{\sev_i} (e^{-c_i \ell_i t} - 1 + c_i \ell_i t)\right). \end{equation*} We first prove the bound in (a). By Markov inequality, for any $t\ge 0$, \begin{align*} \mathbb{P}\left(\sysinf{\Phi} \leq - K \right) &= \mathbb{P}\left( e^{-t \sysinf{\Phi}} \geq e^{t K}\right)\leq \frac{\mathbb{E}[e^{-t\sysinf{\Phi}}]}{e^{t K}}. \end{align*} To upper-bound $\mathbb{E}[e^{-t\sysinf{\Phi}}]$, observe that $e^{-s} \leq 1-s +\frac{s^2}{2}$ for any $s \geq 0$. Then for any $t \geq 0$, \begin{align*} \mathbb{E}[e^{-t \sysinf{\Phi}}] &= \exp\left( \sum_{i=1}^I \frac{\lambda_i}{\sev_i} \left(e^{-c_i \ell_i t} - 1 + c_i \ell_i t\right)\right)\\ &\le \exp\left( \frac{1}{2} \sum_{i=1}^I \frac{\lambda_i}{\sev_i} \left(c_i \ell_i t\right)^2\right)\\ &= \exp\left(\frac{1}{2}\sum_{i=1}^I c_i^2\sev_i\cdot \frac{\lambda_i\ell_i^2}{\sev_i^2}t^2\right)\\ &\leq \exp\left(\frac{1}{2}c_{\max}^2 \sev_{\max} \sigma^2 t^2\right), \end{align*} where we have used the facts that $c_i^2\le c_{\max}^2$ and $\sev_i \leq \sev_{\max}$ for any $i\in[I]$. Therefore, \begin{align*} \mathbb{P}\left(\sysinf{\Phi} \leq - K \right) &\leq \exp\left(\frac{1}{2} c_{\max}^2 \sev_{\max} \sigma^2 t^2 - K t\right). \end{align*} Take $t = \frac{K}{c_{\max}^2 \sev_{\max} \sigma^2}$, we get \begin{equation} \mathbb{P}\left(\Phi \leq - K \right) \leq \mathbb{P}\left(\sysinf{\Phi} \leq - K \right) \leq \exp\left(-\frac{K^2}{2c_{\max}^2 \sev_{\max} \sigma^2}\right), \end{equation} where we have used $\sysinf{\Phi} \leq_{st} \Phi$ in the first inequality. This proves (a). Next we prove the bound in (b). Let $\alpha$ and $\beta$ be any two non-negative numbers such that $\alpha\beta \geq c_{\max}^2\sev_{\max} \sigma^2$ and let $j\ge 0$. By the bound in (a), setting $K = \alpha + \beta j$ gives \begin{align*} \mathbb{P}\left(\sysinf{\Phi} \leq - \alpha - \beta j \right) &\leq \exp\left(-\frac{\alpha^2 + 2\alpha\beta j + \beta^2 j^2}{2c_{\max}^2 \sev_{\max} \sigma^2}\right)\\ &\leq \exp\left(-\frac{\alpha\beta j}{c_{\max}^2\sev_{\max} \sigma^2}\right)\\ &\le e^{-j}. \end{align*} Because $\sysinf{\Phi} \leq_{st} \Phi$, \[ \mathbb{P}\left(\Phi \leq - \alpha - \beta j \right) \leq e^{-j}. \] This proves (b). To prove the bound on $\mathbb{E}\left[\left(\sysinf{\Phi}\right)^-\right]$ in (c), observe that \begin{equation} \mathbb{E}\left[\left(\sysinf{\Phi}\right)^-\right] \leq \mathbb{E}\left[\abs{\sysinf{\Phi}}\right] \leq \sqrt{\mathbb{E}\left[\left(\sysinf{\Phi}\right)^2\right]}, \end{equation} and \begin{align*} \mathbb{E}\left[\left(\sysinf{\Phi}\right)^2\right] &= \sum_{i=1}^I c_i^2 \ell_i^2\mathbb{E}\left[\left(\sysinf{X}_i(\infty)-\frac{\lambda_i}{\sev_i}\right)^2\right]\\ &=\sum_{i=1}^I c_i^2 \ell_i^2 \frac{\lambda_i}{\sev_i}\\ &\leq c_{\max}^2 \sev_{\max} \sigma^2, \end{align*} where we have used the fact that $\sysinf{X}_i(\infty)$ follows Poisson$\left(\frac{\lambda_i}{\sev_i}\right)$ distribution. Because $s\mapsto s^-$ is a non-increasing function for real number $s$, we have \begin{equation} \mathbb{E}\left[\Phi^-\right]\leq \mathbb{E}\left[\left(\sysinf{\Phi}\right)^-\right] \leq \sqrt{c_{\max}^2 \sev_{\max} \sigma^2}. \end{equation} This finishes the proof of (c). \end{proof} \section{Proofs of the Workload Bounds}\label{sec:app:workload-bounds} In this section, we prove the workload bounds Lemma~\ref{result:workload-lower} and Lemma~\ref{result:workload-upper} in Section~\ref{sec:workload-bounds}. \workloadlower* \begin{proof}[Proof of Lemma~\ref{result:workload-lower}] Recall that we have defined the \textit{normalized work} as \[ \overline{W} \triangleq \sum_{i=1}^I \frac{\ell_i}{\sev_i} \left(X_i - \bar{x}_i\right), \] where we denote $\bar{x}_i \triangleq \frac{\lambda_i}{\sev_i}$ for notational simplicity. We have also shown that normalized work has the same expectation as the workload, i.e., $\mathbb{E}[\overline{W}] = \mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i\right]$. This is because $Q_i = X_i - Z_i$, and $\mathbb{E}[Z_i]=\frac{\lambda_i}{\sev_i}$. Therefore, bounding the expected workload is equivalent to bounding the steady-state expectation of the normalized work $\mathbb{E}[\overline{W}]$. To lower bound $\mathbb{E}[\overline{W}]$, the main step is to use a properly chosen small number $\bar{r}_1$ to decompose it as \begin{equation} \mathbb{E}[\overline{W}] = \bar{r}_1 + \mathbb{E}[(\overline{W}-\bar{r}_1)^+] - \mathbb{E}[(\overline{W}-\bar{r}_1)^-]. \end{equation} We bound the positive part $\mathbb{E}[(\overline{W} - \bar{r}_1)^+]$ and the negative part $\mathbb{E}[(\overline{W} - \bar{r}_1)^-]$ separately using different techniques. We bound $\mathbb{E}[(\overline{W}-\bar{r}_1)^+]$ by analyzing the Lyapunov drift of a function $f\colon \mathbb{R}^I \to \mathbb{R}$ defined below. Let $\ve{x},\ve{z} \in \mathbb{R}^I$ denote possible realizations of the state descriptors $\ve{X}(t), \ve{Z}(t)$. Then $f$ is defined as \begin{equation*} f(\ve{x}) = \varphi_M\left(\fnormwork{\ve{x}} - \bar{r}_1\right) \end{equation*} where $\fnormwork{\ve{x}} \triangleq \sum_{i=1}^I \frac{\ell_i}{\sev_i} (x_i - \bar{x}_i)$ is a possible realization of $\overline{W}$, $M$ is a positive number, and $\varphi_M(s)\colon \mathbb{R} \to \mathbb{R}$ is defined as \[ \varphi_M(s) = \begin{cases} 0 & \text{ if } s \leq 0\\ s^2 & \text{ if } 0 < s \leq M\\ 2Ms - M^2 &\text{ if } s > M \end{cases}. \] The function $\varphi_M(s)$ is continuously differentiable with the derivative given by \[ \varphi_M'(s) = 2\min\left( s^+, M\right). \] The bound on $\mathbb{E}[(\overline{W}-\bar{r}_1)^+]$ relies on the relation $\mathbb{E}[G f(\ve{X}, \ve{Z})] = 0$. Without loss of generality, we can assume $\mathbb{E}[Q_i] < \infty$ for all $i\in [I]$, because otherwise $E[\overline{W}] = \infty$ and we are done. Under this assumption, one can verify that $\mathbb{E}[\abs{f(\ve{X})}] < \infty$. Because multiserver-job system has bounded transition rate, by Lemma~\ref{lem:bar-master-condition}, the relation $\mathbb{E}[G f(\ve{X}, \ve{Z})] = 0$ holds. To utilize this relation, we first decompose the drift $G f(\ve{x},\ve{z})$ formula \eqref{eq:proof:drift-form} in the following way: \begin{equation}\label{eq:app:proof:drift-mean-var-decomp-in-lemma1} \begin{aligned} G f(\ve{x}, \ve{z}) &= \sum_{i=1}^I \left(\lambda_i - \sev_i z_i\right)\frac{\partial f}{\partial x_i}(\ve{x})\\ &\mspace{23mu}+ \sum_{i=1}^I \lambda_i \left(f(\ve{x}+\ve{e}_i) - f(\ve{x}) - \frac{\partial f}{\partial x_i}(\ve{x})\right)+\sum_{i=1}^I\sev_i z_i \left(f(\ve{x}-\ve{e}_i) - f(\ve{x}) + \frac{\partial f}{\partial x_i}(\ve{x})\right). \end{aligned} \end{equation} It is easy to see that \begin{equation*} \frac{\partial f}{\partial x_i}(\ve{x}) = \frac{\partial w}{\partial x_i}(\ve{x}) \varphi_M'\left(\fnormwork{\ve{x}}-\bar{r}_1\right) =\frac{2\ell_i}{\sev_i} \min\left( (\fnormwork{\ve{x}} - \bar{r}_1)^+ , M\right). \end{equation*} The remaining two terms are bounded by constants independent of $\ve{x}$ and $\ve{z}$ in the following way. \begin{align*} f(\ve{x}+\ve{e}_i) - f(\ve{x}) - \frac{\partial f}{\partial x_i}(\ve{x}) &= \int_{\xi \in [\ve{x}, \ve{x}+\ve{e}_i]} \left(\frac{\partial f}{\partial x_i}(\xi) - \frac{\partial f}{\partial x_i}(\ve{x})\right) d\xi\\ &= \frac{\ell_i}{\sev_i} \int_{\xi \in [\ve{x}, \ve{x}+\ve{e}_i]} \left(\varphi_M'\left(\fnormwork{\xi} - \bar{r}_1 \right) - \varphi_M'\left(\fnormwork{\ve{x}} - \bar{r}_1\right)\right) d\xi\\ &\geq \frac{2\ell_i}{\sev_i} \int_{\xi \in [\ve{x}, \ve{x}+\ve{e}_i]} \left(\fnormwork{\xi} - \fnormwork{\ve{x}}\right) d\xi \cdot\indibrac{ \bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}<\fnormwork{\ve{x}} < \bar{r}_1 + M - \frac{\ell_{\max}}{\sev_{\min}}}\\ &= \frac{\ell_i^2}{\sev_i^2} \cdot\indibrac{ \bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}<\fnormwork{\ve{x}} < \bar{r}_1 + M - \frac{\ell_{\max}}{\sev_{\min}}}, \end{align*} where the inequality is due to the fact that for any $s_1 \geq s_2$, \begin{equation} \varphi'_M(s_1) - \varphi'_M(s_2) \geq 2(s_1 - s_2) \cdot \indibrac{\bar{r}_1 \leq s_2\leq s_1 \leq \bar{r}_1 + M}, \end{equation} which can be verified by brutal force calculation. Similarly, \begin{align*} f(\ve{x} - \ve{e}_i) - f(\ve{x}) + \frac{\partial f}{\partial x_i}(\ve{x}) &= \int_{\xi \in [\ve{x}-\ve{e}_i, \ve{x}]} \left(-\frac{\partial f}{\partial x_i}(\xi) + \frac{\partial f}{\partial x_i}(\ve{x})\right) d\xi\\ &= \frac{\ell_i}{\sev_i} \int_{\xi \in [\ve{x}-\ve{e}_i, \ve{x}]} \left(-\varphi_M'\left(\fnormwork{\xi} - \bar{r}_1 \right) + \varphi_M'\left(\fnormwork{\ve{x}} - \bar{r}_1\right)\right) d\xi\\ &\geq \frac{2\ell_i}{\sev_i} \int_{\xi \in [\ve{x}-\ve{e}_i, \ve{x}]} \left(-\fnormwork{\xi} + \fnormwork{\ve{x}}\right) d\xi \cdot\indibrac{ \bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}<\fnormwork{\ve{x}} < \bar{r}_1 + M - \frac{\ell_{\max}}{\sev_{\min}}}\\ &= \frac{\ell_i^2}{\sev_i^2} \cdot\indibrac{ \bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}<\fnormwork{\ve{x}} < \bar{r}_1 + M - \frac{\ell_{\max}}{\sev_{\min}}}\\ &\geq \frac{\ell_i^2}{\sev_i^2}\indibrac{ \bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}<\fnormwork{\ve{x}} < \bar{r}_1 + M - \frac{\ell_{\max}}{\sev_{\min}}}. \end{align*} Plugging in the inequalities above back to the decomposition of the drift \eqref{eq:app:proof:drift-mean-var-decomp-in-lemma1} and taking expectation on both sides, because $G f(\ve{X},\ve{Z}) = 0$, we have \begin{equation} \begin{aligned} 0 &\geq \mathbb{E}\left[ \sum_{i=1}^I \ell_i \left(\bar{x}_i - Z_i\right)\cdot 2\min\left( (\overline{W} - \bar{r}_1)^+ , M\right) + \sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \indibrac{ \bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}<\overline{W} < \bar{r}_1 + M - \frac{\ell_{\max}}{\sev_{\min}}}\right]. \end{aligned} \end{equation} Taking limit $M\to\infty$, we have \begin{equation} 0 \geq \mathbb{E}\left[ \sum_{i=1}^I \ell_i \left(\bar{x}_i - Z_i\right)\cdot 2(\overline{W}-\bar{r}_1)^+ + \sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \indibrac{\overline{W}>\bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}}\right]. \end{equation} Here taking the limit on $M$ is legal because the random variable in the expectation is dominated by a random variable $ 2n\ell_{\max}(\overline{W}-\bar{r}_1)^+ + 2n\ell_{\max} / \sev_{\min}$ with finite expectation, and we can apply the dominated convergence theorem. Observe that $ \sum_{i=1}^I \ell_i \left(\bar{x}_i - Z_i\right) \geq -\delta$, after rearranging the terms, we have \begin{equation}\label{eq:app:proof:positive-part-lower-bound} \mathbb{E}\left[(\overline{W}-\bar{r}_1)^+ \right] \geq \frac{1}{2\delta} \mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \indibrac{\overline{W}>\bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}}\right]. \end{equation} Next, we pick a proper $\bar{r}_1$ so that $\mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \indibrac{\overline{W}>\bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}}\right]$ can be lower bounded. Observe that $\mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \right] = 2\sigma^2$ because $\mathbb{E}[Z_i] = \frac{\lambda_i}{\sev_i}$, and $\sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \leq \frac{2n\ell_{\max}}{\sev_{\min}}$. Therefore, \begin{equation} \mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \indibrac{\overline{W}>\bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}}\right] \geq 2\sigma^2 -\frac{2n\ell_{\max}}{\sev_{\min}} \cdot \mathbb{P}\left(\overline{W}\leq\bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}\right) \end{equation} Consider Lemma~\ref{lem:mminf-bounds} with $\Phi= \overline{W}$, $c_i = \frac{1}{\sev_i}$, $K = K_1\triangleq 2\sqrt{\sev_{\max} \sigma^2 \log n} / \sev_{\min} $. Then we have \begin{align*} \mathbb{P}\left(\overline{W} \leq -K_1 \right) \leq \frac{1}{n^2}. \end{align*} Note that this choice of $K_1$ yields $K_1= \Obrac{\sqrt{\sigma^2}\log n}$. Take $\bar{r}_1 = - K_1 - \frac{\ell_{\max}}{\sev_{\min}}$, then $\mathbb{P}\left(\overline{W} \leq \bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}} \right) \leq \frac{1}{n^2}$, so \begin{equation} \mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \indibrac{\overline{W}>\bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}}\right] \geq 2\sigma^2 \cdot (1-o(1)). \end{equation} Combining with \eqref{eq:app:proof:positive-part-lower-bound}, we get \begin{equation} \mathbb{E}\left[(\overline{W}-\bar{r}_1)^+ \right] \geq \frac{\sigma^2}{\delta}\cdot (1-o(1)). \end{equation} The lower bound for negative part $\mathbb{E}[(\overline{W}-\bar{r}_1)^-]$ follows from Lemma~\ref{lem:mminf-bounds}, which says that $E[(\overline{W})^-] = \Obrac{\sqrt{\sigma^2}}$. Because $s\mapsto s^-$ is a monotonically decreasing function, and $\bar{r}_1 \leq 0$, \begin{equation} \mathbb{E}[(\overline{W}-\bar{r}_1)^-] \leq \mathbb{E}[(\overline{W})^-] = \Obrac{\sqrt{\sigma^2}}. \end{equation} Therefore, \begin{align} \mathbb{E}[\overline{W}] &= \bar{r}_1 + \mathbb{E}[(\overline{W}-\bar{r}_1)^+] - \mathbb{E}[(\overline{W}-\bar{r}_1)^-] \\ &\geq K_1 + \frac{\ell_{\max}}{\sev_{\min}} +\frac{\sigma^2}{\delta}\cdot (1-o(1)) - \Obrac{\sqrt{\sigma^2}}\\ &= \frac{\sigma^2}{\delta}\cdot (1-o(1)). \end{align} In the last equality, we have used the fact that $K_1 = \Obrac{\sqrt{\sigma^2}\log n}$, $\ell_{\max} = \obrac{\sqrt{\sigma^2}/ \log n}$, and $\frac{\sigma^2}{\delta} = \wbrac{\sqrt{\sigma^2} \log n}$. This finishes the proof of Lemma~\ref{result:workload-lower}. \end{proof} \workloadupper* \begin{proof}[Proof of Lemma~\ref{result:workload-upper}] Recall that we have defined the \textit{normalized work} as \[ \overline{W} \triangleq \sum_{i=1}^I \frac{\ell_i}{\sev_i} \left(X_i - \bar{x}_i\right), \] where we denote $\bar{x}_i \triangleq \frac{\lambda_i}{\sev_i}$ for notational simplicity. We have also shown that normalized work has the same expectation as the workload, i.e., $\mathbb{E}[\overline{W}] = \mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i\right]$. This is because $Q_i = X_i - Z_i$, and $\mathbb{E}[Z_i]=\frac{\lambda_i}{\sev_i}$. Therefore, bounding the expected workload is equivalent to bounding the steady-state expectation of the normalized work $\mathbb{E}[\overline{W}]$. To bound $\mathbb{E}[\overline{W}]$, we choose a suitable $\bar{r}_2$ and decompose $\mathbb{E}[\overline{W}]$ as follows: \begin{equation} \mathbb{E}[\overline{W}] = \bar{r}_2 + \mathbb{E}[(\overline{W}-\bar{r}_2)^+] - \mathbb{E}[(\overline{W}-\bar{r}_2)^-] \leq \bar{r}_2 + \mathbb{E}[(\overline{W}-\bar{r}_2)^+]. \end{equation} We bound $\mathbb{E}[(\overline{W}-\bar{r}_2)^+]$ by analyzing the Lyapunov drift of a function $f\colon \mathbb{R}^I \to \mathbb{R}$ defined below. Let $\ve{x},\ve{z} \in \mathbb{R}^I$ denote possible realizations of the state descriptors $\ve{X}(t), \ve{Z}(t)$. Then $f$ is defined as \begin{equation*} f(\ve{x}) = \varphi\left(\fnormwork{\ve{x}} - \bar{r}_2\right) \end{equation*} where $\fnormwork{\ve{x}} \triangleq \sum_{i=1}^I \frac{\ell_i}{\sev_i} (x_i - \bar{x}_i)$ is a possible realization of $\overline{W}$, $\varphi(s) = \left(s^+\right)^2$. This proof relies on the relation that $\mathbb{E}[G f(\ve{X}, \ve{Z})] = 0$, which is true by Lemma~\ref{lem:polynomial-zero-drift}. To utilize this relation, we first decompose the drift $G f(\ve{x},\ve{z})$ formula \eqref{eq:proof:drift-form} in the following way: \begin{equation}\label{eq:app:proof:drift-mean-var-decomp} \begin{aligned} G f(\ve{x}, \ve{z}) &= \sum_{i=1}^I \left(\lambda_i - \sev_i z_i\right)\frac{\partial f}{\partial x_i}(\ve{x})\\ &\mspace{23mu}+ \sum_{i=1}^I \lambda_i \left(f(\ve{x}+\ve{e}_i) - f(\ve{x}) - \frac{\partial f}{\partial x_i}(\ve{x})\right)+\sum_{i=1}^I\sev_i z_i \left(f(\ve{x}-\ve{e}_i) - f(\ve{x}) + \frac{\partial f}{\partial x_i}(\ve{x})\right). \end{aligned} \end{equation} It is easy to see that \begin{equation*} \frac{\partial f}{\partial x_i}(\ve{x}) = \frac{\partial r}{\partial x_i}(\ve{x}) \varphi'\left(\fnormwork{\ve{x}} - \bar{r}_2\right) =\frac{2\ell_i}{\sev_i} (\fnormwork{\ve{x}} - \bar{r}_2)^+. \end{equation*} The remaining two terms are bounded by constants independent of $\ve{x}$ and $\ve{z}$ in the following way. \begin{align* f(\ve{x}+\ve{e}_i) - f(\ve{x}) - \frac{\partial f}{\partial x_i}(\ve{x}) &= \int_{\xi \in [\ve{x}, \ve{x}+\ve{e}_i]} \left(\frac{\partial f}{\partial x_i}(\xi) - \frac{\partial f}{\partial x_i}(\ve{x})\right) d\xi\\ &= \frac{\ell_i}{\sev_i} \int_{\xi \in [\ve{x}, \ve{x}+\ve{e}_i]} \left(\varphi'\left(\fnormwork{\xi}-\bar{r}_2\right) - \varphi'\left(\fnormwork{\ve{x}}-\bar{r}_2\right)\right) d\xi\\ &\leq \frac{2\ell_i}{\sev_i} \int_{\xi \in [\ve{x}, \ve{x}+\ve{e}_i]} \left(\fnormwork{\xi} - \fnormwork{\ve{x}}\right) d\xi \cdot\indibrac{\fnormwork{\ve{x}} > \bar{r}_2 - \frac{\ell_{\max}}{\sev_{\min}}}\\ &= \frac{\ell_i^2}{\sev_i^2} \cdot\indibrac{\fnormwork{\ve{x}} > \bar{r}_2 - \frac{\ell_{\max}}{\sev_{\min}}}, \end{align*} where the inequality is because $\varphi'(s) = 2s^+$ is $2$-Lipschitz continuous, and equal to $0$ when $s\leq \bar{r}_2$. Similarly, \begin{equation* f(\ve{x} - \ve{e}_i) - f(\ve{x}) + \frac{\partial f}{\partial x_i}(\ve{x}) \leq \frac{\ell_i^2}{\sev_i^2}\mathbb{1}_{\{\fnormwork{\ve{x}} > \bar{r}_2 - \frac{\ell_{\max}}{\sev_{\min}}\}}. \end{equation*} Plugging in the inequalities above back to the decomposition of the drift \eqref{eq:app:proof:drift-mean-var-decomp} and taking expectation on both sides, because $G f(\ve{X},\ve{Z}) = 0$, we have \begin{equation} \begin{aligned} 0 &\leq \mathbb{E}\left[ \sum_{i=1}^I \ell_i \left(\bar{x}_i - Z_i\right)\cdot 2(\overline{W}-\bar{r}_2)^+\right]+ \mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \mathbb{1}_{\left\{\overline{W}>\bar{r}_2 - \frac{\ell_{\max}}{\sev_{\min}}\right\}}\right]. \end{aligned} \end{equation} Observe that the second term can be straightforwardly bounded as follows \begin{align} \mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i\ell_i^2}{\sev_i}\right) \mathbb{1}_{\left\{\overline{W}>\bar{r}_2 - \frac{\ell_{\max}}{\sev_{\min}}\right\}}\right] & \leq \mathbb{E} \left[\sum_{i=1}^I \left(\frac{\lambda_i \ell_i^2}{\sev_i^2} + \frac{Z_i \ell_i^2}{\sev_i}\right)\right] \nonumber\\ & = 2\sum_{i=1}^I \frac{\lambda_i\ell_i^2}{\sev_i^2} = 2\sigma^2. \end{align} where the first equality is due to $\mathbb{E}[Z_i] = \frac{\lambda_i}{\sev_i}$. Rearranging the terms, we get the key equation \begin{equation}\label{eq:app:proof:bd1:mean-var-terms} \mathbb{E}\left[ \sum_{i=1}^I \ell_i \left(Z_i - \bar{x}_i\right)\cdot (\overline{W}-\bar{r}_2)^+\right] \leq \sigma^2 \end{equation} Suppose we are able to show that \begin{equation}\label{eq:app:proof:drift-goal} \mathbb{E}\left[ \sum_{i=1}^I \ell_i \left(Z_i - \bar{x}_i\right) \cdot (\overline{W}-\bar{r}_2)^+ \right] \geq \gamma \cdot \mathbb{E}\left[ (\overline{W}-\bar{r}_2)^+\right] - o(1), \end{equation} for some $\gamma > 0$, then by \eqref{eq:app:proof:bd1:mean-var-terms}, $\mathbb{E}\left[ (\overline{W}-\bar{r}_2)^+\right] \leq \frac{\sigma^2 + o(1)}{\gamma}$, so $\mathbb{E}[\overline{W}] \leq \bar{r}_2 + \frac{\sigma^2 +o(1)}{\gamma}$. We devote the remainder of this proof to proving \eqref{eq:app:proof:drift-goal}. The idea here is to use the following two events to further partition the probability space \begin{align*} \mathcal{E}_1 = \left\{\sum_{i=1}^I \left(\tfrac{1}{\sev_{\min}} - \tfrac{1}{\sev_i} \right)\ell_i(X_i - \bar{x}_i) > -K_2\right\}, \quad \mathcal{E}_2 = \left\{\overline{W} \leq \frac{n}{\sev_{\min}}\right\}, \end{align*} where $K_2$ is a suitable number such that $\mathcal{E}_1$ happens with high probability. We break the term on the left of \eqref{eq:app:proof:bd1:mean-var-terms} into three terms based on events $\mathcal{E}_1$ and $\mathcal{E}_2$: \begin{align} \mathbb{E}\left[ \sum_{i=1}^I \ell_i\left(Z_i - \bar{x}_i\right)\cdot (\overline{W}-\bar{r}_2)^+\right] &= \mathbb{E}\left[ \sum_{i=1}^I \ell_i\left(Z_i - \bar{x}_i\right)\cdot (\overline{W}-\bar{r}_2)^+ \mathbb{1}_{\{\overline{W}>\bar{r}_2, \mathcal{E}_1\}} \right]\label{eq:app:proof:bd1:indicator-decomp1}\\ &\mspace{5mu}+ \mathbb{E}\left[\sum_{i=1}^I \ell_i\left(Z_i - \bar{x}_i\right)\cdot (\overline{W}-\bar{r}_2)^+\mathbb{1}_{\{\overline{W}>\bar{r}_2,\mathcal{E}_1^c,\mathcal{E}_2\}}\right]\label{eq:app:proof:bd1:indicator-decomp2} \\ &\mspace{5mu}+ \mathbb{E}\left[\sum_{i=1}^I \ell_i\left(Z_i - \bar{x}_i\right)\cdot (\overline{W}-\bar{r}_2)^+\mathbb{1}_{\left\{\overline{W}>\bar{r}_2,\mathcal{E}_1^c, \mathcal{E}_2^c\right\}}\right]\label{eq:app:proof:bd1:indicator-decomp3}. \end{align} Next we deal with the three terms in \eqref{eq:app:proof:bd1:indicator-decomp1} \eqref{eq:app:proof:bd1:indicator-decomp2} \eqref{eq:app:proof:bd1:indicator-decomp3} separately, i.e., we consider three cases: $\mathcal{E}_1$, $\mathcal{E}_1^c \cap \mathcal{E}_2$ and $\mathcal{E}_1^c \cap \mathcal{E}_2^c$. \textbf{Case 1: $\mathcal{E}_1$ happens} Observe that the term in \eqref{eq:app:proof:bd1:indicator-decomp1} is non-zero only when $\overline{W} >\bar{r}_2$ and event $\mathcal{E}_1$ happens, which implies \begin{equation*} \sum_{i=1}^I \frac{\ell_i}{\mu_i} (X_i - \bar{x}_i) > \bar{r}_2, \end{equation*} \begin{equation*} \sum_{i=1}^I \left(\tfrac{1}{\sev_{\min}} - \tfrac{1}{\sev_i} \right)\ell_i(X_i - \bar{x}_i) > - K_2. \end{equation*} Adding up the above two inequalities and rearranging the terms yield \begin{equation} \sum_{i=1}^I \ell_i(X_i - \bar{x}_i) > \sev_{\min} (\bar{r}_2 - K_2). \end{equation} This gives a bound on the following factor in \eqref{eq:app:proof:bd1:indicator-decomp1} \begin{equation} \begin{aligned} \sum_{i=1}^I \ell_i\left(Z_i - \bar{x}_i\right) &\geq \min\left(\sum_{i=1}^I \ell_i X_i, n-\wst\right) - \sum_{i=1}^I\ell_i\bar{x}_i \\ &= \min\left(\sum_{i=1}^I \ell_i(X_i - \bar{x}_i), n-\wst - \sum_{i=1}^I\ell_i\bar{x}_i\right)\\ &\geq \min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta - \wst\right) \end{aligned} \end{equation} where the first inequality is due to the use of a $\wst$-work-conserving policy, the second inequality used the fact that $\sum_{i=1}^I \ell_i \bar{x}_i = n-\delta$. Therefore, \begin{equation} \begin{aligned} \mathbb{E}\left[ \sum_{i=1}^I \ell_i\left(Z_i - \bar{x}_i \right)\cdot (\overline{W}-\bar{r}_2)^+ \mathbb{1}_{\left\{\overline{W} > \bar{r}_2,\mathcal{E}_1\right\}}\right]\geq \min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta - \wst\right)\cdot\mathbb{E}\left[\left(\overline{W} - \bar{r}_2\right)^+\mathbb{1}_{\left\{\overline{W} > \bar{r}_2,\mathcal{E}_1\right\}}\right] . \end{aligned}\label{eq:app:proof:bd1:drift-part1} \end{equation} \textbf{Case 2: $\mathcal{E}_1^c \cap \mathcal{E}_2$ happens} To bound the term in \eqref{eq:app:proof:bd1:indicator-decomp2}, we need to analyze the probability of event $\mathcal{E}_1^c$. Consider Lemma~\ref{lem:mminf-bounds} with $\Phi= \sum_{i=1}^I \left(\frac{1}{\sev_{\min}} - \frac{1}{\sev_i} \right)\ell_i(X_i - \bar{x}_i)$, $c_i = \frac{1}{\sev_{\min}} - \frac{1}{\sev_i}$, $\alpha = \beta= \sqrt{\frac{\sev_{\max}}{\sev_{\min}^2}\sigma^2}$, $j=3\log n$. It can be verified that $\alpha\beta \geq c_{\max}^2\sev_{\max}\sigma^2$. Let $K_2=\alpha+\beta j$. Then we have \begin{align*} \mathbb{P}\left(\mathcal{E}_1^c\right)=\mathbb{P}\left(\sum_{i=1}^I \left(\tfrac{1}{\sev_{\min}} - \tfrac{1}{\sev_i} \right)\ell_i(X_i - \bar{x}_i) \leq -K_2 \right)\le \frac{1}{n^3}. \end{align*} Note that this choice of $K_2$ yields $K_2= O(\sqrt{\sigma^2}\log n)$. With the upper bound $\mathbb{P}\left(\mathcal{E}_1^c\right)\le\frac{1}{n^3}$, we bound the term in \eqref{eq:app:proof:bd1:indicator-decomp2} in the following way. Observe that $\sum_{i=1}^I\ell_i(Z_i - \bar{x}_i) \geq -n$. Further, when the event $\mathcal{E}_2$ occurs, $\overline{W}\le\frac{n}{\sev_{\min}}$, thus $0 \leq (\overline{W}-\bar{r}_2)^+\le\frac{n}{\sev_{\min}}$. Therefore, \begin{equation*} \mspace{23mu}\mathbb{E}\left[\sum_{i=1}^I\ell_i(Z_i - \bar{x}_i)\cdot(\overline{W} - \bar{r}_2)^+\mathbb{1}_{\left\{\overline{W} > \bar{r}_2, \mathcal{E}_1^c, \mathcal{E}_2\right\}}\right] \geq -n\cdot \frac{n}{\sev_{\min}}\cdot \mathbb{P}\left(\mathcal{E}_1^c\right) \geq -\frac{1}{\sev_{\min} n}, \end{equation*} \begin{equation*} \mspace{23mu}\mathbb{E}\left[(\overline{W} - \bar{r}_2)^+ \mathbb{1}_{\left\{\overline{W} > \bar{r}_2, \mathcal{E}_1^c, \mathcal{E}_2\right\}}\right] \leq \frac{n}{\sev_{\min}}\cdot \mathbb{P}\left(\mathcal{E}_1^c\right) \leq \frac{1}{\sev_{\min} n^2}. \end{equation*} Combining the above two inequalities yields \begin{equation}\label{eq:app:proof:bd1:drift-part2} \begin{aligned} &\mspace{23mu}\mathbb{E}\left[\sum_{i=1}^I\ell_i(Z_i - \bar{x}_i)\cdot(\overline{W} - \bar{r}_2)^+\mathbb{1}_{\left\{\overline{W} > \bar{r}_2, \mathcal{E}_1^c, \mathcal{E}_2\right\}}\right]\\ &\geq \min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta - \wst\right) \cdot \mathbb{E}\left[(\overline{W} - \bar{r}_2)^+ \mathbb{1}_{\left\{\overline{W} > \bar{r}_2, \mathcal{E}_1^c, \mathcal{E}_2\right\}}\right] - \frac{n+\delta}{\sev_{\min} n^2}, \end{aligned} \end{equation} where we have used the fact that $\min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta - \wst\right) \leq \delta$. \textbf{Case 3: $\mathcal{E}_1^c \cap \mathcal{E}_2^c$ happens} Lastly, we bound the term in (\ref{eq:app:proof:bd1:indicator-decomp3}). Observe that when the event $\mathcal{E}_2^c$ occurs, $\sum_{i=1}^I \ell_i X_i \geq n$. By the definition of $\wst'$-work-conserving policy, $\sum_{i=1}^I \ell_i Z_i \geq n-\wst$. Therefore, \begin{equation}\label{eq:app:proof:bd1:drift-part3} \begin{aligned} \mspace{23mu}\mathbb{E}\left[\sum_{i=1}^I\ell_i(Z_i - \bar{x}_i)\cdot(\overline{W} - \bar{r}_2)^+\mathbb{1}_{\left\{\overline{W} > \bar{r}_2, \mathcal{E}_1^c, \mathcal{E}_2^c\right\}}\right] \geq (\delta - \wst)\cdot\mathbb{E}\left[ (\overline{W} - \bar{r}_2)^+\mathbb{1}_{\left\{\overline{W} > \bar{r}_2, \mathcal{E}_1^c, \mathcal{E}_2^c\right\}}\right] \end{aligned} \end{equation} Combining the three cases \eqref{eq:app:proof:bd1:drift-part1} \eqref{eq:app:proof:bd1:drift-part2} \eqref{eq:app:proof:bd1:drift-part3}, we have \begin{equation} \mathbb{E}\left[ \sum_{i=1}^I \ell_i \left(Z_i - \bar{x}_i\right) \cdot (\overline{W}-\bar{r}_2)^+ \right] \geq \min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta - \wst\right) \cdot \mathbb{E}\left[ (\overline{W}-\bar{r}_2)^+\right] - \frac{n+\delta}{\sev_{\min} n^2}. \end{equation} Therefore, we have shown \eqref{eq:app:proof:drift-goal} with $\gamma = \min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta - \wst\right)$. By \eqref{eq:app:proof:bd1:mean-var-terms}, we conclude that \begin{equation} \begin{aligned} \mathbb{E}[\overline{W}] &\leq \bar{r}_2 + \mathbb{E}\left[(\overline{W} - \bar{r}_2)^+\right] \\ &\leq \bar{r}_2 + \frac{\sigma^2}{\min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta - \wst\right)} + O\left(\frac{1}{n}\right). \end{aligned} \end{equation} When $\delta= \obrac{\sqrt{\sigma^2} / \log n}$, taking $\bar{r}_2 = K_2 + (\delta - \delta')/\sev_{\min}$, we have \begin{align} \mathbb{E}[\overline{W}] &\leq K_2 + \frac{\delta - \delta'}{\sev_{\min}} + \frac{\sigma^2}{\delta - \wst} + \Obrac{\frac{1}{n}} \nonumber\\ &= \frac{\sigma^2}{\delta - \wst} \cdot \left(1 + o(1)\right),\nonumber \end{align} where we have used the fact that $K_2 = O(\sqrt{\sigma^2}\log n)$ and $\delta = o\left(\sqrt{\sigma^2}/\log n\right)$. When $\delta= \Wbrac{\sqrt{\sigma^2} / \log n}$, we have $\delta \geq C \sqrt{\sigma^2}/\log n$ for some $C > 0$ and $n$ large enough. Because $\delta - \wst \geq \epsilon_0 \delta$, we get $\delta - \wst \geq \epsilon_0 C \sqrt{\sigma^2}/\log n$ for $n$ large enough. Taking $\bar{r}_2 = K_2 + \epsilon_0 C \sqrt{\sigma^2}/(\sev_{\min}\log n)$ yields $\min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta - \wst\right) \geq \epsilon_0 C \sqrt{\sigma^2}/\log n$, so \begin{align*} \mathbb{E}[\overline{W}] &\leq K_2 + \frac{\epsilon_0 C \sqrt{\sigma^2}}{\sev_{\min} \log n} + \frac{\sqrt{\sigma^2}\log n}{\epsilon_0 C} + \Obrac{\frac{1}{n}}\\ &= \Obrac{\sqrt{\sigma^2}\log n}. \end{align*} This finishes the proof. \end{proof} \section{Proof of Theorem~\ref{result:waiting-time-fcfs} (waiting time under FCFS)}\label{sec:app:fcfs} In this section, we prove Theorem~\ref{result:waiting-time-fcfs}. We first state two lemmas Lemma~\ref{lem:fcfs:sandwich} and Lemma~\ref{lem:fcfs:independence}. Then we prove the theorem using the two lemmas. Finally we give the proofs of the two lemmas. As sketched in Section~\ref{sec:proof:fcfs}, the proof proceeds by constructing upper and lower bounding systems using a \textit{Modified-FCFS} policy. Specifically, Modified-FCFS serves the jobs in a FCFS order, but it will not serve the next job until there are at least $\ell_{\max}$ idle servers. We define the upper bounding system as the multiserver-job system with $n$ servers under Modified-FCFS; we let the lower bounding system be the multiserver-job system with $(n+\ell_{\max})$ servers under Modified-FCFS. To distinguish between the three systems, we add superscripts $^{(U)}$ to the quantities corresponding to the upper bounding system, and superscripts $^{(L)}$ to the quantities corresponding to the lower bounding system. Let $\sysup{Q}_i(t)$ and $\syslow{Q}_i(t)$ denote the queue lengths of type $i$ jobs in the upper bounding system and in the lower bounding system, respectively, and let $\sysup{Q}_{\Sigma}(t) = \sum_{i=1}^I \sysup{Q}_i(t)$ and $\syslow{Q}_{\Sigma}(t) = \sum_{i=1}^I \syslow{Q}_i(t)$ be the total queue lengths. Now we are ready to state the lemmas. Lemma~\ref{lem:fcfs:sandwich} below shows that the queue length of each type of jobs in the original system is bounded between the queue lengths in the upper bounding system and the lower bounding system. Lemma~\ref{lem:fcfs:independence} proves that under Modified-FCFS, the number of type $i$ jobs in the queue is proportional to the arrival rate $\lambda_i$. \begin{restatable}{lem}{fcfssandwich}\label{lem:fcfs:sandwich} \begin{equation} \mathbb{E}[\syslow{Q}_i(\infty)] \leq \mathbb{E}\left[Q_i(\infty)\right] \leq \mathbb{E}[\sysup{Q}_i(\infty)] \quad \forall i\in [I]. \end{equation} \end{restatable} \begin{restatable}{lem}{fcfsindependence}\label{lem:fcfs:independence} For both the upper bounding system and the lower bounding system, we have \begin{align} \mathbb{E}[\sysup{Q}_i(\infty)] &= \frac{\lambda_i}{\lambda}\mathbb{E}[ \sysup{Q}_{\Sigma}(\infty) ],\quad \forall i\in [I], \label{eq:proof:system2:queue-fraction}\\ \mathbb{E}[\syslow{Q}_i(\infty)] &= \frac{\lambda_i}{\lambda}\mathbb{E}[ \syslow{Q}_{\Sigma}(\infty) ],\quad \forall i\in [I].\label{eq:proof:system3:queue-fraction} \end{align} \end{restatable} With the lemmas stated, we are ready to prove Theorem~\ref{result:waiting-time-fcfs}: \begin{proof}[Proof of Theorem~\ref{result:waiting-time-fcfs}] We omit the superscript $^{\textrm{FCFS}}$ in this proof. Recall that by Little's law, $\mathbb{E}\big[T^w_i\big] = \frac{1}{\lambda_i} \mathbb{E}[Q_i]$ and $\mathbb{E}\big[T^w\big] = \frac{1}{\lambda} \sum_{i=1}^I \mathbb{E}[Q_i]$. Then by Lemma~\ref{lem:fcfs:sandwich}, in order to bound $\mathbb{E}[Q_i]$, we only need to give a lower bound on the queue length in the lower bounding system $\mathbb{E}[\syslow{Q}_i]$ and give an upper bound on the queue length in the upper bounding system $\mathbb{E}[\sysup{Q}_i]$, for each $i\in[I]$. Observe that the lower bounding system has $n+\ell_{\max}$ servers, with slack capacity $\delta+\ell_{\max}$. Because $\delta + \ell_{\max} \leq 2\delta = \obrac{\sqrt{\sigma^2} / \log n}$, we can apply the workload lower bound in Lemma~\ref{result:workload-lower} to get \begin{equation*} \sum_{i=1}^I \frac{\ell_i}{\sev_i} \mathbb{E}[\syslow{Q}_i] \geq \frac{\sigma^2}{\delta+\ell_{\max}} \cdot (1-o(1)). \end{equation*} By Lemma~\ref{lem:fcfs:independence}, this means \[ \frac{1}{\lambda} \mathbb{E}[\syslow{Q}_{\Sigma}]\cdot\sum_{i=1}^I \frac{\lambda_i \ell_i}{\sev_i} \geq \frac{\sigma^2}{\delta+\ell_{\max}} \cdot (1-o(1)). \] Because $\sum_{i=1}^I \frac{\lambda_i \ell_i}{\sev_i} = n-\delta = n\cdot (1-o(1))$, we apply Lemma~\ref{lem:fcfs:independence} again to get \begin{equation} \mathbb{E}[\syslow{Q}_i] \geq \frac{\lambda_i\sigma^2}{n(\delta+\ell_{\max})} \cdot (1-o(1)) \quad \forall i\in[I]. \end{equation} For the upper bounding system, observe that it has $n$ server and slack capacity $\delta$, and operates under a $\ell_{\max}$-work-conserving policy. Applying the workload upper bound Lemma~\ref{result:workload-upper} yields \begin{equation*} \frac{1}{\lambda} \sum_{i=1}^I \frac{ \ell_i}{\sev_i} \mathbb{E}[\sysup{Q}_i] \leq \frac{\sigma^2}{\delta-\ell_{\max}} \cdot (1+o(1)). \end{equation*} Following a similar argument as in lower bounding system, we have \begin{equation} \mathbb{E}[\sysup{Q}_i] \leq \frac{\lambda_i \sigma^2}{n(\delta-\ell_{\max})}\cdot (1+o(1)) \quad \forall i\in[I]. \end{equation} Therefore, by Lemma~\ref{lem:fcfs:sandwich}, we have \begin{equation} \frac{\lambda_i\sigma^2}{n(\delta+\ell_{\max})} \cdot (1-o(1)) \leq \mathbb{E}[Q_i] \leq \frac{\lambda_i \sigma^2}{n(\delta-\ell_{\max})}\cdot (1+o(1)) \quad \forall i\in[I], \end{equation} which implies the waiting time bounds in Lemma~\ref{result:waiting-time-fcfs}. \end{proof} The lemmas are proved using some sample path coupling arguments. We first give a construction of the sample paths of a multiserver-job system. We index all the jobs by their order of arriving to the system. Let $A_0(k)$, $S_0(k)$, $C(k)$ be three sequences of independent random variables, where $A_0(k)$ is job $k$'s inter-arrival time following $\exp(\lambda)$ distribution, $S_0(k)$ is a random seed for job $k$'s service time following $\exp(1)$, $C(k)$ is the job $k$'s type. Based on the primitive stochastic elements, we can define the arrival time $A(k) = \sum_{j=1}^k A_0(k)$, service time $S(k) = S_0(k) / \sev_{C(k)}$ and server need $L(k) = \ell_{C(k)}$. Now the arrival process, service time, and server need distributions conform with the definition in our model section. Given the realization of these random variables, we can simulate the system dynamic under FCFS or Modified-FCFS given those quantities. Let job $k$'s waiting time be $W(k)$, then the job $k$ starts its service at time $A(k)+W(k)$ and leaves the system at $A(k)+W(k)+S(k)$, occupying $L(k)$ servers during the time interval. To distinguish between the three systems mentioned above, we add superscripts (U) to the quantities corresponding to the upper bounding system, and superscripts (L) to the quantities corresponding to the lower bounding system. We couple the sample paths of the original system, the upper bounding system, and the lower bounding system by making them share the same realization of primitive stochastic elements. Then $A(k) = \sysup{A}(k) = \syslow{A}(k)$, $S(k) = \sysup{S}(k) = \syslow{S}(k)$, $L(k) = \sysup{L}(k) = \syslow{L}(k)$ for all $k$.\\ Now we are ready to prove Lemma~\ref{lem:fcfs:sandwich} and Lemma~\ref{lem:fcfs:independence}: \begin{proof}[Proof of Lemma~\ref{lem:fcfs:sandwich}]: We prove by induction on $k$ that \begin{equation} W(k) \leq \sysup{W}(k) \quad \forall k=1,2,\dots. \label{eq:proof:fcfs:induction-on-wait} \end{equation} Case $k=1$ is trivial because $W(1) = \sysup{W}(1) = 0$. Suppose we have proved case $1,2,\dots, k$. For case $k+1$, to get a contradiction, suppose $W(k+1) > \sysup{W}(k+1)$. Let $T = \sysup{A}(k+1) + \sysup{W}(k+1)$. The job $k+1$ starts service at time $T$ in the upper bounding system, but doesn't start service until $A(k+1) + W(k+1)$ in the original system. This implies that the moment before time $T$, the original system has $>n - L(k+1)$ busy servers, while the upper bounding system has $\leq n - \ell_{\max}$ busy servers. Because $n - L(k+1) \geq n - \ell_{\max}$, \begin{equation} \sum_{j\in \mathcal{\ve{Z}}(T;k)} L(j) > \sum_{j\in \sysup{\mathcal{\ve{Z}}}(T;k)} L(j), \label{eq:proof:fcfs:busy-server-inequality} \end{equation} where \[ \mathcal{\ve{Z}}(T;k) = \{j\mid j\leq k, A(j) + W(j) + S(j) > T\}, \] \[ \sysup{\mathcal{\ve{Z}}}(T;k) = \{j\mid j\leq k, A(j) + \sysup{W}(j) + S(j) > T\}. \] $\mathcal{\ve{Z}}(T;k)$ and $\sysup{\mathcal{\ve{Z}}}(T;k)$ are the set of jobs with index $j\leq k$ who hasn't finished service by time $T$ in the original system and upper bounding system. However, by the induction hypothesis, $\mathcal{\ve{Z}}(T;k) \subseteq \sysup{\mathcal{\ve{Z}}}(T;k)$, this contradicts (\ref{eq:proof:fcfs:busy-server-inequality})! Therefore $W(k+1) \leq \sysup{W}(k+1)$. By induction, (\ref{eq:proof:fcfs:induction-on-wait}) is true. Observe that the number of type~$i$ jobs in the queues at time $t$ is \begin{align} Q_i(t) &= \sum_{k=1}^\infty \mathbb{1}\{C(k) = i, A(k)\leq t, A(k) + W(k) > t\} \label{eq:proof:fcfs:q-w}\\ \sysup{Q}_i(t) &= \sum_{k=1}^\infty \mathbb{1}\{C(k) = i, A(k)\leq t, A(k) + \sysup{W}(k) > t\}.\label{eq:proof:fcfs:q-w-upper} \end{align} by (\ref{eq:proof:fcfs:induction-on-wait}), $Q_i(t) \leq \sysup{Q}_i(t)$ for any $t, i$. Therefore, in steady-state, we have $\mathbb{E}[Q_i] \leq \mathbb{E}[\sysup{Q}_i]$ for any $i$. For the other inequality, we perform a similar argument. We prove by induction on $k$ that \begin{equation} W(k) \geq \syslow{W}(k) \quad \forall k=1,2,\dots. \label{eq:proof:fcfs:induction-on-wait2} \end{equation} Case $k=1$ is trivial because $W(1) = \syslow{W}(1) = 0$. Suppose we have proved case $1,2,\dots, k$. For case $k+1$, to get a contradiction, suppose $W(k+1) < \syslow{W}(k+1)$. Let $T = A(k+1) + W(k+1)$, then $T<\syslow{A}(k+1) + \syslow{W}(k+1)$. This implies that at time $T$, the $(k+1)$-th job in the original system starts its service, while the $(k+1)$-th job in the lower bounding system is still waiting at the head of line. According to the policy they use, at the moment right before $T$, the original system has $\leq n-L(k+1)$ busy servers, while the lower bounding system has $>n$ busy servers. Therefore, \begin{equation} \sum_{j\in \mathcal{\ve{Z}}(T;k)} L(j) < \sum_{j\in \syslow{\mathcal{\ve{Z}}}(T;k)} L(k), \label{eq:proof:fcfs:busy-server-inequality2} \end{equation} where \[ \mathcal{\ve{Z}}(T;k) = \{j \mid j\leq k, A(j) + W(j) + S(j) > T\}, \] \[ \syslow{\mathcal{\ve{Z}}}(T;k) = \{j \mid j\leq k, A(j) + \syslow{W}(j) + S(j) > T\}. \] However, by induction hypothesis, $\syslow{\mathcal{\ve{Z}}}(T;k) \subseteq \mathcal{\ve{Z}}(T;k)$, this contradicts (\ref{eq:proof:fcfs:busy-server-inequality2}). Therefore $W(k+1) \geq \syslow{W}(k+1)$. By induction, \eqref{eq:proof:fcfs:induction-on-wait2} is true. Because , \begin{equation} \syslow{Q}_i(t) = \sum_{k=1}^\infty \mathbb{1}\{C(k) = i, A(k)\leq t, A(k) + \syslow{W}(k) > t\}, \label{eq:proof:fcfs:q-w-lower} \end{equation} by \eqref{eq:proof:fcfs:q-w} and the fact that $W(k) \geq \syslow{W}(k)$ for all $k$, it follows that $Q_i(t) \geq \syslow{Q}_i(t)$ for all $i,t$. Therefore, in steady-state, we have $\mathbb{E}[\syslow{Q}_i] \leq \mathbb{E}[Q_i]$ for any $i$. This finishes the proof of Lemma~\ref{lem:fcfs:sandwich}. \end{proof} \fcfsindependence* \begin{proof}[Proof of Lemma~\ref{lem:fcfs:independence}]: Observe that \begin{equation} \begin{aligned} \sysup{Q}_i(t) = \sum_{k=1}^\infty \mathbb{1}\{\sysup{C}(k) = i, \sysup{A}(k) \leq t, \sysup{A}(k) + \sysup{W}(k) > t\}. \end{aligned} \end{equation} Taking expectation on both sides, we get \begin{equation} \begin{aligned} \mathbb{E} \sysup{Q}_i(t) = \sum_{k=1}^\infty \frac{\lambda_i}{\lambda} \mathbb{P}\Big(&\sysup{A}(k) \leq t, \sysup{A}(k) + \sysup{W}(k) > t \mid \sysup{C}(k) = i\Big) . \end{aligned}\label{eq:proof:modified-fcfs:queue-fraction-intermediate} \end{equation} Let $\mathcal{F}_k = \sigma((\sysup{A}_0(j), \sysup{S_0}(j), \sysup{C}(j))\mid j\leq k)$. It is not hard to see that \[ \left(\sysup{S}(j), \sysup{A}(j), \sysup{L}(j), \sysup{W}(j) \right)\in \mathcal{F}_k \quad \text{ for } j\leq k. \] Observe that \begin{equation} \label{eq:proof:fcfs:independence-long-ineq} \begin{aligned} &\mspace{23mu}\{\sysup{A}(k)\leq t, \sysup{A}(k)+\sysup{W}(j) > t\} \\ &= \{\sysup{A}(k) \leq t, \sum_{j\in \sysup{\mathcal{\ve{Z}}}(t;k-1)} \sysup{L}(j) > n - \ell_{\max}\}. \end{aligned} \end{equation} and RHS $\in \sigma(\mathcal{F}_{k-1},\sysup{A}_0(k))$. Therefore, $\{\sysup{A}(k) \leq t, \sysup{A}(k) + \sysup{W}(k) > t\} \in \sigma(\mathcal{F}_{k-1},\sysup{A}_0(k))$, which is independent of $\sysup{C}(k)$. This fact helps us simplify the RHS of (\ref{eq:proof:modified-fcfs:queue-fraction-intermediate}) and get \begin{equation} \mathbb{E} \sysup{Q}_i(t) = \frac{\lambda_i}{\lambda}\sum_{k=1}^\infty \mathbb{P}\left(\sysup{A}(k) \leq t, \sysup{A}(k) + \sysup{W}(k) > t\right), \end{equation} but \begin{equation} \mathbb{E} \sysup{Q}_{\Sigma}(t) = \sum_{k=1}^\infty \mathbb{P}\left(\sysup{A}(k) \leq t, \sysup{A}(k) + \sysup{A}(k) > t\right). \end{equation} This proves (\ref{eq:proof:system2:queue-fraction}). The proof of (\ref{eq:proof:system3:queue-fraction}) is almost identical with all superscript $(U)$ replaced by superscript $(L)$, and equation \eqref{eq:proof:fcfs:independence-long-ineq} replaced by \begin{equation} \begin{aligned} &\mspace{23mu}\{\syslow{A}(k)\leq t, \syslow{A}(k)+\syslow{W}(j) > t\} \\ &= \{\syslow{A}(k) \leq t, \sum_{j\in \syslow{\mathcal{\ve{Z}}}(t;k-1)} \syslow{L}(j) > n\}. \end{aligned} \end{equation} \end{proof} \section{Proofs of the lemmas for Theorem~\ref{result:waiting-time-priority} (mean waiting time under P-Priority)}\label{sec:app:priority} \subsection{General markov chain}\label{sec:app:tail-bounds-general} In this subsection, we consider a continuous-time Markov chain $\{\ve{S}(t)\}_{t\geq 0}$ on a countable state space $\mathcal{S}$ with generator $G$. Let $r_{ss'}$ denote the transition rate from state $\ve{s}$ to $\ve{s}'$, and let $r(\ve{s}) = -r_{ss}\triangleq \sum_{\ve{s}'\in\mathcal{S},\ve{s}'\neq \ve{s}} r_{ss'}.$ For any function $f\colon \mathcal{S}\to\mathbb{R}$, the drift of $f$ is equal to \begin{equation} G f(\ve{s}) = \sum_{\ve{s}'\in \mathcal{S}} r_{ss'} \left(f(\ve{s}') - f(\ve{s})\right). \end{equation} We assume that $\{\ve{S}(t)\}_{t\geq 0}$ has a stationary distribution and let $\ve{S}(\infty)$ denote a random element that follows the stationary distribution. For a Lyapunov function $V: \mathcal{S}\rightarrow \mathbb{R}_+$, Lemma~\ref{lem:lyapunov-upper-bound} below gives a tail bound on $V(\ve{S}(\infty))$ based on drift analysis. It is a straightforward consequence of Lemma~A.1 in \cite{WenWan_21}, which slightly generalizes the well-known Lyapunov-based tail bounds (see, e.g., \cite{BerGamTsi_98,WanMagSri_17}). \begin{lem}[Lyapunov Upper Bound]\label{lem:lyapunov-upper-bound} Consider the Markov chain $\{\ve{S}(t)\}_{t\geq 0}$ and let $V: \mathcal{S}\rightarrow \mathbb{R}_+$ be a Lyapunov function such that $\mathbb{E}[V(\ve{S}(\infty))] < \infty$. Assume that \begin{align*} &\sup_{\ve{s}\in\mathcal{S}} r(\ve{s}) < \infty,\\ &v_{\max} \triangleq \sup_{\ve{s},\ve{s}'\in\mathcal{S}: r_{ss'} > 0} \abs{V(\ve{s}') - V(\ve{s})} < \infty,\\ &f_{\max} \triangleq \sup_{\ve{s}} \sum_{\ve{s}':V(\ve{s}')>V(\ve{s})} r_{ss'}\left(V(\ve{s}') - V(\ve{s})\right) <\infty. \end{align*} If there exists $B\geq 0$, $\gamma > 0,$ $\xi > 0$ and a subset $\mathcal{E}\subseteq \mathcal{S}$ such that for all $\ve{s}$ with $V(\ve{s}) > B+v_{\max}$, \begin{equation*} G V(\ve{s}) \leq \begin{cases} - \gamma, \quad &\forall \ve{s}\in \mathcal{E},\\ \xi, \quad &\forall \ve{s}\in \mathcal{S}\backslash\mathcal{E}, \end{cases} \end{equation*} then for all $j\geq 0$, \begin{equation}\label{eq:lyapunov-upper:conclusion} \mathbb{P}\left(V(\ve{S}(\infty)) \ge B +2v_{\max}\cdot\left(\left(\frac{ f_{\max}}{\gamma}+2\right)j+1\right)\right) \leq e^{-j} + \left(\frac{\xi}{\gamma}+1\right)\mathbb{P}(\ve{S}(\infty) \in \mathcal{E}^c). \end{equation} \end{lem} \begin{proof}[Proof of Lemma~\ref{lem:lyapunov-upper-bound}] According to Lemma~1 of \cite{BerGamTsi_98}, for any integer $j'\geq 0$, \begin{equation*} \begin{aligned} \mathbb{P}\left(V(S(\infty)) > B + 2v_{\max}\cdot j'\right) &\leq \left(\frac{f_{\max}}{f_{\max}+\gamma}\right)^{j'} +\left(\frac{\xi}{\gamma}+1\right)\mathbb{P}(S(\infty) \in \mathcal{E}^c). \\ &\leq \exp\left(-\frac{\gamma j'}{f_{\max} + \gamma}\right) + \left(\frac{\xi}{\gamma}+1\right)\mathbb{P}(S(\infty) \in \mathcal{E}^c) \end{aligned} \end{equation*} For any $j \geq 0$, we set $j' = \lceil( \frac{f_{\max}}{\gamma} +1)j \rceil$, which is an integer less than or equal to $\left(\left(\frac{ f_{\max}}{\gamma}+2\right)j+1\right)$. Then \eqref{eq:lyapunov-upper:conclusion} follows. \end{proof} \subsection{Multiserver-job system}\label{sec:app:tail-bounds-msj} With the general tool Lemma~\ref{lem:lyapunov-upper-bound} ready, we can now start proving Lemma~\ref{lem:proof:workload-tail}, Lemma~\ref{lem:proof:total-server-need-tail} and Lemma~\ref{lem:proof:total-server-need-expectation}, which are needed for proving Theorem~\ref{result:waiting-time-priority}. We will also prove Corollary~\ref{result:queueing-probability} on queueing probability. \workloadtail* \tsntail* \begin{proof}[Proof of Lemma~\ref{lem:proof:workload-tail}] The Lemma is proved by applying Lemma~\ref{lem:lyapunov-upper-bound} to the Lyapunov function $V_1(\ve{x}) = \sum_{i=1}^I \frac{\ell_i }{\sev_i} x_i$, where $\ve{x} \in \mathbb{R}^I$ denote possible realizations of $\ve{X}$. Recall that the drift of $V_1(\ve{x})$ is \begin{equation} \begin{aligned} G V_1(\ve{x}, \ve{z}) = \sum_{i=1}^I \lambda_i \left(V_1(\ve{x}+\ve{e}_i) - V_1(\ve{x})\right) + \sum_{i=1}^I \sev_i z_i \left(V_1(\ve{x}-\ve{e}_i) - V_1(\ve{x})\right). \end{aligned}\label{eq:proof:gv1-full}\\ \end{equation} From the formula of the drift, we can immediately conclude that $v_{\max}$, $f_{\max}$ in Lemma~\ref{lem:lyapunov-upper-bound} are $v_{\max} = \max_{i \in [I]} \frac{\ell_i}{\sev_i}$, $f_{\max}=\sum_{i=1}^I \frac{\lambda_i\ell_i}{\sev_i}$. The two parameters satisfy $v_{\max} \leq \frac{\ell_{\max}}{\sev_{\min}}$, $f_{\max} = n-\delta \leq n$. We spend the rest of the proof showing that $G V_1(\ve{x}, \ve{z})<-\gamma$ with high probability and $G V_1(\ve{x},\ve{z}) < \xi$ otherwise for some $\gamma, \xi > 0$, when $V_1(\ve{x})$ is larger than a threshold, i.e., when \begin{equation*} \sum_{i=1}^I \frac{\ell_i}{\sev_i}x_i = V_1(\ve{x}) > \sum_{i=1}^I \frac{\ell_i}{\sev_i}\bar{x}_i + B_1, \end{equation*} for some $B_1 \geq 0$. We prove this by finding a suitable state-space concentration. To see what we need to upper bound $G V_1$, we write out its form explicitly: \begin{align} G V_1(\ve{x},\ve{z}) &= \sum_{i=1}^I \left(\frac{\lambda_i\ell_i}{\sev_i} - \ell_i z_i\right) \label{eq:proof:gv1:temp0} \\ &\leq \sum_{i=1}^I \frac{\lambda_i\ell_i}{\sev_i} - \min\left(\sum_{i=1}^I \ell_i x_i, n - \ell_{\max}\right) \nonumber \\ &= -\min\left(\sum_{i=1}^I \ell_i (x_i-\bar{x}_i), \delta - \ell_{\max}\right) \nonumber\\ &\leq -\min\left(\sum_{i=1}^I \ell_i (x_i-\bar{x}_i), \epsilon_0\delta\right), \label{eq:proof:gv1:temp} \end{align} where the first inequality is because of the $\ell_{\max}$-work-conserving condition, and the last inequality used the fact that $\ell_{\max} \leq \epsilon_0\delta$. The last expression suggests that we need a high probability lower bound on $\sum_{i=1}^I \ell_i X_i$. We apply Lemma~\ref{lem:mminf-bounds} to construct a subset $\mathcal{E}_{3}(j_1) \subseteq \mathbb{R}^I$ such that $\ve{X} \in \mathcal{E}_{3}(j_1)$ with high probability, where $j_1$ is a non-negative number. We set $c_i = \frac{1}{\sev_{\min}}- \frac{1}{\sev_i}$, $\alpha = \frac{\epsilon \delta}{\sev_{\min}}$, $\beta = \frac{\sev_{\max} n\ell_{\max}}{\sev_{\min}^2 \epsilon\delta}$, $j = 2\log n + j_1$ in Lemma~\ref{lem:mminf-bounds}. It can be verified that $\alpha\beta \geq \frac{\sev_{\max} n \ell_{\max}}{\sev_{\min}^3} \geq c_{\max}^2 \sev_{\max} \sigma^2$. Then we have \begin{equation} \mathbb{P}\left(\sum_{i=1}^I\left(\tfrac{1}{\sev_{\min}} - \tfrac{1}{\sev_i} \right)\ell_i(X_i - \bar{x}_i) \leq -\alpha - \beta j_1 \right) \leq e^{-j_1}. \end{equation} Let $\alpha_{3} = \alpha + 2 \beta \log n$, $\beta_{3} = \beta$, we have \begin{equation} \mathbb{P}\left(\sum_{i=1}^I\left(\tfrac{1}{\sev_{\min}} - \tfrac{1}{\sev_i} \right)\ell_i(X_i - \bar{x}_i) \leq -\alpha_{3} - \beta_{3} j_1 \right) \leq \frac{1}{n^2} e^{-j_1}. \end{equation} Note that this choice of $\alpha_{3}$ and $\beta_{3}$ satisfies $\beta_{3} = \Theta\left(\frac{n\ell_{\max}}{ \delta}\right)$ and $\alpha_{3} = \frac{\epsilon \delta}{\sev_{\min}} + \Theta\left(\frac{n\ell_{\max}}{ \delta}\log(n)\right)$. Define \[ \mathcal{E}_{3}(j_1) = \left\{\ve{x}\in\mathbb{R}^I \;\middle|\; \sum_{i=1}^I \left(\tfrac{1}{\sev_{\min}} - \tfrac{1}{\sev_i} \right)\ell_i(x_i - \bar{x}_i) > -\alpha_{3} - \beta_{3} j_1 \right\}, \] then $\mathbb{P}\left(\mathcal{E}_{3}(j_1)\right) \geq 1-\frac{1}{n^2}e^{-j_1}$. Next, we divide the state space into two parts based on $\mathcal{E}_{3}(j_1)$, and analyze $G V(\ve{x},\ve{z})$ on each part separately. When $V_1(\ve{x}) > \sum_{i=1}^I \frac{\ell_i}{\sev_i}\bar{x}_i + B_1$ and $\ve{x}\in\mathcal{E}_{3}(j_1)$, the former condition implies that \begin{equation*} \sum_{i=1}^I \frac{\ell_i}{\sev_i}(x_i - \bar{x}_i) > B_1, \end{equation*} while the latter condition implies that \begin{equation*} \sum_{i=1}^I \left(\tfrac{1}{\sev_{\min}} - \tfrac{1}{\sev_i} \right)\ell_i(x_i - \bar{x}_i) > -\alpha_{3} - \beta_{3} j_1. \end{equation*} Adding up the above two inequality and choosing $B_1 = \alpha_{3} + \beta_{3} j_1+\frac{\epsilon \delta}{\sev_{\min}}$ yield \begin{equation} \sum_{i=1}^I \ell_i(x_i - \bar{x}_i) \geq \epsilon\delta. \end{equation} By (\ref{eq:proof:gv1:temp}) and the fact that $\epsilon < \epsilon_0$, we conclude that $G V(\ve{x},\ve{z}) \leq - \epsilon \delta$. On the other hand, when $V_1(\ve{x}) > \sum_{i=1}^I \frac{\ell_i}{\sev_i}\bar{x}_i + B_1$ and $\ve{x}\notin \mathcal{E}_{3}(j_1)$, it follows from \eqref{eq:proof:gv1:temp0} that $GV(\ve{x},\ve{z}) \leq n$. Now we can apply Lemma~\ref{lem:lyapunov-upper-bound} with $B=\sum_{i=1}^I \frac{\ell_i}{\sev_i}\bar{x}_i + B_1$, $\gamma = -\epsilon \delta$, $\xi = n$, $v_{\max} = \max_{i\in[I]}\frac{\ell_i}{\sev_i}$, $f_{\max} = \sum_{i=1}^I \frac{\lambda_i \ell_i}{\sev_i}$ and $\mathcal{E} = \mathcal{E}_{3}(j_1)$ to get \begin{equation} \begin{aligned} &\mspace{23mu}\mathbb{P}\Bigg(\sum_{i=1}^I \frac{\ell_i}{\sev_i} (X_i - \bar{x}_i) \geq \alpha_{3} + \beta_{3} j_1 + \frac{\epsilon\delta}{\sev_{\min}}+ 2v_{\max}\left(\left(\frac{f_{\max}}{\epsilon\delta}+2\right)j_2+1\right)\Bigg)\leq e^{-j_2} + \left(\frac{n}{\epsilon\delta}+1\right)\frac{1}{n^2}e^{-j_1}. \end{aligned} \end{equation} which holds for any $j_1, j_2 \geq 0$. This inequality can be further simplified to \begin{equation} \begin{aligned} &\mspace{23mu}\mathbb{P}\Bigg(\sum_{i=1}^I \frac{\ell_i}{\sev_i} (X_i - \bar{x}_i) \geq \alpha_{3} + \beta_{3}j_1 + \frac{\epsilon\delta}{\sev_{\min}} + 2\frac{\ell_{\max}}{\sev_{\min}}\left(\frac{(2\epsilon_0+1)n}{\epsilon\delta}j_2+1\right)\Bigg)\leq e^{-j_2} + e^{-j_1}. \end{aligned} \end{equation} where we have used the facts that $v_{\max} \leq \frac{\ell_{\max}}{\sev_{\min}}$, $f_{\max} \leq n$, $n>\delta$, $\epsilon < \epsilon_0$, and $\left(\frac{n}{\epsilon\delta}+1\right)\frac{1}{n^2} \leq 1$ which holds for $n$ large enough. Replacing both of $j_1$ and $j_2$ with $j+\log(2)$, and letting $\beta_1 = \beta_{3} + \frac{(4\epsilon_0+2) n \ell_{\max}}{\sev_{\min} \epsilon \delta}$, $\alpha_1 = \alpha_{3} + \frac{\epsilon \delta}{\sev_{\min}} + \frac{2\ell_{\max}}{\sev_{\min}} + \beta_1 \log(2)$, we get the equation in the lemma statement. Note that this choice of $\alpha_1$ and $\beta_1$ implies that $\beta_1 =\Theta\left(\frac{n\ell_{\max}}{\delta}\right)$ and $\alpha_1 = \frac{2\epsilon\delta}{\sev_{\min}}+\Theta\left(\frac{n\ell_{\max}}{\delta}\log(n)\right)$. This proves Lemma~\ref{lem:proof:workload-tail}. \end{proof} \begin{proof}[Proof of Lemma~\ref{lem:proof:total-server-need-tail}] Again we try to prove the result by applying Lemma~\ref{lem:lyapunov-upper-bound} on the Lyapunov function $V_2(\ve{x}) = \sum_{i=1}^I \ell_i x_i$. Recall that the drift of $V_2(\ve{x})$ is equal to \begin{equation} \begin{aligned} G V_2(\ve{x}, \ve{z}) &= \sum_{i=1}^I \lambda_i \left(V_2(\ve{x}+\ve{e}_i) - V_2(\ve{x})\right) + \sum_{i=1}^I \sev_i z_i \left(V_2(\ve{x}-\ve{e}_i) - V_2(\ve{x})\right). \end{aligned}\label{eq:proof:gv2-full} \end{equation} From the formula of the drift, we see that parameters $v_{\max}$, $f_{\max}$ of Lemma~\ref{lem:lyapunov-upper-bound} satisfies \begin{align} v_{\max} &= \ell_{\max} \leq n\ell_{\max}\\ f_{\max} &= \sum_{i=1}^I \lambda_i \ell_i \leq \sev_{\max} n. \end{align} We spend the rest of the proof showing that $G V_2(\ve{x}, \ve{z})<-\gamma$ with high probability and $G V_2(\ve{x},\ve{z}) < \xi$ otherwise for some $\gamma, \xi > 0$, when $V_2(\ve{x})$ is larger than a threshold, i.e., when \begin{equation} \sum_{i=1}^I \ell_i x_i = V_2(\ve{x}) > \sum_{i=1}^I \ell_i\bar{x}_i + B_2, \label{eq:proof:v2-greater-B} \end{equation} for some non-negative $B_2$ to be specified later. We bound $GV_2$ by finding a suitable state-space concentration. To do this, we write out the form of $G V_2$ explicitly and decompose $GV_2(\ve{x},\ve{z})$ into two terms: \begin{align} G V_2(\ve{x},\ve{z}) &= \sum_{i=1}^I (\lambda_i \ell_i - \sev_i \ell_i z_i) \label{eq:proof:gv2-temp0}\\ &= \sum_{i=1}^I \left(\lambda_i \ell_i +(\sev_{\max} - \sev_i)\ell_i z_i\right) - \sum_{i=1}^I \sev_{\max} \ell_i z_i \nonumber\\ &\leq \sum_{i=1}^I \left(\lambda_i \ell_i +(\sev_{\max} - \sev_i)\ell_i x_i \right) - \sev_{\max} \min\left(\sum_{i=1}^I \ell_i x_i, n-\ell_{\max} \right)\nonumber\\ &= -\sev_{\max}\min\left(\sum_{i=1}^I \frac{\sev_i}{\sev_{\max}} \ell_i(x_i -\bar{x}_i), \;(\delta - \ell_{\max})-\sum_{i=1}^I\left(1-\frac{\sev_i}{\sev_{\max}}\right)\ell_i(x_i-\bar{x}_i)\right),\label{eq:proof:iter2:gv2-leq-sth} \end{align} where the inequality is due to $z_i \leq x_i$ and the $\ell_{\max}$-work-conserving condition. The last expression suggests that in order to apply Lemma~\ref{lem:lyapunov-upper-bound}, we need to lower bound $\sum_{i=1}^I \frac{\sev_i}{\sev_{\max}} \ell_i(X_i -\bar{x}_i)$ and upper bound $\sum_{i=1}^I(1-\frac{\sev_i}{\sev_{\max}})\ell_i(X_i-\bar{x}_i)$ with high probability. Now we construct a subset $\mathcal{E} \subseteq \mathbb{R}^I$ such that $\ve{X}\in \mathcal{E}$ with high probability, and $f(\ve{x})$ has negative drift whenever $\ve{x}\in\mathcal{E}$ and $f(\ve{x})>B_2$ for some $B_2\geq 0$. For a fixed $j_1 \geq 0$, define the set \[ \mathcal{E}_{4}(j_1) = \left\{\ve{x}\in\mathbb{R}^I \;\middle|\; \sum_{i=1}^I \left(\tfrac{\sev_{\max}}{\sev_i} + \tfrac{\sev_i}{\sev_{\max}} - 2\right) \ell_i(x_i - \bar{x}_i) > - \alpha_{4} - \beta_{4} j_1\right\}, \] where \[ \beta_{4} = \left(\frac{\sev_{\max}}{\sev_{\min}} + \frac{\sev_{\min}}{\sev_{\max}} - 2\right)^2\frac{\sev_{\max}}{\sev_{\min}} \cdot \frac{n\ell_{\max}}{\epsilon \delta}, \quad \alpha_{4} = \epsilon \delta + 2\beta_{4} \log n. \] Note that this choice of $\beta_{4}$, $\alpha_{4}$ yields $\beta_{4} = \Theta\left(\frac{n\ell_{\max}}{\delta}\right)$, $\alpha_{4}= \epsilon \delta + \Theta\left(\frac{n\ell_{\max}}{\delta} \log n\right)$. In addition, let \[ \mathcal{E}_1(j_1) = \left\{\ve{x}\in\mathbb{R}^I \;\middle|\; \sum_{i=1}^I \frac{\ell_i}{\sev_i} (x_i - \bar{x}_i) < \alpha_1 + \beta_1 j_1\right\}, \] where $\beta_1 = \Theta\left(\frac{n\ell_{\max}}{\delta}\right)$ and $\alpha_1 = \frac{2\epsilon\delta}{\sev_{\min}}+\Theta\left(\frac{n\ell_{\max}}{\delta}\log n\right)$ as defined in Lemma~\ref{lem:proof:workload-tail}. Define $\mathcal{E}$ as \[ \mathcal{E} = \mathcal{E}_{4}(j_1)\cap \mathcal{E}_1(j_1+2\log n), \] If we choose $B_2$ as \begin{align*} B_2 &= \sev_{\max}(\alpha_1+\beta_1 (j_1+2\log n))+\alpha_{4}+\beta_{4}j_1 + \epsilon \delta\\ &= 2\left(1+\tfrac{\sev_{\max}}{\sev_{\min}}\right) \epsilon \delta +\Theta\left(\frac{n\ell_{\max}}{\delta}\log(n)\right) + \Theta\left(\frac{n\ell_{\max}}{\delta}\right) j_1, \end{align*} then $V_2(\ve{x}) > \sum_{i=1}^I \ell_i\bar{x}_i + B_2$ and $\ve{x}\in \mathcal{E}$ imply the following three inequalities: \begin{align} &\sum_{i=1}^I \ell_i(x_i - \bar{x}_i) > \sev_{\max}\left(\alpha_1+\beta_1 (j_1+2\log n)\right)+\alpha_{4}+\beta_{4}j_1 + \epsilon \delta, \label{eq:proof:iter2:ssc1}\\ &\sum_{i=1}^I \frac{\ell_i}{\sev_i} (x_i - \bar{x}_i) < \alpha_1 + \beta_1 (j_1+2\log n),\label{eq:proof:iter2:ssc2}\\ &\sum_{i=1}^I \left(\tfrac{\sev_{\max}}{\sev_i}+\tfrac{\sev_i}{\sev_{\max}}-2\right)\ell_i(x_i - \bar{x}_i) > -\alpha_{4} - \beta_{4} j_1 \label{eq:proof:iter2:ssc3}. \end{align} Consider $- \eqref{eq:proof:iter2:ssc1} + \sev_{\max} \cdot \eqref{eq:proof:iter2:ssc2} - \eqref{eq:proof:iter2:ssc3}$, we get \begin{equation} \sum_{i=1}^I \left(1 - \tfrac{\sev_i}{\sev_{\max}}\right)\ell_i (x_i - \bar{x}_i) \leq -\epsilon \delta < 0; \end{equation} consider $2\cdot \eqref{eq:proof:iter2:ssc1} - \sev_{\max} \cdot \eqref{eq:proof:iter2:ssc2} + \eqref{eq:proof:iter2:ssc3}$, we get \begin{equation} \sum_{i=1}^I \frac{\sev_i}{\sev_{\max}} \ell_i(x_i - \bar{x}_i) \geq \sev_{\max}\left(\alpha_1+\beta_1 (j_1+2\log n)\right)+\alpha_{4}+\beta_{4}j_1 + 2\epsilon \delta > \epsilon \delta. \end{equation} In the above inequalities we have used the fact that all parameters involved in the expressions, $\alpha_1, \beta_1, j_1, \alpha_{4}, \beta_{4},\delta$, are non-negative. We substitute the above two inequalities back to \eqref{eq:proof:iter2:gv2-leq-sth}, and choose $\epsilon < \min(1-\epsilon_0, \epsilon_0)$. This gives us \begin{equation*} GV_2(\ve{x},\ve{z}) \leq -\sev_{\max} \min(\epsilon \delta, \delta - \ell_{\max}) \leq -\sev_{\max} \epsilon \delta. \end{equation*} Next, we show that $\ve{X}\in\mathcal{E}$ with high probability. We apply Lemma~\ref{lem:mminf-bounds} with $c_i = \frac{\sev_{\max}}{\sev_i} + \frac{\sev_i}{\sev_{\max}} - 2$, $c_{\max}= \frac{\sev_{\max}}{\sev_{\min}} + \frac{\sev_{\min}}{\sev_{\max}} - 2$, $\alpha = \epsilon \delta$, $\beta = \frac{c_{\max}^2 \sev_{\max} n\ell_{\max}}{\sev_{\min}\epsilon\delta}$. It can be verified that $\alpha\beta \geq c_{\max}^2 \sev_{\max} \sigma^2$, so \begin{equation} \mathbb{P}\left(\sum_{i=1}^I \left(\tfrac{\sev_{\max}}{\sev_i} + \tfrac{\sev_i}{\sev_{\max}} - 2\right) \ell_i(X_i - \bar{x}_i) \leq - \alpha - \beta j\right) \leq e^{-j}, \end{equation} Setting $j = j_1+2\log n$ and recalling the definition of $\alpha_4$, $\beta_4$, we get \begin{equation} \mathbb{P}\left(\sum_{i=1}^I \left(\tfrac{\sev_{\max}}{\sev_i} + \tfrac{\sev_i}{\sev_{\max}} - 2\right) \ell_i(X_i - \bar{x}_i) \leq - \alpha_{4} - \beta_{4} j_1\right) \leq \frac{1}{n^2} e^{-j_1}, \end{equation} i.e., $\mathbb{P}\left(\ve{X}\in\mathcal{E}_{4}(j_1)\right) \geq 1 - \frac{1}{n^2} e^{-j_1}$. Applying Lemma~\ref{lem:proof:workload-tail} to the set $\mathcal{E}_1(j_1+2\log n)$, we have $\mathbb{P}\left(\ve{X} \in \mathcal{E}_1(j_1+2\log n)\right) \geq 1 - \frac{1}{n^2}e^{-j_1}$. Recall that $\mathcal{E} = \mathcal{E}_{4}(j_1)\cap \mathcal{E}_{1}(j_1+2\log n)$, by union bound, \[ \mathbb{P}(\ve{X}\in\mathcal{E}) \geq 1 - \frac{2}{n^2}e^{-j_1}. \] On the other hand, when $\ve{x}\notin \mathcal{E}$, from the form of \eqref{eq:proof:gv2-temp0}, we can see that the drift $G V_2(\ve{x},\ve{z})\leq\sev_{\max} n$. We apply Lemma~\ref{lem:lyapunov-upper-bound} with $B = \sum_{i=1}^I \ell_i\bar{x}_i + B_2$ $\gamma = -\sev_{\max} \epsilon \delta$, $\xi = \sev_{\max} n$, $\mathcal{E} = \mathcal{E}_{4}(j_1)\cap \mathcal{E}_{1}(j_1+2\log n)$, $f_{\max} \leq \sev_{\max} n$, $v_{\max} = \ell_{\max}$. This gives us \begin{equation} \begin{aligned} &\mspace{23mu} \mathbb{P}\left(\sum_{i=1}^I \ell_i(X_i - \bar{x}_i) \geq B_2 + 2 \ell_{\max} \left(\left(\tfrac{f_{\max}}{\sev_{\max}\epsilon\delta}+2\right)j_2 + 1\right) \right)\leq e^{-j_2}+ \left(\frac{n}{\epsilon \delta}+1\right)\frac{2}{n^2} e^{-j_1}. \end{aligned} \label{eq:proof:v2-apply-lem} \end{equation} This inequality can be further simplified to \begin{equation} \begin{aligned} &\mspace{23mu} \mathbb{P}\left(\sum_{i=1}^I \ell_i(X_i - \bar{x}_i) \geq B_2 + 2 \ell_{\max} \left(\frac{(2\epsilon_0+1)n}{\epsilon\delta} j_2 + 1\right) \right)\leq e^{-j_2}+ e^{-j_1}, \end{aligned} \end{equation} where we have used the fact that $f_{\max} \leq n\sev_{\max}$, $n>\delta$, $\epsilon < \epsilon_0$, and $\left(\frac{n}{\epsilon \delta}+1\right)\frac{2}{n^2} \leq 1$ which holds for $n$ large enough. Setting $j_2$ to be equal to $j_1$ and rearranging the terms, we get \begin{equation} \mathbb{P}\left(\sum_{i=1}^I \ell_i(X_i - \bar{x}_i) \geq \alpha_2 + \beta_2 j_1\right) \leq 2\exp(-j_1), \end{equation} where \[ \beta_2 = \frac{(2\epsilon_0+1)n\ell_{\max}}{\epsilon\delta}+\sev_{\max} \beta_1 +\beta_{4} = \Theta(\frac{n\ell_{\max}}{\delta}), \] \begin{align*} \alpha_2 &= \sev_{\max}(\alpha_1+2\beta_2 \log n) + \alpha_{4}+\epsilon \delta + 2\ell_{\max}\\ &= 2(1+\frac{\sev_{\max}}{\sev_{\min}}) \epsilon \delta +\Theta(\frac{n\ell_{\max}}{\delta}\log(n)). \end{align*} We choose any $\epsilon$ satisfying $0 < \epsilon < \min\left(1-\epsilon_0, \epsilon_0, \frac{1}{4(1+\sev_{\max}/\sev_{\min})}\right)$ and set $j_1 \leftarrow j + \log(2)$, then Lemma~\ref{lem:proof:total-server-need-tail} is proved. \end{proof} \tsnupper* \begin{proof}[Proof of Lemma~\ref{lem:proof:total-server-need-expectation}] We proceed by trying to build a connection between the expectation $\mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i - \bar{x}_i)\right]$ and the tail probability $\mathbb{P}\left(\sum_{i=1}^I \ell_i (X_i - \bar{x}_i) \geq \alpha_2 + \beta_2 j\right)$, where $\alpha_2=\frac{\delta}{2} + \Theta\left(\frac{n\ell_{\max}}{\delta}\log n \right)$, $\beta_2=\Theta\left(\frac{n\ell_{\max}}{\delta}\right)$ are given in Lemma~\ref{lem:proof:total-server-need-tail}. We first decompose $\mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i - \bar{x}_i)\right]$ as follows: \begin{align} \mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i - \bar{x}_i)\right] &= \mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i - \bar{x}_i) \mathbb{1}_{\{\sum_{i=1}^I \ell_i X_i \geq n\}}\right]+ \mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i - \bar{x}_i) \mathbb{1}_{\{\sum_{i=1}^I \ell_i X_i < n\}}\right].\nonumber\\ &= \mathbb{E}\left[\left(\sum_{i=1}^I \ell_i(X_i - \bar{x}_i) - \delta\right)^+ \right]\label{eq:total-server-need-expect:decomp1}\\ &\mspace{18mu} + \delta \mathbb{P}\left(\sum_{i=1}^I \ell_i X_i \geq n\right)\label{eq:total-server-need-expect:decomp2}\\ &\mspace{18mu}+\mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i - \bar{x}_i) \mathbb{1}_{\{\sum_{i=1}^I \ell_i X_i < n\}}\right] \label{eq:total-server-need-expect:decomp3}, \end{align} where in the second equality we have used the fact that $\sum_{i=1}^I \ell_i \bar{x}_i + \delta = n$. Next, we bound the three terms separately. The first term $\mathbb{E}\left[\left(\sum_{i=1}^I \ell_i(X_i - \bar{x}_i) - \delta\right)^+ \right]$ can be rewritten as follows: \begin{align*} &\mspace{23mu} \mathbb{E}\left[\left(\sum_{i=1}^I \ell_i(X_i - \bar{x}_i) - \delta\right)^+ \right]\\ &= \int_0^\infty \mathbb{P}\left(\sum_{i=1}^I \ell_i (X_i - \bar{x}_i) - \delta \geq t\right) dt\\ &\leq \sum_{j=\lfloor \frac{\delta-\alpha_2}{\beta_2}\rfloor}^\infty \int_{\alpha_2+\beta_2 j}^{\alpha_2+\beta_2(j+1)} \mathbb{P}\left(\sum_{i=1}^I \ell_i (X_i - \bar{x}_i) \geq t\right) dt\\ &\leq \sum_{j=\lfloor \frac{\delta-\alpha_2}{\beta_2}\rfloor}^\infty \beta_2 \mathbb{P}\left(\sum_{i=1}^I \ell_i(X_i - \bar{x}_i) \geq \alpha_2 + \beta_2 \cdot j\right)\\ &\leq \sum_{j=\lfloor \frac{\delta-\alpha_2}{\beta_2}\rfloor}^\infty \beta_2 e^{-j}, \end{align*} where $\lfloor a \rfloor$ means the largest integer that is no greater than a real number $a$, and the last inequality is due to Lemma~\ref{lem:proof:total-server-need-tail}. Therefore, \begin{equation} \mathbb{E}\left[\left(\sum_{i=1}^I \ell_i(X_i - \bar{x}_i) - \delta\right)^+ \right] \leq \frac{e}{e-1}\beta_2 \exp\left(-\left\lfloor\frac{\delta-\alpha_2}{\beta_2}\right\rfloor\right), \label{eq:total-server-need-expect:bound-decomp1} \end{equation} where $e$ is the base for the natural logarithm. Next, we try to bound the second and third terms $\delta \mathbb{P}\left(\sum_{i=1}^I \ell_i X_i \geq n\right) + \mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i - \bar{x}_i) \mathbb{1}_{\{\sum_{i=1}^I \ell_i X_i < n\}}\right]$ by analyzing the Lyapunov drift of the function $f(\ve{x}) = \sum_{i=1}^I \frac{\ell_i}{\sev_i}x_i$. The drift is equal to \begin{equation*} G f(\ve{x},\ve{z}) = \sum_{i=1}^I \left(\frac{\lambda_i\ell_i}{\sev_i} - \ell_i z_i\right). \end{equation*} Because $f(\ve{x})$ is a linear function, and the system operates under an $\ell_{\max}$-work-conserving policy, by Lemma~\ref{lem:polynomial-zero-drift}, we have $\mathbb{E}\left[G f(\ve{X},\ve{Z})\right] = 0$, i.e. \begin{equation} \mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i\ell_i}{\sev_i} - \ell_i Z_i\right)\right] = 0. \end{equation} Observe that by the $\ell_{\max}$-work-conserving condition, $\sum_{i=1}^I \ell_i Z_i \geq n-\ell_{\max}$ when $\sum_{i=1}^I \ell_i X_i \geq n$, and $\sum_{i=1}^I \ell_i Z_i = \sum_{i=1}^I \ell_i X_i $ when $\sum_{i=1}^I \ell_i X_i < n$. Therefore, \[ \begin{aligned} \mspace{23mu}\mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i\ell_i}{\sev_i} - \ell_i Z_i\right)\mathbb{1}_{\{\sum_{i=1}^I \ell_i X_i \geq n\}}\right] \leq (-\delta + \ell_{\max}) \mathbb{P}\left(\sum_{i=1}^I \ell_i X_i \geq n\right), \end{aligned} \] and \[ \begin{aligned} \mspace{23mu}\mathbb{E}\left[\sum_{i=1}^I \left(\frac{\lambda_i\ell_i}{\sev_i} - \ell_i Z_i\right)\mathbb{1}_{\{\sum_{i=1}^I \ell_i X_i < n\}}\right]\leq \mathbb{E}\left[\sum_{i=1}^I \ell_i (\bar{x}_i - X_i) \mathbb{1}_{\{\sum_{i=1}^I \ell_i X_i < n\}}\right]. \end{aligned} \] Summing up the above two equations and rearranging the terms yield \begin{align} &\mspace{18mu}\mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i-\bar{x}_i) \mathbb{1}_{\{\sum_{i=1}^I \ell_i X_i < n\}}\right] + \delta \mathbb{P}\left(\sum_{i=1}^I \ell_i X_i \geq n\right) \nonumber \\ &\leq \ell_{\max} \mathbb{P}\left(\sum_{i=1}^I \ell_i X_i \geq n\right) \nonumber\\ &= \ell_{\max} \mathbb{P}\left(\sum_{i=1}^I \ell_i (X_i-\bar{x}_i) \geq \delta \right) \nonumber \\ &\leq \ell_{\max} \exp\left(-\left\lfloor\frac{\delta-\alpha_2}{\beta_2}\right\rfloor\right) \label{eq:total-server-need-expect:bound-decomp23}. \end{align} where the last inequality follows from Lemma~\ref{lem:proof:total-server-need-tail} with $j = \lfloor \frac{\delta-\alpha_2}{\beta_2}\rfloor$. Combining \eqref{eq:total-server-need-expect:bound-decomp1} and \eqref{eq:total-server-need-expect:bound-decomp23}, we finally get \begin{equation} \mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i - \bar{x}_i)\right] \leq \left(\frac{e}{e-1} \beta_2 + \ell_{\max} \right) \exp\left(-\left\lfloor\frac{\delta-\alpha_2}{\beta_2}\right\rfloor\right). \end{equation} Observe that \begin{equation} \frac{e}{e-1}\beta_2 + \ell_{\max} = O\left(\frac{n\ell_{\max}}{\delta}\right). \end{equation} Because $\delta = \wbrac{\frac{n\ell_{\max}}{\delta}\log n}$, we have $\alpha_2 = \frac{\delta}{2} + o(\delta)$. Consequently, \begin{equation} \left\lfloor\frac{\delta-\alpha_2}{\beta_2}\right\rfloor =\Omega\left( \frac{\delta^2}{n\ell_{\max}}\right). \end{equation} Therefore, \[\mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i - \bar{x}_i)\right] =O\left(\frac{n\ell_{\max}}{\delta}\right)\exp\left(-\Omega\left( \frac{\delta^2}{n\ell_{\max}}\right)\right). \] Because $\delta = \wbrac{\sqrt{n\ell_{\max}}\log n}$, we have $\exp\left(-\Omega\left( \frac{\delta^2}{n\ell_{\max}}\right)\right) \leq \exp\left(-\Wbrac{(\log n)^2}\right)$, which decays faster than any polynomial. Therefore we can omit the factor $O\left(\frac{n\ell_{\max}}{\delta}\right)$. This finishes the proof of Lemma~\ref{lem:proof:total-server-need-expectation}. \end{proof} \queueingprob* \begin{proof}[Proof of Corollary~\ref{result:queueing-probability}] Choosing $j = \lfloor\frac{\delta - \alpha_2}{\beta_2}\rfloor$ in Lemma~\ref{lem:proof:total-server-need-tail}, we have \begin{align} \mathbb{P}\left(\sum_{i=1}^I \ell_i (X_i-\bar{x}_i) \geq \alpha_2 + \beta_2 \cdot j \right) &\leq \mathbb{P}\left(\sum_{i=1}^I \ell_i (X_i-\bar{x}_i) \geq \alpha_2 + \beta_2 \cdot j \right) \\ &\leq \exp\left(-\left\lfloor\frac{\delta-\alpha_2}{\beta_2}\right\rfloor\right). \end{align} where the first inequality is because $\delta \geq \alpha_2 + \beta_2\cdot j$. Recall that $\alpha_2 = \frac{\delta}{2} + \Thebrac{\frac{n\ell_{\max}}{\delta}\log n}$, $\beta_2 = \Thebrac{\frac{n\ell_{\max}}{\delta}}$. Because we have assumed $\delta = \wbrac{\sqrt{n\ell_{\max}}\log n}$, $\alpha_2 = \frac{\delta}{2}+\obrac{\delta}$. Therefore, $\lfloor\frac{\delta-\alpha_2}{\beta_2}\rfloor = \Wbrac{\frac{\delta^2}{n\ell_{\max}}}$. This finishes the proof of Corollary~\ref{result:queueing-probability}. \end{proof} \section{Conclusion and Future Work}\label{sec:conclusion} In this paper, we have established order-wise sharp bounds on the mean waiting times of multiserver jobs under the FCFS policy and the P-Priority policy. We have also proved a lower bound of mean waiting time applicable to any policy. Those bounds imply the optimality of P-Priority and the strict sub-optimality of FCFS. Apart from the theoretical analysis, we have also demonstrated through simulations the performance improvement of P-Priority compared with FCFS in finite systems, and the fact that N-Priority, which is the non-preemptive variant of P-Priority, has comparable performance with P-Priority. There are several interesting directions for future work: (i) Derive a tighter bound on the mean waiting time under P-Priority when the commonness assumption is violated. (ii) Analyze the performance of N-Priority. (iii) Relax the maximal server need assumption (Assumption~\ref{assump:lm-bound}), which may require new policy designs to ensure stability while keeping the mean waiting time small. \section{Introduction}\label{sec:introduction} In today's large-scale computing clusters behind cloud platforms, \textit{multiserver jobs} have become increasingly prevalent, where a multiserver job is a job that demands to occupy multiple ``servers'' (which can be multiple physical servers, multiple CPU cores, etc.) simultaneously during its runtime \cite{TirBarDen_20,VerPedKor_15,LinPaoCho_18,AbaBarChe_16}. For example, cloud platforms allow users to specify the number of CPU cores in their virtual machines or containers, and this information can be utilized by centralized schedulers to make scheduling decisions (see, for example, \cite{VerPedKor_15, GKE}). Moreover, the number of ``servers'' that a multiserver job requests, which we refer to as the \textit{server need}, is becoming increasingly large. This trend is driven by machine learning jobs from applications like TensorFlow~\cite{AbaBarChe_16}, where the jobs are highly parallel and require synchronization. According to the statistics from Google's Borg Scheduler \cite{VerPedKor_15}, the server needs in Borg can vary across six orders of magnitudes. In this paper, we study the impact of multiserver jobs on the delay performance of large-scale computing systems using queueing models. Queueing models with multiserver jobs have been studied in the literature, but quantifying the delay performance is notoriously hard. Exact steady-state distributions can only be derived in highly simplified settings with two servers \cite{BriGre_84,FilKar_06}, while the majority of prior work has focused on characterizing stability conditions \cite{GroHarSch_20,AfaBasGri_19,MorRum_16,RumMor_17}. However, even for stability, exact conditions are known only for the special cases where all jobs have the same service rates or where there are two job classes. A recent advance in understanding the delay of multiserver jobs is a characterization of the \emph{queueing probability} in a large system by \citet{WanXieHar_21}, where the queueing probability is the probability that an arriving job has to queue rather than entering service immediately. Specifically, \citet{WanXieHar_21} consider a multiserver job system with $n$ servers, and study the asymptotic scaling regimes where $n$ becomes large. The scaling regimes allow different job types to have different arrival rates, server needs and service rates. Among those parameters, server needs and arrival rates can scale up with $n$. Such scaling regimes capture the trend that different multiserver jobs can be highly heterogeneous, especially in terms of server needs. \citet{WanXieHar_21} establish an upper bound on the queueing probability, based on which they give a sufficient condition for the queueing probability to diminish as $n$ goes to infinity. Although the work \cite{WanXieHar_21} identifies when the queueing probability diminishes in large systems, which is a much desirable operating scenario, it does not provide much insight for differentiating between scheduling policies. In particular, the queueing probability upper bound in \cite{WanXieHar_21} holds for any scheduling policy that is reasonably work-conserving (although the bound is presented only for the First-Come-First-Serve policy in \cite{WanXieHar_21}). Moreover, queueing probability does not directly translate to delay of jobs. In this paper, we focus on the \emph{waiting time} of jobs, which is the time a job spends waiting in the queue (not receiving any service), under various scheduling policies. The waiting time is a performance metric that is directly related to job delay. Our goal is to establish bounds on the mean waiting time that are \emph{order-wise tight} as the number of servers, $n$, scales. Such tight bounds will enable us to differentiate between policies based on their delay performance. We comment that there has been a line of work in the literature \cite{Liu_19,LiuYin_19,LiuYin_20,LiuGonYin_20,vanZubBor_20,WenWan_21,WenZhoSri_21} that focuses on quantifying when the mean waiting time diminishes in large systems for various queueing models. However, little is known on \emph{how fast} the mean waiting time diminishes due to the lack of lower bounds. Our results provide the rate of diminishing when the mean waiting time does diminish, but our tight bounds on the mean waiting time are not limited to the ``diminishing'' scenario. Since the First-Come-First-Serve (FCFS) policy is widely used as a default policy in practice and also it receives the most attention from theoretical studies of multiserver jobs \cite{BriGre_84,FilKar_06,GroHarSch_20,AfaBasGri_19,MorRum_16,RumMor_17}, we will first examine FCFS and understand the exact order of the mean waiting time under it. Then a natural question that arises is: \emph{can any policy outperform FCFS in terms of the mean waiting time?} More generally, we aim to answer the following fundamental questions: \begin{itemize} \item \emph{What is the optimal order of the mean waiting time as the system scales? \item Which policy achieves the optimal order?} \end{itemize} \subsection{Model and performance metric} We consider a system that consists of $n$ servers and $I$ types of jobs. An example is illustrated in Figure~\ref{fig:msj}. Suppose type~$i$ jobs needs the simultaneous service of $\ell_i$ servers. We sort the job types so that their \emph{server needs}~$\ell_i$'s satisfy $\ell_1 \leq \ell_2 \leq \dots \ell_I$. Let the \textit{maximal server need} $\ell_{\max}$ to be $\ell_{\max} = \max_{i\in\{1,2,\dots,I\}} \ell_i=\ell_I$, and we call type~$I$ jobs the \textit{maximal-need jobs}. The dynamics of the system are as follows. For each $i=1,2,\dots, I$, type~$i$ jobs arrive to the system following a Poisson process with \emph{arrival rate}~$\lambda_i$. Upon arrival, a job either starts service immediately or waits in a centralized queue. When the type~$i$ job job starts service, it leaves the queue and makes exclusive use of $\ell_i$ servers. The job leaves the system after receiving enough service. The service time of a type~$i$ job follows an exponential distribution with \emph{service rate}~$\sev_i$. The service times and arrival events are independent. During the operation of the system, a scheduling policy is used to determine which set of jobs to serve at each time. The scheduling policy is allowed to be preemptive, i.e., we can pause a job in the middle of its service and put it back to the queue. \begin{figure} \centering \includegraphics[width=8cm]{figs/multi-server-job-mobi-v2.pdf} \caption{A multiserver-job system with two types of jobs. Type $1$ jobs have arrival rate $\lambda_1$, service rate $\sev_1$, and server need $\ell_1 = 2$. Type $2$ jobs have arrival rate $\lambda_2$, service rate $\sev_2$, and server need $\ell_2 =3$.} \label{fig:msj} \vspace{-0.4cm} \end{figure} We measure the performance of our scheduling policy based on \textit{mean waiting time} as defined below: let $T^w_i(\infty)$ denote the waiting time of type~$i$ jobs in steady-state, then the mean waiting time is defined as the steady-state expected waiting time averaged over all job types, i.e., \begin{equation*} \E\big[T^w(\infty)\big]=\frac{1}{\lambda}\sum_{i=1}^I \lambda_i \mathbb{E}\left[T^w_i(\infty)\right], \end{equation*} where $\lambda \triangleq \sum_{i=1}^I \lambda_i$ is the total arrival rate. \subsection{Scaling regimes}\label{subsec:intro-scaling} We study job delay in scaling regimes where the number of servers, $n$, goes to infinity. Specifically, we consider a sequence of systems with parameters scaling up jointly with $n$, and analyze the growth/decrease rate of mean waiting times. In the considered scaling regimes, the arrival rates $\lambda_i$ and server needs $\ell_i$ are allowed to scale with $n$, while the service rate $\sev_i$ and the number of job types $I$ stay constant. One key parameter for specifying a scaling regime is the \textit{slack capacity} $\delta$, defined as $\delta= n - \sum_{i=1}^I \frac{\lambda_i \ell_i}{\sev_i}$, which is the expected number of idle servers in steady state. Slack capacity is used to specify the heaviness of traffic, which is alternatively specified by \emph{load} $\rho$ given by $\rho=\sum_{i=1}^I \frac{\lambda_i\ell_i}{n\sev_i}$ in literature. \begin{figure} \centering \includegraphics[width=6cm]{figs/traffic-v2.pdf} \caption{Scaling regimes under the special parameterization with slack capacity $\delta = n^\alpha$ and maximum server need $\ell_{\max} = n^\gamma$. The traffic is heavier as we move to the upper left. The three triangles are partitioned by lines $\gamma=\alpha$ and $\alpha=\frac{1+\gamma}{2}$.} \label{fig:traffic} \end{figure} For expositional purposes, here we parameterize the scaling regimes in the following way: $\ell_{\max} = n^\gamma$, $\delta = n^\alpha$ for some exponents $0\leq \alpha, \gamma < 1$. We assume that the total arrival rate $\lambda = \Theta(n)$. Note that the scaling regimes we study in this paper are more general, and we refer the readers to Section~\ref{sec:model} for full details. We aggregate all scaling regimes with the same $(\alpha, \gamma)$ pair into one point and plot out all such points, as shown in Figure~\ref{fig:traffic}. We partition the set of exponent pairs $(\alpha, \gamma)\in [0,1)^2$ into three triangles, using the lines $\alpha=\gamma$ and $\alpha = \frac{1+\gamma}{2}$. The corresponding scaling regimes to the upper left are in general ``heavier'' than the scaling regimes to the lower right, since the former regimes have larger work variability and smaller slack capacity. We comment that the point $(\alpha, \gamma) = (\frac{1}{2}, 0)$ is analogous to the celebrated Halfin-Whitt regime \cite{HalWhi_81} and $(\alpha, \gamma) = (0,0)$ is analogous to the Non-Degenerate Slowdown (NDS) regime \cite{Ata_12} in traditional multiclass M/M/$n$ models. We focus on the scaling regimes where $\gamma < \alpha < \frac{1+\gamma}{2}$, marked in blue in Figure~\ref{fig:traffic}. The scaling regimes satisfying the condition are not too light; the lighter regimes marked in white, studied in \cite{WanXieHar_21}, can be shown to have both queueing probability and mean waiting time diminish at a rate faster than any polynomial in $n$ under any reasonably work-conserving policy. Meanwhile, the regimes under consideration are not too heavy either; the system still enjoys diminishing mean waiting time together with high system utilization. \subsection{Results} We present our main results here in the specialized scaling regimes for expositional purposes. The general forms with fully specified assumptions are presented in Sections~\ref{sec:model} and \ref{sec:main-results}. Our results and analysis heavily use the asymptotic notation. \footnote{We use the standard Bachmann–Landau notation. Consider two sequences $a(n)$ and $b(n)$ (or simply $a$ and $b$), where $b(n)$ is positive for large enough $n$. Then $a = \Obrac{b}$ if $\limsup_{n\to\infty}\frac{|a|}{b}<\infty$; $a = \obrac{b}$ if $\lim_{n\to\infty} \frac{a}{b} = 0$; $a = \Wbrac{b}$ if $\liminf_{n\to\infty}\frac{a}{b}>0$, which is equivalent to $b = \Obrac{a}$; $a = \wbrac{b}$ if $\lim_{n\to\infty} \frac{\abs{a}}{b} = \infty$, which is equivalent to $b = \obrac{a}$; $a = \Thebrac{b}$ if $a$ satisfies both $a = \Obrac{b}$ and $a = \Wbrac{b}$.} \begin{itemize}[leftmargin=1em] \item\textbf{Mean waiting time under FCFS.} The exact order of the mean waiting time under FCFS is given by \begin{equation} \E\big[T^w(\infty)\big]^{\textnormal{FCFS}} = \Thebrac{n^{\gamma-\alpha}}. \end{equation} \item\textbf{Mean waiting time lower bound.} Under any policy, the mean waiting time is lower bounded as \begin{equation}\label{eq:lower-intro} \E\big[T^w(\infty)\big] = \Wbrac{n^{-\alpha}}, \end{equation} \item\textbf{Order-wise optimal policy.} Consider a static priority policy that we call the \emph{P-Priority policy}, which preemptively prioritizes the jobs with smaller server needs. Then the mean waiting time under P-Priority achieves the lower bound in \eqref{eq:lower-intro}, i.e., \begin{equation}\label{eq:pp-intro} \E\big[T^w(\infty)\big]^{\textnormal{P-Priority}} = \Thebrac{n^{-\alpha}}. \end{equation} Therefore, the P-Priority policy is order-wise optimal in the mean waiting time. \end{itemize} Comparing the mean waiting time under FCFS and under P-Priority, we can see that FCFS is strictly suboptimal, and P-Priority improves upon FCFS by a factor of $\Thebrac{n^{\gamma}}$. A key to proving the mean waiting time results above is the \emph{order-wise tight} bounds on the expected workload we establish (Lemma~\ref{result:workload-lower} and Lemma~\ref{result:workload-upper}). In addition, although we consider the system under the traffic regime where $\gamma < \alpha < \frac{1+\gamma}{2}$, we still need to analyze ``subsystems'' that are in the lighter traffic regime. In this lighter regime, we show that the total server need decays faster than any polynomial (Lemma~\ref{lem:proof:total-server-need-expectation}). All these lemmas hold under a very general class of policies, so they could be potentially relevant when we study policies other than FCFS and P-Priority. \subsubsection*{\textbf{Results on queueing probability}} As a by-product to our analysis, we further derive an upper bound on the queueing probability under a work-conserving policy, presented in Corollary~\ref{result:queueing-probability}, which significantly improves upon the queueing probability upper bound in \cite{WanXieHar_21} in a slightly more constrained traffic regime. \subsubsection*{\textbf{Simulation experiments}} The P-Priority policy we consider in our analysis is a \emph{preemptive} policy, but preemption is usually not preferable in practice. Therefore, we use simulation experiments to explore a \emph{non-preemptive} version of the priority policy, which we call the N-Priority policy. N-Priority serves a job with the smallest server need in the queue when enough number of servers free up. Our simulation experiments compare the mean waiting time under FCFS, P-Priority, and N-Priority. The simulation results, presented in Section~\ref{sec:simulation}, show that N-Priority has comparable performance with P-Priority, and demonstrate the performance gap between FCFS and P-Priority/N-Priority. \subsection{Technical challenges} The main technical challenges in analyzing the considered multi-server-job system are rooted in the \emph{heterogeneity} among job types in both their service rates and their server needs. Such heterogeneity makes the system dynamics multidimensional: neither the total number of jobs in service nor the total number of busy servers determines the current job departure rate. We comment that even for a classical multi-class M/M/$n$ system, where there are multiple job types with different service rates but all job types have a server need of $1$, finding an optimal scheduling policy is known to be a hard problem, and solutions are available mostly in the so-called Halfin-Whitt heavy-traffic regime through the diffusion control problem \cite{AtaManRei_04, HarZee_04, AtaGur_12}. Compared with the classical multi-class M/M/$n$ system, our multiserver-job system has an additional layer of intricacy due to the heterogeneous server needs, which makes it possible for the system to have servers idling while there are jobs waiting in the queue. To address the challenges due to heterogeneity, our analysis relies on various state-space concentration results. State-space concentration is a phenomenon where the state concentrates around a \emph{subset} of the state space in steady state, observed in queueing systems in heavy-traffic or large-system regimes \cite{WanMagSri_17, Liu_19, LiuYin_19, LiuYin_20, LiuGonYin_20, WenZhoSri_21} In the multiserver-job system we consider, state-space concentration results are crucial for analyzing the system dynamics when the queue is nonempty. The scenario when the queue is nonempty is especially important to our scaling regimes since the queueing probability may not be diminishing even when the mean waiting time is diminishing. This contrasts with the analysis in prior work \cite{WanXieHar_21}, which focuses on diminishing queueing probability. Furthermore, our performance goal is to achieve the \emph{optimal order} of the mean waiting time in large systems, which deviates from the traditional performance goal of minimizing delay or certain long-run cost. \section{Model}\label{sec:model} A basic description of the system parameters and dynamics has been given in the introduction section. In this section, we provide formal descriptions of the scheduling policies, the system states, the scaling regime, and the concept of subsystems used in our analysis. \subsubsection*{\textbf{Scheduling policies}} A scheduling policy decides which jobs to put into service at any moment of time. We are interested in the following two policies: \begin{itemize}[leftmargin=1em] \item \emph{First-Come-First-Serve (FCFS)}: Jobs are placed onto servers in a First-Come-First-Serve fashion until either the next job in queue does not fit or all the jobs are in service. \item \emph{Preemptive Priority (P-Priority)}: Recall that the job types are indexed in a way such that $\ell_1\leq \ell_2\leq \dots \leq \ell_I$. We assign priorities to job types such that a smaller index has a higher priority. Whenever there is a job arrival or departure, P-Priority preempts all the jobs in service and determines a new schedule from scratch. P-Priority starts from job type~$1$ and places as many type~$1$ jobs as possible onto servers. After this, if there are still servers available, P-Priority goes to the next priority level, type~$2$, and places as many type~$2$ jobs as possible onto servers. This procedure continues until no more jobs in the queue can fit into the servers. \end{itemize} \subsubsection*{\textbf{System state}} Under FCFS or P-Priority, a Markovian representation of the system state can be described as follows. The state $\ve{u}$ of the Markov chain is an ordered list of the jobs in the system, sorted in their order of arrival, and each entry of $\ve{u}$ describes the type of the corresponding job and whether the job is in service or not. Let the state space be denoted as $\mathcal{U}$. Although the state space is infinite dimensional, in our analysis, we typically only need to focus on three $I$-dimensional vectors defined below. For any time $t$ and each job type~$i$, let $X_i(t)$ denote the number of type~$i$ jobs in the system, $Z_i(t)$ denote the number of type~$i$ jobs in service, and $Q_i(t)\triangleq X_i(t)-Z_i(t)$ denote the number of type~$i$ jobs waiting in the queue. Note that since the total number of servers in use cannot exceed $n$, and we cannot serve more jobs than there are in the system, we have the following constraints: \begin{equation}\label{eq:assump:job-constraints} \begin{aligned} \sum_{i=1}^I \ell_i Z_i(t) &\le n \quad\text{for all }t\geq 0,\\ Z_i(t) &\leq X_i(t) \quad \text{for all } t\geq 0, i\in[I], \end{aligned} \end{equation} where $[I]$ denotes the index set $\{1,2, \dots, I\}$. Let $X_i(\infty)$, $Z_i(\infty)$, and $Q_i(\infty)$ be random variables that follow the corresponding steady-state distributions when they exist. We sometimes use vector representations of these quantities for convenience. For example, we write $\ve{X}(t)=\left(X_1(t),X_2(t),\dots,X_I(t)\right)$. We define the vectors $\ve{Z}(t)$, $\ve{Q}(t)$, $\ve{X}(\infty)$, $\ve{Z}(\infty)$, and $\ve{Q}(\infty)$ in a similar way. Note that these random elements correspond to the $n$ server system and thus their distributions depend on $n$. Throughout this paper, for conciseness, we often omit the $(\infty)$ in the steady-state random elements except in theorem or lemma statements. Recall that our performance metric is the mean waiting time $\E\big[T^w(\infty)\big]$, given by $$\E\big[T^w(\infty)\big]=\frac{1}{\lambda}\sum_{i=1}^I \lambda_i \mathbb{E}\big[T^w_i(\infty)\big],$$ where $T^w_i(\infty)$ is the waiting time of type~$i$ jobs in steady-state. Note that by Little's law, the mean waiting time can be written as \begin{equation*} \E\big[T^w(\infty)\big]=\frac{1}{\lambda}\sum_{i=1}^I\mathbb{E}\left[Q_i(\infty)\right]. \end{equation*} Therefore, bounding the mean waiting time reduces to bounding the expected total queue length. \subsubsection*{\textbf{Scaling regimes}} Recall that we consider a scaling regimes where number of servers, $n$, goes to infinity, and the arrival rates $\lambda_i$ and server needs $\ell_i$ are allowed to scale with $n$, \textit{while the service rate $\sev_i$ and the number of job types $I$ stay constant}. The scaling regimes are specified by the slack capacity $\delta\triangleq n - \sum_{i=1}^I \frac{\lambda_i \ell_i}{\sev_i}$, the maximal server need $\ell_{\max} \triangleq\max_{i\in[I]} \ell_i=\ell_I$ and another parameter called the \textit{work variability}: $\sigma^2 \triangleq \sum_{i=1}^I \frac{\lambda_i \ell_i^2}{\sev_i^2}$. Work variability reflects the variability of the ``work'' caused by job arrivals in terms of server--time product, which is $\frac{\ell_i}{\sev_i}$ in expectation for each type~$i$ job. To help later presentation, we also define the \emph{load brought by type~$i$ jobs} $\rho_i$ as $\rho_i = \frac{\lambda_i \ell_i}{n\sev_i}$. We state our assumptions below. Note that throughout this paper, $\log n$ denotes natural logarithm. \begin{assump}[Heavy traffic assumption]\label{assump:traffic} The slack capacity $\delta$ is small compared with $\sqrt{\sigma^2}$: \begin{equation}\label{eq:assump:traffic} \delta=o\left(\frac{\sqrt{\sigma^2}}{\log n}\right). \end{equation} \end{assump} \begin{assump}[Maximal server need assumption]\label{assump:lm-bound} There exists a constant $\epsilon_0$ with $0 < \epsilon_0 < 1$ such that \begin{equation}\label{eq:assump:lm-bound} \ell_{\max} \leq \epsilon_0 \delta. \end{equation} \end{assump} \begin{assump}[Commonness assumption]\label{assump:commonness} The load brought by the maximal-need jobs is not too small: \begin{equation}\label{eq:assump:commonness} \rho_{I} \triangleq \frac{\lambda_{I}\ell_{I}}{n\sev_{I}} = \wbrac{\sqrt{\frac{\delta \log n}{\sqrt{\sigma^2} }\cdot \frac{\ell_{\max}}{n}}\log n}. \end{equation} \end{assump} The heavy traffic assumption guarantees that the traffic is not too light, while the maximal server need assumption guarantees that the system is stable under FCFS and P-Priority. The commonness assumption assumes that the load brought by the maximal-need jobs are not too small. To understand the right hand side expression in the commonness assumption, note that it is automatically satisfied when $\rho_{I} = \wbrac{\sqrt{\ell_{\max}/n}\log n}$. For example, when $\ell_{\max} = \Thebrac{\sqrt{n}}$, then it suffices to have $\rho_{I} = \wbrac{n^{-1/4}\log n}$. However, when the traffic becomes heavier, i.e., when $\frac{\delta \log n}{\sqrt{\sigma^2} }$ becomes smaller, the commonness assumption in \eqref{eq:assump:commonness} can be much weaker than $\rho_{I} = \wbrac{\sqrt{\ell_{\max}/n}\log n}$. In the simplified setting of Section~\ref{sec:introduction} where $\ell_{\max}=n^\gamma$ and $\delta=n^\alpha$, the first two assumptions correspond to $\alpha < \frac{1+\gamma}{2}$ and $\alpha > \gamma$, respectively. To have an intuitive view of the magnitudes of the parameters, we give the following asymptotics: $\sigma^2 = \Obrac{n\ell_{\max}}$, $\delta = \obrac{n / (\log n)^2}$, and $\ell_{\max} \leq \epsilon_0 \delta = \obrac{n / (\log n)^2}$. They can be verified using the definitions and assumptions. \subsubsection*{\textbf{Subsystems}} In our analysis, we frequently use the concept of the $i$-th \emph{subsystem}, which is the system that has all type~$j$ jobs in the original system with $j\leq i$ and removes all type~$k$ jobs with $k\geq i$. In the $i$-th subsystem, the slack capacity becomes $\delta_i = n - \sum_{j=1}^i \frac{\lambda_j \ell_j}{\sev_j}$, and the work variability becomes $\sigma^2_i = \sum_{j=1}^i \frac{\lambda_j \ell_j^2}{\sev_j^2}$. Note that $\delta = \delta_{I}$ and $\sigma^2_{I} = \sigma^2$. The maximal server need in the $i$-th system is $\ell_i$ since $\ell_1 \leq \ell_2 \leq \dots \le \ell_i$. As $i$ increases, the load of the $i$-th subsystem gets heavier since $\delta_i$ becomes smaller. There is a \emph{critical index} $\indexmain$ such that \begin{equation}\label{eq:istar} \indexmain = \min\left\{i\in[I]\;\middle|\; \delta_i=\obrac{\frac{\sqrt{\sigma^2_i}}{\log n}}\right\}, \end{equation} i.e., the $\indexmain$th subsystem is the smallest subsystem whose traffic regime is as heavy as that of the original system. Recall that we have assumed $\delta=\obrac{\frac{\sqrt{\sigma^2}}{\log n}}$, so the set in \eqref{eq:istar} contains at least the index $I$ and thus $\indexmain$ is well-defined. Note that $\delta_i$ is monotonically decreasing while $\sigma^2_i$ is monotonically increasing. Thus the index $\indexmain$ serves as a division point: for any $i$ with $\indexmain \leq i \leq I$, we have $\delta_i = \obrac{\frac{\sqrt{\sigma^2_i}}{\log n}}$, resulting in a lighter traffic regime; and for any $i$ with $1 \leq i < \indexmain$, we have $\delta_i = \Wbrac{\frac{\sqrt{\sigma^2_i}}{\log n}}$, resulting in a heavier traffic regime. \section{Main results}\label{sec:main-results} In this section, we first present our main results under the scaling regimes we specify in Section~\ref{sec:model} as Theorems~\ref{result:waiting-time-fcfs}, \ref{result:waiting-time-lower-bound}, and \ref{result:waiting-time-priority}. Then, to demonstrate our results in a more intuitive fashion, we consider the parameterized scaling regimes defined in Section~\ref{subsec:intro-scaling} as a special case, and present the specialized form of our results as Corollary~\ref{coro:parameterized}. \begin{restatable}[Mean waiting time under FCFS]{thm}{waitingfcfs}\label{result:waiting-time-fcfs} Consider the multiserver-job system with $n$ servers satisfying Assumptions~\ref{assump:traffic} and \ref{assump:lm-bound}. Under the FCFS policy, for each $i\in [I]$, the expected waiting time of type~$i$ jobs satisfies \begin{align} \mathbb{E}\big[T^w_i(\infty)\big]^\textnormal{FCFS} & \ge \frac{\sigma^2}{n(\delta+\ell_{\max})}\cdot \left(1-o(1)\right),\\ \mathbb{E}\big[T^w_i(\infty)\big]^\textnormal{FCFS} & \leq \frac{\sigma^2}{n(\delta-\ell_{\max})} \cdot \left(1+o(1)\right). \end{align} Consequently, \begin{equation} \E\big[T^w(\infty)\big]^\textnormal{FCFS} = \Thebrac{\frac{\sigma^2}{n\delta}}, \quad \mathbb{E}\big[T^w_i(\infty)\big]^\textnormal{FCFS} = \Thebrac{\frac{\sigma^2}{n\delta}}. \end{equation} \end{restatable} \begin{restatable}[Mean waiting time lower bound]{thm}{waitinglower}\label{result:waiting-time-lower-bound} Consider the multiserver-job system with $n$ servers satisfying Assumptions~\ref{assump:traffic} and \ref{assump:lm-bound}. Under any policy, the mean waiting time is lower bounded as \begin{equation}\label{eq:result:mean-waiting-time-lower-bound} \begin{split} \E\big[T^w(\infty)\big] &\geq \max_{\indexmain \leq i \leq I} \frac{1}{\lambda} \frac{\sev_{\min}\sigma^2_i}{\ell_i \delta_i} \cdot (1 - o(1)) \\ &= \Wbrac{\max_{\indexmain \leq i \leq I}\frac{1}{\lambda} \frac{\sigma^2_i}{\ell_i \delta_i}}, \end{split} \end{equation} where $\indexmain$ is the critical index defined in \eqref{eq:istar} and $\sev_{\min}=\min_{i\in[I]}\sev_i$, and the expression represented by $o(1)$ is independent of the policies. \end{restatable} \begin{restatable}[Mean waiting time under P-Priority]{thm}{waitingpriority}\label{result:waiting-time-priority} Consider the multiserver-job system with $n$ servers satisfying Assumptions~\ref{assump:traffic}, \ref{assump:lm-bound}, and \ref{assump:commonness}. Under the P-Priority policy, the mean waiting time satisfies \begin{equation}\label{eq:result:mean-waiting-time-priority} \begin{aligned} \E\big[T^w(\infty)\big]^\textnormal{P-Priority} &\leq \frac{1}{\lambda} \sum_{i=\indexmain}^I \frac{\sev_{\max} \sigma^2_i}{\ell_i (\delta_i - \ell_i)} \cdot \left(1+o(1)\right)\\ &=\Obrac{\max_{\indexmain \leq i \leq I}\frac{1}{\lambda} \frac{\sigma^2_i}{\ell_i \delta_i}}, \end{aligned} \end{equation} where $\indexmain$ is the critical index defined in \eqref{eq:istar} and $\sev_{\max}=\max_{i\in[I]}\sev_i$. Consequently, the P-Priority policy achieves the optimal order of the mean waiting time. \end{restatable} We have a more general bound for P-Priority policy that holds without Assumption~\ref{assump:commonness}. Interested readers can refer to the appendices of our technical report \cite{HonWan_21}. Below we state the results appearing in Section~\ref{sec:introduction} as direct consequences to the above theorems. \begin{cor}[Mean waiting times in the parameterized scaling regimes]\label{coro:parameterized} Consider the multiserver-job system with $n$ servers satisfying Assumptions~1, 2 and 3. Suppose the maximal server need $\ell_{\max} = n^\gamma$ and the slack capacity $\delta = n^\alpha$, then the assumptions simplify to $0\leq\gamma < \alpha < \frac{1+\gamma}{2}<1$, $\rho_I = \Thebrac{1}$. We further assume that the total arrival rate $\lambda = \Theta(n)$. Then we have the following results: \begin{enumerate}[label=(\alph*)] \item Under the FCFS policy, for each $i\in[I]$, the expected waiting time of type~$i$ jobs satisfies \begin{equation} \mathbb{E}\big[T^w_i(\infty)\big]^\textnormal{FCFS} = \Thebrac{n^{\gamma - \alpha}}, \end{equation} and the mean waiting time over all job types also satisfies \begin{equation} \E\big[T^w(\infty)\big]^\textnormal{FCFS} = \Thebrac{n^{\gamma - \alpha}}. \end{equation} \item Under any policy, the mean waiting time is lower bounded as \begin{equation} \E\big[T^w(\infty)\big] = \Wbrac{n^{ - \alpha}}, \end{equation} where the expression represented by $\Wbrac{n^{-\alpha}}$ is independent of the policies. \item The mean waiting time under the P-Priority policy satisfies \begin{equation} \E\big[T^w(\infty)\big]^\textnormal{P-Priority} = \Thebrac{n^{ - \alpha}}. \end{equation} \end{enumerate} \end{cor} \section{Proof Roadmap and Drift method preliminaries}\label{sec:drift-prelim} We organize our proofs of the main results as follows: we first prove two important bounds for a quantity called \textit{workload} given by $\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i$, in Lemma~\ref{result:workload-lower} and Lemma~\ref{result:workload-upper}, respectively. Then we convert the workload bounds to the waiting time bounds in Theorem~\ref{result:waiting-time-fcfs} and Theorem~\ref{result:waiting-time-lower-bound} using properties of FCFS and a linear programming relaxation. For Theorem~\ref{result:waiting-time-priority}, we analyze P-Priority by considering each $i$-th subsystems for $i\in[I]$. Some subsystems only need Lemma~\ref{result:workload-lower} and \ref{result:workload-upper}, while others require an additional Lemma~\ref{lem:proof:total-server-need-expectation}. Our proof approach is closely related to the recently developed drift method \cite{ErySri_12, MagSri_16}. The drift method allows us to extract information from a continuous-time Markov chain $\{\ve{S}(t)\}_{t\geq 0}$ on state-space $\mathcal{S}$ by computing the \textit{drift} of different test functions. Specifically, let $f: \mathcal{S} \to \mathbb{R}$ be a function from the state space $\mathcal{S}$ to real numbers. The \textit{drift} of a function $f$ is defined as \begin{equation} G f(\ve{s}) \triangleq \lim_{t\to 0}\mathbb{E}\left[\frac{f\left(\ve{S}(t)\right) - f(\ve{s})}{t} \;\middle|\; \ve{S}(0)=\ve{s}\right]. \end{equation} We call the operator $G$ the \textit{generator} of the Markov chain. For a multiserver-job system, let $I$-dimensional real vectors $\ve{x}, \ve{z} \in \mathbb{R}^I$ be possible realizations of state descriptors $\ve{X}(t)$ and $\ve{Z}(t)$, where recall that $\ve{X}(t)$ is the vector of the number of jobs in the system at time $t$, and $\ve{Z}(t)$ is the vector of the number of jobs in service at time $t$. We focus on $f$ that only depends on $\ve{x}$, i.e., $f: \mathbb{R}^I \to \mathbb{R}$. The drift of $f$ is of the form \begin{equation}\label{eq:proof:drift-form} G f(\ve{x}, \ve{z}) = \sum_{i=1}^I \lambda_i \left(f(\ve{x}+ \ve{e}_i) - f(\ve{x})\right)+ \sum_{i=1}^I \sev_i z_i \left(f(\ve{x}-\ve{e}_i) - f(\ve{x})\right), \end{equation} where $\ve{e}_i \in \mathbb{R}^I$ is the vector whose $i$-th entry is $1$ and all the other entries are $0$. Note that although $f$ and $G f$ are functions of the system state $\ve{u}$, we write $f(\ve{x})$ and $G f(\ve{x},\ve{z})$ to highlight the variables that affect their values. We frequently use the following relation regarding the drift \begin{equation}\label{eq:proof:drift-method-master} \mathbb{E}[G f(\ve{X},\ve{Z})] = 0. \end{equation} Heuristically, this is because when $\ve{X}(0)$ and $\ve{Z}(0)$ follow the stationary distribution, $\ve{X}(t)$ and $\ve{Z}(t)$ also follow the stationary distribution, so $f(\ve{X}(t))$ and $f(\ve{X}(0))$ have the same expectation. Rigorously speaking, this relation only holds for well behaved functions and Markov processes. The conditions under which the relation holds are discussed in detail in our technical report \cite{HonWan_21}. Throughout the paper, we assume \eqref{eq:proof:drift-method-master} holds for all $f$ that we consider. \section{Workload bounds}\label{sec:workload-bounds} In this section, we prove two bounds for a quantity called \textit{workload} given by $\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i$. These bounds are fundamental to the proofs of the main theorems. In Lemma~\ref{result:workload-lower}, we give a lower bound on the expected workload applicable to \emph{any policy}. In Lemma~\ref{result:workload-upper}, we give upper bounds on the expected workload under any \emph{$\wst$-work-conserving policy}, a class of policies defined in Definition~\ref{def:work-conserving}. The proof sketches of Lemma~\ref{result:workload-lower} and Lemma~\ref{result:workload-upper} are given in this section, and the complete proofs are provided in the appendices of \cite{HonWan_21}. \begin{restatable}[Workload lower bound]{lem}{workloadlower}\label{result:workload-lower} Consider the multiserver-job system with $n$ servers satisfying Assumptions \ref{assump:traffic} and \ref{assump:lm-bound}. Under any policy, the expected workload is lower bounded as \begin{equation}\label{eq:result:workload-lower} \mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i(\infty)\right] \geq \frac{\sigma^2}{\delta} \cdot (1 - o(1)), \end{equation} where the expression represented by $o(1)$ is independent of the policies. \end{restatable} \begin{defn}\label{def:work-conserving} We call a policy $\wst$-work-conserving, if the following equation holds \begin{equation} \sum_{i=1}^I \ell_i Z_i(t) \geq \min\left(\sum_{i=1}^I \ell_i X_i(t), n - \wst \right) \quad \forall t\geq 0 . \end{equation} \end{defn} Here $\sum_{i=1}^I \ell_i Z_i(t)$ is equal to the number of busy servers at time~$t$, while $\sum_{i=1}^I \ell_i X_i(t)$, which we call the \textit{total server need}, is the potential number of busy servers if we can put all jobs at time $t$ into service. Therefore, under a $\wst$-work-conserving policy, either all jobs are in service, or there are at most $\wst$ idling servers. Under any $\ell_{\max}$-work-conserving policy, one can show that the system is stable when $\ell_{\max} \leq \epsilon_0 \delta$ (Assumption~\ref{assump:lm-bound}) holds. In particular, the system is stable under both FCFS and P-Priority. \begin{restatable}[Workload upper bound]{lem}{workloadupper}\label{result:workload-upper} Consider the multiserver-job system with $n$ servers under a $\wst$-work-conserving policy with $\wst \leq \epsilon_0 \delta$, where $ \epsilon_0 \in (0,1)$ is the parameter in Assumption~\ref{assump:lm-bound}. Then when $\delta = \obrac{\frac{\sqrt{\sigma^2}}{\log n}}$, \begin{equation}\label{eq:result:workload-upper-case1} \mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i(\infty) \right] \leq \frac{\sigma^2}{\delta - \wst} \cdot (1 + o(1)) = \Obrac{\frac{\sigma^2}{\delta}}; \end{equation} when $\delta = \Wbrac{\frac{\sqrt{\sigma^2}}{\log n}}$, \begin{equation}\label{eq:result:workload-upper-case2} \mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i(\infty) \right] = \Obrac{\sqrt{\sigma^2}\log n}. \end{equation} \end{restatable} \begin{remark*} When Assumption~\ref{assump:traffic} is satisfied, i.e., when $\delta = \obrac{\frac{\sqrt{\sigma^2}}{\log n}}$, the workload upper bound in Lemma~\ref{result:workload-upper} coincides with the workload lower bound in Lemma~\ref{result:workload-lower} order-wise, which implies that the expected workload $\mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i(\infty) \right] = \Thebrac{\frac{\sigma^2}{\delta}}$. Note that in this case, although the expected workload under all $\wst$-work-conserving policies has the same order, the mean waiting time can vary among policies, as shown for FCFS and P-Priority in Theorems~\ref{result:waiting-time-fcfs} and \ref{result:waiting-time-priority}. \end{remark*} \subsubsection*{\textbf{Preliminaries for proving Lemma~\ref{result:workload-lower} and Lemma~\ref{result:workload-upper}}} Our proofs focus on bounding the \textit{normalized work}, defined as \[ \overline{W} \triangleq \sum_{i=1}^I \frac{\ell_i}{\sev_i} \left(X_i - \bar{x}_i\right), \] where we write $\bar{x}_i \triangleq \frac{\lambda_i}{\sev_i}$ for notational simplicity. We claim that normalized work has the same expectation as the workload, i.e., $\mathbb{E}[\overline{W}] = \mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i\right]$. To see this, recall that $Q_i=X_i-Z_i$. Now consider the drift of $X_i$, given by $G X_i=\lambda_i-\sev_i Z_i$. One can verify that $X_i$ satisfies $\mathbb{E}[G X_i]=0$, and thus $\mathbb{E}[Z_i]=\frac{\lambda_i}{\sev_i}$. Therefore, the expected workload can be written as: \begin{equation} \mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i} Q_i\right] = \mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i}\left(X_i - Z_i\right)\right] =\mathbb{E}\left[\sum_{i=1}^I \frac{\ell_i}{\sev_i}\left(X_i - \bar{x}_i\right)\right] = \mathbb{E}[\overline{W}]. \end{equation} Therefore, bounding the expected workload is equivalent to bounding the steady-state expectation of the normalized work $\mathbb{E}[\overline{W}]$. We break $\mathbb{E}[\overline{W}]$ into three terms: \begin{equation} \mathbb{E}[\overline{W}] = \bar{r} + \mathbb{E}[(\overline{W} - \bar{r})^+] - \mathbb{E}[(\overline{W} - \bar{r})^-], \end{equation} where $\bar{r} \in \mathbb{R}$ is up to our choice; $(\overline{W} - \bar{r})^+ \triangleq \max\{\overline{W} - \bar{r}, 0\}$ denotes the positive part, and $(\overline{W} - \bar{r})^- \triangleq -\min \{\overline{W} - \bar{r}, 0\}$ denotes the negative part. The major difficulty during the proofs is bounding the expectation of the positive part $\mathbb{E}[(\overline{W} - \bar{r})^+]$. This relies on the relation that $\mathbb{E}[G f(\ve{X}, \ve{Z})] = 0$ as introduced in Section~\ref{sec:drift-prelim}. In our proofs, we choose $f$ to be piecewise quadratic functions to get bounds on the term \[ \mathbb{E}\left[\sum_{i=1}^I \ell_i \left( Z_i-\bar{x}_i\right)\cdot (\overline{W}-\bar{r})^+\right]. \] Since $\sum_{i=1}^I \ell_i (Z_i - \bar{x}_i) = \sum_{i=1}^I \ell_i Z_i - n+\delta$, we will be able to bound $\mathbb{E}[(\overline{W} - \bar{r})^+]$ if we are able to give an accurate estimate of the number of busy servers $\sum_{i=1}^I \ell_i Z_i$ when the normalized work $\overline{W} \geq \bar{r}$. To get a precise estimate, we exploit the state-space concentration result that says for each $i\in[I]$, $X_i$ cannot be much smaller than $\bar{x}_i$, i.e., $(X_i - \bar{x}_i)^-$ is small with high probability. Formally, this state-space concentration is established by Lemma~\ref{lem:mminf-bounds}, whose proof uses a sample-path coupling argument and is given in \cite{HonWan_21}. \begin{restatable}{lem}{mminfbounds}\label{lem:mminf-bounds} Consider the multiserver-job system with $n$ servers. For any nonnegative vector $c = (c_1, \dots, c_I)\in\mathbb{R}^{I}_+$ independent of $n$, let $c_{\max}=\max_{i\in[I]} c_i$, $\sev_{\max} = \max_{i\in[I]} \sev_i$ and let \begin{equation*} \Phi=\sum_{i=1}^I c_i \ell_i\left(X_i(\infty)-\bar{x}_i\right), \end{equation*} where $\bar{x}_i = \frac{\lambda_i}{\sev_i}$. Then we have the three bounds below. \begin{enumerate}[label=(\alph*)] \item For any $K \geq 0$, \begin{equation} \mathbb{P}\left(\Phi \leq -K \right) \leq \exp\left(-\frac{K^2}{2c_{\max}^2 \sev_{\max} \sigma^2}\right). \end{equation} \item For any $\alpha\ge 0$ and $\beta \geq 0$ such that $\alpha\beta \geq c_{\max}^2\sev_{\max} \sigma^2$ and any $j\ge 0$, \begin{equation} \mathbb{P}\left(\Phi \leq - \alpha - \beta j \right) \leq e^{-j}. \end{equation} \item Let $\Phi^-=\max\left\{-\Phi,0\right\}$ to be the negative part of $\Phi$. Then \begin{equation} \mathbb{E}\left[\Phi^-\right] \leq \sqrt{c_{\max}^2 \sev_{\max} \sigma^2}. \end{equation} \end{enumerate} \end{restatable} Next, we give the proof sketches of Lemma~\ref{result:workload-lower} and Lemma~\ref{result:workload-upper}. \subsubsection*{\textbf{Proof sketch of Lemma~\ref{result:workload-lower} (workload lower bound)}} Recall that $\mathbb{E}[\overline{W}] = \bar{r}_1 + \mathbb{E}[(\overline{W} - \bar{r}_1)^+] - \mathbb{E}[(\overline{W} - \bar{r}_1)^-]$, for some scalar $\bar{r}_1$ to be specified later. To bound the positive part, we invoke the relation $\mathbb{E}[G f(\ve{X}, \ve{Z})]=0$ for a carefully constructed function $f(x)$ and get \begin{equation} \mathbb{E}\left[\sum_{i=1}^I \ell_i \left( Z_i-\bar{x}_i\right)\cdot (\overline{W}-\bar{r}_1)^+\right] \geq \sigma^2 - \Obrac{n\ell_{\max}} \mathbb{P}\left(\overline{W} \leq \bar{r}_1 + \frac{\ell_{\max}}{\sev_{\min}}\right). \end{equation} According to Lemma~\ref{lem:mminf-bounds} (a) with $\Phi = \overline{W}$, we can choose some $\bar{r}_1 = -\Obrac{\sqrt{\sigma^2} \log n + \ell_{\max}}$ such that the probability on the right hand side is bounded by $\frac{1}{n^2}$. Moreover, observe that $\sum_{i=1}^I \ell_i \left( Z_i-\bar{x}_i\right) \leq n - (n-\delta) = \delta$, we get \begin{equation} \mathbb{E}[(\overline{W} - \bar{r}_1)^+] \geq \frac{\sigma^2}{\delta} \cdot (1-o(1)). \end{equation} By Lemma~\ref{lem:mminf-bounds} (c), we can immediately get that because $\bar{r}_1 \leq 0$, the negative part \[ \mathbb{E}[(\overline{W} - \bar{r}_1)^-] \leq \mathbb{E}[(\overline{W})^-] = \Obrac{\sqrt{\sigma^2}}. \] Combining the bounds on $\mathbb{E}\left[(\overline{W}-\bar{r}_1)^+\right]$ and $\mathbb{E}[(\overline{W} - \bar{r}_1)^-]$ gives \[ \mathbb{E}[\overline{W}] = \frac{\sigma^2}{\delta} \cdot (1-o(1)) - \Obrac{\sqrt{\sigma^2} \log n + \ell_{\max}} = \frac{\sigma^2}{\delta} \cdot (1-o(1)), \] where the last equality follows from Assumption~\ref{assump:traffic} and \ref{assump:lm-bound}, that is, $\delta = \obrac{\sqrt{\sigma^2}/\log n}$ and $\ell_{\max} \leq \epsilon_0 \delta$. \subsubsection*{\textbf{Proof sketch of Lemma~\ref{result:workload-upper} (workload upper bound)}} Observe that $E[\overline{W}] \leq \bar{r}_2 + \mathbb{E}[(\overline{W} - \bar{r}_2)^+]$, for some $\bar{r}_2$ to be specified later. To bound the positive part $\mathbb{E}[(\overline{W} - \bar{r}_2)^+]$, we apply the relation $\mathbb{E}[G f(\ve{X}, \ve{Z})] = 0$ to a carefully constructed function $f(x)$ \begin{equation}\label{eq:proof:bd1:drift-var-terms} \mathbb{E}\left[\sum_{i=1}^I \ell_i \left( Z_i-\bar{x}_i\right)\cdot (\overline{W}-\bar{r}_2)^+\right] \leq \sigma^2. \end{equation} In addition, we claim that there exists some $\gamma > 0$ such that \begin{equation}\label{eq:proof:workload-upper:intermediate-goal} \gamma \cdot \mathbb{E}[(\overline{W} - \bar{r}_2)^+] \leq \mathbb{E}\left[\sum_{i=1}^I \ell_i \left( Z_i-\bar{x}_i\right)\cdot (\overline{W}-\bar{r}_2)^+\right] + o(1). \end{equation} To prove this, we observe that both of the terms $\mathbb{E}[(\overline{W} - \bar{r}_2)^+]$ and $\mathbb{E}\left[\sum_{i=1}^I \ell_i \left( Z_i-\bar{x}_i\right)\cdot (\overline{W}-\bar{r}_2)^+\right]$ are non-zero only when \begin{equation} \sum_{i=1}^I \frac{\ell_i}{\sev_i}(X_i - \bar{x}_i) \geq \bar{r}_2. \end{equation} By Lemma~\ref{lem:mminf-bounds} (b) with $c_i = \frac{1}{\sev_{\min}} - \frac{1}{\sev_i}$, we also have the following inequality with probability at least $1 - \frac{1}{n^3}$, \begin{equation}\label{eq:proof:workload-upper:with-high-prob} \sum_{i=1}^I \left(\frac{1}{\sev_{\min}} - \frac{1}{\sev_i}\right) \ell_i (X_i - \bar{x}_i) \geq - K_2 . \end{equation} for some $K_2 = \Obrac{\sqrt{\sigma^2}\log n}$. Adding up the two inequalities above and applying $\wst$-work-conserving property, we get \[ \sum_{i=1}^I \ell_i (Z_i - \bar{x}_i) \geq\min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta- \wst\right). \] After handling the low probability event that \eqref{eq:proof:workload-upper:with-high-prob} does not hold, we can show \eqref{eq:proof:workload-upper:intermediate-goal} with $\gamma = \min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta- \wst\right)$. Therefore, \begin{align*} \mathbb{E}[\overline{W}] &\leq \bar{r}_2 + \mathbb{E}[(\overline{W} - \bar{r}_2)^+]\\ &\leq \bar{r}_2 + \frac{\sigma^2}{\min\left(\sev_{\min}(\bar{r}_2 - K_2), \delta- \wst\right)} + o(1). \end{align*} The upper bounds \eqref{eq:result:workload-upper-case1} and \eqref{eq:result:workload-upper-case2} in Lemma~\ref{result:workload-upper} follow once we choose a suitable $\bar{r}_2$. When $\delta = \obrac{\sqrt{\sigma^2}/\log n}$, choosing $\bar{r}_2 = K_2 + (\delta - \wst)/\sev_{\min}$ yields $\mathbb{E}[\overline{W}] \leq \frac{\sigma^2}{\delta-\wst}\cdot (1+o(1))$. When $\delta = \Wbrac{\sqrt{\sigma^2}/\log n}$, choosing $\bar{r}_2 = K_2 + \Obrac{\sqrt{\sigma^2} \log n}$ yields $\mathbb{E}[\overline{W}] \leq \Obrac{\sqrt{\sigma^2}\log n}$. \section{Proof Sketch of Theorem~\ref{result:waiting-time-fcfs} (waiting times under FCFS)}\label{sec:proof:fcfs} The full proof of Theorem~\ref{result:waiting-time-fcfs} is presented in our technical report \cite{HonWan_21}. Here we give a proof sketch. The proof is based on the intuition that, under FCFS, the number of type~$i$ jobs in the queue is approximately proportional to its arrival rate $\lambda_i$, i.e. \begin{equation}\label{eq:fcfs-heuristics} \mathbb{E}[Q_i] \approx \frac{\lambda_i}{\lambda} \mathbb{E}[Q_\Sigma], \end{equation} where $Q_\Sigma \triangleq \sum_{i=1}^I Q_i$ is the total queue length. Therefore, we can easily convert from the expected workload to mean waiting time: \begin{equation} \sum_{i=1}^I \frac{\ell_i}{\sev_i} \mathbb{E}[Q_i] \approx \sum_{i=1}^I \frac{\lambda_i \ell_i}{\sev_i} \frac{1}{\lambda} \mathbb{E}[Q_\Sigma] = (n-\delta) \mathbb{E}\left[T^w\right], \end{equation} where the second equality is due to Little's law and the fact that $ \sum_{i=1}^I \frac{\lambda_i \ell_i}{\sev_i} = n-\delta$. This intuition is formalized by considering a \textit{Modified-FCFS} policy, under which $\mathbb{E}^{\text{Modified-FCFS}}[Q_i]= \frac{\lambda_i}{\lambda} \mathbb{E}^{\text{Modified-FCFS}}[Q_\Sigma]$. Using the Modified-FCFS, we then construct an upper bounding system and a lower bounding system for the original FCFS system, such that the queue lengths of the original system are sandwiched between the queue lengths of the two modified systems. \section{Proof of Theorem~\ref{result:waiting-time-lower-bound} (mean waiting time lower bound)}\label{sec:proof:lower} \begin{proof} Recall that by Little's law, $\mathbb{E}\big[T^w\big] = \frac{1}{\lambda}\sum_{i=1}^I \mathbb{E}[Q_i]$. Therefore, it suffices to show a lower bound on the total queue length. We fix a policy in the original system. For any $i$ with $\indexmain \leq i \leq I$, we consider the $i$-th subsystem by ignoring all job types with index greater than $i$. In the $i$-th subsystem, it is always possible to achieve the same $\mathbb{E}[Q_j]$'s for $j\leq i$ by imitating the service decisions taken by the original system. Therefore, we have $\sum_{j=1}^i \frac{\ell_j }{\sev_j}\mathbb{E}[Q_j]\ge \frac{\sigma^2_i}{\delta_i} \cdot (1-o(1))$, where the right hand side expression is the workload lower bound of the $i$-th subsystem according to Lemma~\ref{result:workload-lower}. Then the expected waiting time $\mathbb{E}[T^w]$ is lower-bounded by the optimal value of the following linear programming problem: \begin{alignat}{2} &\min_{\{q_j\colon j\in[I]\}}& \mspace{23mu} &\frac{1}{\lambda}\sum_{j=1}^I q_j\nonumber\\ &\text{subject to}& \quad &\sum_{j=1}^i \frac{\ell_j}{\sev_j} q_j\geq \frac{\sigma^2_i}{\delta_i} \cdot (1-o(1)) \quad \indexmain \leq i \leq I \nonumber\\ &&& q_j \geq 0 \quad \forall j \in [I],\nonumber \end{alignat} where $q_j$ corresponds to $\mathbb{E}[Q_j]$. It is easy to see that the objective value of this optimization problem satisfies \begin{align} \frac{1}{\lambda}\sum_{j=1}^{I} q_j \geq \frac{1}{\lambda}\frac{\sev_{\min}}{\ell_i}\sum_{j=1}^i \frac{\ell_j}{\sev_j}q_j \geq \frac{\sev_{\min}\sigma^2_i}{\lambda\ell_i\delta_i} \cdot (1-o(1)), \end{align} for any $\indexmain \leq i \leq I$, where in the first inequality we have used the fact that $\sev_j\geq\sev_{\min}$ and $\ell_j\leq\ell_i$ for any $j\leq i$. Because the choice of $i$ with $\indexmain \leq i \leq I$ is arbitrary, we have that the optimal value is no less than \begin{equation} \max_{\indexmain \leq i \leq I} \frac{\sev_{\min} \sigma^2_i}{\lambda \ell_i \delta_i} \cdot (1-o(1)). \end{equation} Therefore, $\mathbb{E}\big[T^w\big] \geq \max_{\indexmain \leq i \leq I} \frac{\sev_{\min} \sigma^2_i}{\lambda \ell_i \delta_i} \cdot (1-o(1))$. This completes the proof. \end{proof} \section{Proof of Theorem~\ref{result:waiting-time-priority} (mean waiting time under P-Priority)}\label{sec:proof:priority} To understand the behavior under P-Prioriy policy, one key observation is that for each $i\in[I]$, the type~$i$ jobs are unaffected by type~$j$ jobs with $j > i$. As a result, we can learn about the original system by analyzing each $i$-th subsystem, which is obtained by removing all jobs of type $j$ with $j>i$. Some subsystems are under relatively heavier traffic, or more precisely, subject to $\delta_i = \obrac{\frac{\sqrt{\sigma^2_i}}{\log n}}$, while some subsystems are under lighter traffic. For those subsystems under relatively heavier traffic, Lemma~\ref{result:workload-lower} and Lemma~\ref{result:workload-upper} are enough for use; for those subsystems under lighter traffic, we sometimes use Lemma~\ref{lem:proof:total-server-need-expectation}, which is a more refined bound on the expected total server need $\mathbb{E}\left[\sum_{i=1}^I \ell_i X_i\right]$, proved based on the two tail bounds in Lemma~\ref{lem:proof:workload-tail} and Lemma~\ref{lem:proof:total-server-need-tail}. The proofs of these Lemmas are in the appendices of \cite{HonWan_21}. \begin{restatable}{lem}{workloadtail}\label{lem:proof:workload-tail} Consider the multiserver-job system with $n$ servers satisfying $\ell_{\max} \leq \epsilon_0 \delta$ (Assumption~\ref{assump:lm-bound}). Under any $\ell_{\max}$-work-conserving policy, the normalized work has the following tail bound: for any $\epsilon$ such that $0<\epsilon < \epsilon_0$, there exists $\alpha_1 = \frac{2\epsilon\delta}{\sev_{\min}}+\Theta\left(\frac{n\ell_{\max}}{\delta}\log n\right)$ and $\beta_1 = \Theta\left(\frac{n\ell_{\max}}{\delta}\right)$ such that for any $j\ge 0$, \begin{equation} \mathbb{P}\left(\sum_{i=1}^I \frac{\ell_i}{\sev_i} (X_i(\infty) - \bar{x}_i) \geq \alpha_1 + \beta_1 \cdot j\right) \leq e^{-j}, \label{eq:proof:sub-hw:claim3-statement} \end{equation} where $\bar{x}_i = \frac{\lambda_i}{\sev_i}$. \end{restatable} \begin{restatable}{lem}{tsntail}\label{lem:proof:total-server-need-tail} Consider the multiserver-job system with $n$ servers satisfying $\ell_{\max} \leq \epsilon_0 \delta$ (Assumption~\ref{assump:lm-bound}). Under any $\ell_{\max}$-work-conserving policy, the total server need has the following tail bound: there exists $\alpha_2$ and $\beta_2$ with $\alpha_2 = \frac{\delta}{2} + \Theta(\frac{n\ell_{\max}}{\delta}\log n)$ and $\beta_2 = \Theta(\frac{n\ell_{\max}}{\delta})$ such that for any $j\ge 0$, \begin{equation} \mathbb{P}\left(\sum_{i=1}^I \ell_i (X_i(\infty) - \bar{x}_i) \geq \alpha_2 + \beta_2 \cdot j\right) \leq e^{-j}, \end{equation} where $\bar{x}_i = \frac{\lambda_i}{\sev_i}$. \end{restatable} The proof technique of the two lemmas is using state space concentration successively: Lemma~\ref{lem:proof:workload-tail} relies on the state-space concentration implied by Lemma~\ref{lem:mminf-bounds}, while Lemma~\ref{lem:proof:total-server-need-tail} relies on the state-space concentration implied by Lemma~\ref{lem:mminf-bounds} and Lemma~\ref{lem:proof:workload-tail}. As a consequence of the first two lemmas, we can give a bound on the expectation of the total server need $\mathbb{E}[\sum_{i=1}^I \ell_i X_i]$, in a different traffic regime than what is assumed in Assumption~\ref{assump:traffic}. This is useful for analyzing the dynamics of subsystems under P-Priority. \begin{restatable}[Total server need upper bound under a lighter traffic]{lem}{tsnupper}\label{lem:proof:total-server-need-expectation} Consider the multiserver-job system with $n$ servers satisfying $\ell_{\max} \leq \epsilon_0 \delta$ (Assumption~\ref{assump:lm-bound}), and $\delta = \wbrac{\sqrt{n\ell_{\max}}\log n}$. Then under any $\ell_{\max}$-work-conserving policy, the expected total server need has the following upper bound: \begin{equation} \mathbb{E}\left[\sum_{i=1}^I \ell_i (X_i(\infty) - \bar{x}_i)\right] = \exp\left(-\Omega\left( \frac{\delta^2}{n\ell_{\max}}\right)\right), \end{equation} where $\bar{x}_i = \frac{\lambda_i}{\sev_i}$. \end{restatable} As a quick digression, with Lemma~\ref{lem:proof:total-server-need-tail}, we can prove an upper bound on the queueing probability in Corollary~\ref{result:queueing-probability}. We comment that this queueing probability bound significantly improves on the bound in \cite{WanXieHar_21} in a slightly more constrained traffic regime. \begin{restatable}[Queueing probability]{cor}{queueingprob}\label{result:queueing-probability} Consider the multiserver-job system with $n$ servers satisfying $\ell_{\max} \leq \epsilon_0 \delta$ (Assumption~\ref{assump:lm-bound}), and $\delta = \wbrac{\sqrt{n\ell_{\max}}\log n}$. Then the probability that a job arrival in steady-state experiencing queueing has the following upper bound: \begin{equation} \mathbb{P}\left(\sum_{i=1}^I \ell_i X_i(\infty) \geq n\right) = \exp\left(-\Omega\left( \frac{\delta^2}{n\ell_{\max}}\right)\right). \end{equation} \end{restatable} Now we are ready to prove Theorem~\ref{result:waiting-time-priority}. \begin{proof}[Proof of Theorem~\ref{result:waiting-time-priority}] Recall that by Little's Law, we have that $\mathbb{E}\left[ T^w \right] = \frac{1}{\lambda}\sum_{i=1}^I \mathbb{E}[Q_i]$, and thus it suffices to bound $\mathbb{E}[Q_i]$'s. We bound $\mathbb{E}[Q_i]$ separately for each $i\in [I]$ as follows: \begin{equation}\label{eq:priority:individual-bdd-by-server-need} \mathbb{E}\left[Q_i\right] \leq \frac{1}{\ell_i} \mathbb{E} \left[\sum_{j=1}^i \ell_j Q_j \right] \leq \frac{1}{\ell_i} \mathbb{E} \left[\sum_{j=1}^i \ell_j \left(X_j - \bar{x}_j\right) \right], \end{equation} where we have used the fact that $Q_i$'s are non-negative, $Q_j = X_j - Z_j$ and $\mathbb{E}[Z_j] = \frac{\lambda_j}{\sev_j} = \bar{x}_j$. Observe that under P-Priority, the dynamics of the first $i$ types of jobs are unaffected by the rest of the jobs. Therefore, the expectation $\mathbb{E} \left[\sum_{j=1}^i \ell_j \left(X_j - \bar{x}_j\right) \right]$ can be viewed as the expected total server need in the $i$-th subsystem, which has slack capacity $\delta_i$, maximal server need $\ell_i$, and work variability $\sigma^2_i$. We discuss the bound on $\mathbb{E}[Q_i]$ in three cases based on different relationships of $\delta_i$, $\ell_i$ and $\sigma^2_i$. \noindent \textbf{Case 1: $\delta_i = \obrac{\frac{\sqrt{\sigma^2_i}}{\log n}}$}. Applying Lemma~\ref{result:workload-upper} to the $i$-th subsystem, we have \begin{align*} \mathbb{E} \left[\sum_{j=1}^i \ell_j \left(X_j - \bar{x}_j\right) \right] &\leq \sev_{\max} \mathbb{E} \left[\sum_{j=1}^i \frac{\ell_j}{\sev_j} \left(X_j - \bar{x}_j\right) \right]\\ &\leq \frac{\sev_{\max} \sigma^2_i}{\delta_i-\ell_i} \cdot (1+o(1)). \end{align*} Therefore, \begin{equation}\label{eq:priority:last-q} \mathbb{E}[Q_i] \leq \frac{\sev_{\max}\sigma^2_i}{\ell_i (\delta_i - \ell_i)} \cdot \left(1+o(1)\right). \end{equation} \noindent \textbf{Case 2: $\delta_i = \Wbrac{\frac{\sqrt{\sigma^2_i}}{\log n}}$ and $\ell_i = \wbrac{\frac{\delta \log n}{\sqrt{\sigma^2}} \ell_{\max}}$}. Applying Lemma~\ref{result:workload-upper} to the $i$-th subsystem, we have \begin{align*} \mathbb{E} \left[\sum_{j=1}^i \ell_j \left(X_j - \bar{x}_j\right) \right] \leq \sev_{\max} \mathbb{E} \left[\sum_{j=1}^i \frac{\ell_j}{\sev_j} \left(X_j - \bar{x}_j\right) \right]=\Obrac{\sqrt{\sigma^2_i}\log n}. \end{align*} Therefore, \begin{equation} \mathbb{E}[Q_i] \leq \Obrac{\frac{\sqrt{\sigma^2_i}\log n}{\ell_i}} =\obrac{\frac{\sigma^2}{\delta}\cdot\frac{1}{\ell_{\max}}}, \end{equation} where we have used the facts that $\ell_i = \wbrac{\frac{\delta \log n}{\sqrt{\sigma^2}} \ell_{\max}}$ and $\sigma^2_i \leq \sigma^2$ in the second equality. \noindent \textbf{Case 3: $\delta_i = \Wbrac{\frac{\sqrt{\sigma^2_i}}{\log n}}$ and $\ell_i = \Obrac{\frac{\delta \log n}{\sqrt{\sigma^2}} \ell_{\max}}$}. We first show that $\delta_i= \wbrac{\sqrt{n\ell_i}\log n}$. To see this, observe that $\delta_i = \Wbrac{\frac{\sqrt{\sigma^2_i}}{\log n}}$ implies $i < I$, so $\delta_i \geq \frac{\lambda_{I}\ell_{I}}{\sev_{I}} = n \rho_{I}$. By Assumption~\ref{assump:commonness}, we have \begin{equation} \delta_i \geq n \rho_{I} = \wbrac{\sqrt{\frac{\delta \log n}{\sqrt{\sigma^2} }\cdot n\ell_{\max}}\log n} = \wbrac{\sqrt{n\ell_i}\log n}. \end{equation} Therefore, we can apply Lemma~\ref{lem:proof:total-server-need-expectation} to the $i$-th subsystem to get: \begin{align*} \mathbb{E} \left[\sum_{j=1}^i \ell_j \left(X_j - \bar{x}_j\right) \right] = \exp\left(-\Wbrac{\frac{\delta_i^2}{n\ell_i}}\right)\leq \exp\left(-\Wbrac{(\log n)^2}\right), \end{align*} where we have used $\delta_i= \wbrac{\sqrt{n\ell_i}\log n}$ in the last inequality. Therefore, $ \mathbb{E}[Q_i] \leq \exp\left(-\Wbrac{(\log n)^2}\right) $, which decays faster than any polynomial in $n$. Combining the three cases, we get \begin{align*} \mathbb{E}\left[ T^w \right] & \leq \frac{1}{\lambda}\Bigg(\sum_{i=\indexmain}^I \frac{\sev_{\max}\sigma^2_i}{\ell_i (\delta_i - \ell_i)} \cdot \left(1+o(1)\right) \\ &\mspace{40mu} + \obrac{\frac{\sigma^2}{\delta}\cdot\frac{1}{\ell_{\max}}} + \exp\left(-\Wbrac{(\log n)^2}\right)\Bigg) \\ &\leq \frac{1}{\lambda}\sum_{i=\indexmain}^I \frac{\sev_{\max}\sigma^2_i}{\ell_i (\delta_i - \ell_i)} \cdot \left(1+o(1)\right), \end{align*} where we have used the fact that $\mathbb{E}\left[ T^w \right] = \frac{1}{\lambda}\sum_{i=1}^I \mathbb{E}[Q_i]$. Here the summation is taken from $\indexmain$ to $I$ because Case~1 is equivalent to $\indexmain \leq i\leq I$. The second inequality is because the other two terms are of lower order compared with $\frac{\sev_{\max}\sigma^2_{I}}{\ell_{I}(\delta_{I}-\ell_{I})}$. It remains to show that $\frac{1}{\lambda}\sum_{i=\indexmain}^I \frac{\sev_{\max}\sigma^2_i}{\ell_i (\delta_i - \ell_i)} = \Thebrac{\max_{\indexmain \leq i \leq I}\frac{1}{\lambda} \frac{\sigma^2_i}{\ell_i \delta_i}}$. This is because $I$ and $\sev_{\max}$ are independent of $n$ during scaling, and $\ell_i \leq \ell_{\max} \leq \epsilon_0 \delta \leq \epsilon_0 \delta_i$ for some $\epsilon_0 < 1$. This finishes the proof. \end{proof} \section{Simulation Results}\label{sec:simulation} \begin{figure} \centering \subfigure[Mean waiting time under the Parameter Set One. There are three job types, with service rates and server needs given by $\sev_1 = 0.25$, $\ell_1 = 1$; $\sev_2 = 0.5$, $\ell_2 = \lfloor\log_2 n\rfloor$; $\sev_3 =1 $, $\ell_3 =\lfloor \sqrt{n}\rfloor$; slack capacity $\delta = 2\lfloor \sqrt{n}\rfloor$, loads $\rho_1 = \rho_2 = \rho_3 = \frac{n-\delta}{3n}$, and arrival rates $\lambda_i$'s are chosen according to loads, service rates and server needs.]{\includegraphics[width=6cm]{figs/std_policy_compare.pdf}} \subfigure[Mean waiting time under the Parameter Set Two. There are three job types, with the same service rates, server needs and slack capacity as the Parameter Set One. The loads are given by $\rho_1 = \rho_2 = \frac{n - \delta - n^{0.7}}{2n}$, $\rho_3 = n^{-0.3}$. The arrival rates $\lambda_i$'s are chosen according to loads, service rates and server needs. ]{\includegraphics[width=6cm]{figs/IM2_policy_compare.pdf}} \caption{The mean waiting times of FCFS, P-Priority, and N-Priority under two sets of parameters. } \label{fig:mwt-exp} \vspace{-0.4cm} \end{figure} In this section, we perform simulation experiments to demonstrate the mean waiting time under FCFS, P-Priority and N-Priority, where N-Priority is the non-preemptive variant of P-Priority that serves a job with the smallest server need in the queue when enough number of servers free up. We run the simulation experiment under two sets of parameters. The Parameter Set One satisfies all three assumptions, while the Parameter Set Two does not satisfy Assumption~\ref{assump:commonness}. The parameters are specified in the caption of Figure~\ref{fig:mwt-exp}. We plot the mean waiting time against the number of servers $n$ under the three policies, as shown in Figure~\ref{fig:mwt-exp}. The parameter $n$ takes value in $\{2^6, 2^8, 2^{10}, 2^{12}, 2^{14}, 2^{16}, 2^{18}\}$. For each data point, we run a long enough trajectory to estimate the mean and the confidence interval. The confidence interval is estimated through batch means method, which divides the trajectory into $20$ batches, and calculates the variance of the means of each batch. It turns out that the confidence intervals of most data points in the plots are too small to be visible because our numerical estimates are accurate enough. We can make the following observations from the experiments on both parameter sets. First, there is a large performance gap between FCFS and P-Priority for systems with finite number of servers $n$, which complements our asymptotic results. Note that although in the Parameter Set Two, the absolute different between FCFS and P-Priority seems to close up as $n$ gets large, their ratio is always greater than $3$ when $n \geq 2^{10}$, and it gets to as large as $41.5$ under Parameter Set One, and $57.5$ under Parameter Set Two. Second, N-Priority performs comparably with P-Priority, and sometimes even performs slightly better.
{'timestamp': '2022-03-29T02:22:56', 'yymm': '2109', 'arxiv_id': '2109.05343', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05343'}
arxiv
\section{Introduction and Motivation} Diabetes self-management is a time-consuming, yet critical, task for people with type 1 diabetes. To avoid serious diabetic complications, these individuals must continually manage their blood glucose levels (BGLs), keeping them as close to normal as possible. They must avoid both low BGLs, or hypoglycemia, and high BGLs, or hyperglycemia, for their physical safety and well-being. Diabetes self-management entails carefully monitoring BGLs throughout the day, by testing blood obtained from finger sticks and/or by using a continuous glucose monitoring (CGM) system. It also entails making numerous daily decisions about the timing and dosage of insulin and the timing, ingredients, and quantity of food consumed. Current diabetes self-management may be characterized as \emph{reactive}, rather than \emph{proactive}. When BGLs are too high, individuals may take insulin to lower them, and when BGLs are too low, they may eat a snack or take glucose tablets to raise them. The ability to accurately predict BGLs could enable people with type 1 diabetes to take preemptive actions \emph{before} experiencing the negative effects of hypoglycemia or hyperglycemia. There have been efforts to model BGLs for the purpose of determining insulin dosages dating back to the 1960s \cite{boutayeb2016}. There has been much recent work in BGL prediction for the purpose of providing support for diabetes self-management, including our own \cite{bunescu:icmla13,plis:maiha14}. Accounts of some of the most recent BGL prediction efforts can be found in the proceedings of two international BGL prediction challenges \cite{kdh-2018-proceedings,kdh-2020-proceedings}. It should be noted that, even with the benefit of accurate BGL predictions, individuals still need to determine how much to eat, how much insulin to take, and what other actions they can take to prevent hypoglycemia or hyperglycemia. The broad goal of the research presented here is to essentially reverse the BGL prediction problem, and instead predict how many grams of carbohydrate (carbs) an individual should eat or how much insulin they should take in order to achieve a desired BGL target. We have previously introduced in \cite{mirshekarian:embc19} an LSTM-based neural architecture that was trained to answer {\it what-if} questions of the type “What will my BGL be in 60 minutes if I eat a snack with 30 carbs 10 minutes from now?”. By using the BGL target as a feature and the carbohydrates or insulin as labels, we have shown in subsequent work \cite{beauchamp:kdh20} that a similar LSTM-based architecture can be trained instead to predict the number of carbs that should be consumed or the amount of insulin that should be taken during the prediction window in order to reach that BGL target. Preliminary results were reported in \cite{beauchamp:kdh20} only for the task of carbohydrate recommendation, where the aim was to achieve a desired target BGL 30 or 60 minutes into the future. The timing of the meal was variable within the prediction window and was used as one of the inputs to the model. In this paper, we update the task definition to make it more applicable to the type of situations that are frequently encountered in the self-management of type 1 diabetes. As such, the timing of the bolus or meal is now fixed at 10 minutes into the future, based on the assumption that patients are most interested in using the system right before making a meal or bolus decision. To achieve the desired BGL, the user can specify any time horizon between 30 and 90 minutes, giving them more flexibility in terms of how fast they want their BGL to change. Furthermore, we improve the LSTM-based architecture from \cite{beauchamp:kdh20} and use it as a repeating residual block in a deep residual forecasting network derived from the BGL prediction architecture recently proposed by \citet{rubin_falcone:nbeats_bgl}. The neural architecture from \cite{rubin_falcone:nbeats_bgl} is in turn a modified version of the N-BEATS architecture \cite{oreshkin:nbeats} that was shown to obtain state-of-the-art results on a wide array of time series forecasting problems. Overall, the new recommendation approach using the integrated deep network is generic in the sense that it can be trained to make recommendations about any variable that can impact BGLs, in particular, carbohydrates and insulin. Carbohydrate recommendations are potentially useful when someone wants to prevent hypoglycemia well in advance or when someone wants to achieve a higher target BGL before physical exercise that is expected to lower it. Bolus recommendations are useful prior to meals and also for lowering BGLs when individuals experience hyperglycemia. The rest of the paper is organized as follows: Section~\ref{sec:related} presents related work in blood glucose level prediction and automated bolus calculators, and positions our work in relation to recent developments in these areas. Three major recommendation scenarios are introduced in Section~\ref{sec:scenarios}, followed in Section~\ref{sec:models} by a description of a set of baseline models and neural architectures that are designed to make recommendations in each of these scenarios. Section~\ref{sec:dataset} introduces the OhioT1DM dataset and explains how recommendation examples were derived from it. The experimental methodology and results are presented in Sections~\ref{sec:methodology} and~\ref{sec:results}, respectively. The paper concludes in Section~\ref{sec:conclusion} with a summary of our contributions and ideas for future work. \section{Related Work} \label{sec:related} Bolus calculators have been in use since 2003 \cite{gross:calculator}, wherein a standard formula is used to calculate a recommended insulin dosage, taking into count parameters such as carbohydrate intake, carbohydrate-to-insulin ratio, insulin on board, and target BGL. \citet{walsh:jdst18} discuss some major sources of errors and the potential improvements that could be made to bolus advisors. One such improvement mentioned was the utilization of the massive amount of clinical data that is collected from these bolus advisor systems. AI techniques have been used to take advantage of this data to create more intelligent and personalized insulin recommendation systems. \citet{pesl:case_based} describe a bolus advisor system based on case-based reasoning that personalizes an individual's bolus calculations. The system gathers simple information, such as the range of recent blood glucose levels and the time of day, and compares the current situation to situations from the past to find similar cases. The system then uses the bolus recommendation from a similar previous case and adapts it to the current scenario. The work by \citet{tyler:knn} shows a K-nearest-neighbors based system that provides weekly recommendations to improve the effectiveness of an individual's multiple daily injection therapy. With the amount of clinical data collected from CGM systems and wearable sensors, deep learning is a natural fit for insulin advisor systems. The work in \citet{stavroula:dtt} represents an early attempt at creating insulin recommendations by utilizing neural networks. \citet{cappon:jdst18} observe that the standard formula approach to bolus calculation ignores potentially important preprandial conditions, such as the glucose rate of change. To address this, they propose a simple feed-forward neural network that utilizes CGM data and other easily accessible factors to personalize the bolus calculation. The experimental evaluations on simulated data show a small, but statistically significant improvement in the blood glucose risk index. Simulated data is also used by \citet{sun:jbhi19}, where a basal-bolus advisor is trained using reinforcement learning in order to provide personalized suggestions to people with type 1 diabetes taking multiple daily injections of insulin. \citet{zhu:bolus_drl} also utilize simulated type 1 diabetes data for their deep reinforcement learning approach to personalizing bolus calculations. They use the UVA/Padova type 1 diabetes simulator \cite{dalla_man:simulator} to train models to learn how to reduce or amplify the bolus dose recommended by a bolus calculator to provide more personalized recommendations. In contrast with previous work that used a type 1 diabetes simulator \cite{cappon:jdst18,sun:jbhi19,zhu:bolus_drl}, the systems described in this paper are trained and evaluated on data acquired from people with type 1 diabetes, derived from the OhioT1DM dataset \cite{ohiot1dm:marling:kdh18} as explained in Section~\ref{sec:dataset}. The case-based reasoning system introduced by \citet{pesl:case_based} also makes use of real-patient data; however, their system does not learn directly from this data. Instead, it learns from clinical experts' advice, requiring also that the system is tweaked on a regular basis. Elsewhere \cite{mirshekarian:embc19}, we have shown that patterns that are learned from simulated data do not always transfer to real data, and vice-versa. By training and evaluating on real data, the results reported in this paper are expected to be more representative of the actual performance of the recommendation system if it were to be deployed in practice. Most of the related work on bolus recommendations presented above use global means of evaluating system performance, such as the percentage of time BGLs are in a target range \cite{sun:jbhi19,zhu:bolus_drl}, or the blood glucose risk index \cite{cappon:jdst18}. In contrast, our approaches are evaluated retrospectively on how close their recommendations are to the actual carbohydrate content or bolus dosages that led to a particular target BGL. As such, the trained models can be used to make recommendations in order to achieve a specific BGL. The neural architectures that we propose in this paper are also general in the sense that they can be used to make recommendations for any type of discrete intervention that may impact BGLs. While, in this paper, they are evaluated on bolus, carbs, and bolus given carbs recommendations, we also see them as applicable for recommending other relevant variables, such as exercise. \section{Three Recommendation Scenarios} \label{sec:scenarios} We assume that blood glucose levels are measured at 5 minute intervals through a CGM system. We also assume that discrete deliveries of insulin (boluses) and continuous infusions of insulin (basal rates) are recorded. Subjects provide the timing of meals and estimates of the number of grams of carbohydrate in each meal. Given the available data up to and including the present (time $t$), the system aims to estimate how much a person should eat or bolus 10 minutes from now (time $t+10$) such that their blood glucose will reach a target level $\tau$ minutes after that action (time $t + 10 + \tau$). A system that computes these estimates could then be used in the following three recommendation scenarios: \begin{enumerate} \item {\bf Carbohydrate Recommendations}: Estimate the amount of carbohydrate $C_{t+10}$ to have in a meal in order to achieve a target BG value $G_{t+10+\tau}$. \item {\bf Bolus Recommendations}: Estimate the amount of insulin $B_{t+10}$ to deliver with a bolus in order to achieve a target BG value $G_{t+10+\tau}$. \item {\bf Bolus Recommendations given Carbohydrates}: Expecting that a meal with $C_{t+20}$ grams of carbohydrate will be consumed 20 minutes from now, estimate the amount of insulin $B_{t+10}$ to deliver with a bolus 10 minutes before the meal in order to achieve a target BG value $G_{t+10+\tau}$. \end{enumerate} These recommendation scenarios were designed to align with decision-making situations commonly encountered by people with type 1 diabetes. In particular, the corresponding recommendation systems would help an individual to estimate how much to eat or bolus for the purpose of raising or lowering their BGL (scenarios 1 and 2), as well as how much to bolus for a planned meal (scenario 3). In the following Section~\ref{sec:models}, we describe a number of baseline models and neural architectures, all implementing the three types of recommendations. The neural architectures use Long Short-Term Memory (LSTM) networks either in a standalone prediction model (Section~\ref{sec:lstm}) or integrated as basic repeating blocks in a deep residual network (Section~\ref{sec:nbeats}). The models are trained on examples extracted from the OhioT1DM dataset~\cite{ohiot1dm:marling:kdh18}, as explained in Section~\ref{sec:dataset}. Ideally, to match the intended use of these recommendations in practice, training examples should not have any extra meals or boluses in the prediction window $[t, t + 10 + \tau]$. Following the terminology from \cite{mirshekarian:embc19}, we call these examples {\it inertial}. However, to benefit from a larger number of training examples, we also train and evaluate models on a more general class of {\it unrestricted} examples, in which other bolus or meal events are allowed to appear in the prediction window. Correspondingly, experimental results for inertial vs. unrestricted examples are presented in Section~\ref{sec:results}. \section{Baseline Models and Neural Architectures} \label{sec:models} Given training data containing time series of blood glucose levels, meals with their carbohydrate intake, and boluses with their corresponding insulin dosages, we define the following two baselines: \begin{enumerate} \item {\bf Global average}: For the carbohydrate recommendation scenario, the average number $\mu$ of carbs over all of the meals in the subject's training data is computed and used as the estimate for all future predictions for that subject, irrespective of the context of the example. Analogously, for the bolus and bolus given carbs recommendation scenarios, $\mu$ is the average amount of insulin dosage over all boluses in the subject's training data. This is a fairly simple baseline, as it predicts the same average value for every test example for a particular subject. \item {\bf ToD average}: In this Time-of-Day (ToD) dependent baseline, an average number of carbs or an average amount of bolus insulin is computed for each of the following five time windows during a day: \begin{itemize} \item 12am-6am: $\mu_1$ = early breakfast / late snacks. \item 6am-10am: $\mu_2$ = breakfast. \item 10am-2pm: $\mu_3$ = lunch. \item 2pm-6pm: $\mu_4$ = dinner. \item 6pm-12am: $\mu_5$ = late dinner / post-dinner snacks. \end{itemize} The average for each ToD interval is calculated over all of the meals or boluses appearing in the corresponding time frame in the subject's training data. At test time, to make a recommendation for time $t+10$, we first determine the ToD interval that contains $t+10$ and output the corresponding ToD average. \end{enumerate} Given sufficient historical data, the ToD baseline is expected to perform well for individuals who tend to eat very consistently and have regular diets. However, it is expected to perform poorly for individuals who have a lot of variation in their diets. \begin{figure*}[t] \includegraphics[width=\textwidth]{carbs-block} \caption{The general neural network architecture for the carbohydrate recommendation scenario. The dashed blue line in the graph represents a subject's BGL, while the solid brown line represents the basal rate of insulin. The gray star represents the meal at time $t+10$. The other meals are represented by squares, and boluses are represented by circles. Meals and boluses with a red outline cannot appear in {\it inertial} examples, but are allowed in {\it unrestricted} examples. The blue units in $\text{LSTM}_{1}$ receive input from different time steps in the past. The green units in $\text{LSTM}_{2}$ receive input from the prediction window. The purple trapezoid represents the 5 fully connected layers, whereas the output node at the end computes the prediction.} \label{fig:carbs} \end{figure*} \begin{figure*}[t] \includegraphics[width=\textwidth]{bolus-block} \caption{The general neural network architecture for the bolus and bolus given carbs recommendation scenarios. The architecture itself is similar to that shown in Figure~\ref{fig:carbs}. The grey star now represents the bolus at time $t+10$. For the bolus recommendation scenario, the events outlined in red or orange are not allowed in {\it inertial} examples. However, in the bolus given carbs scenario, the meal event $C_{t+20}$ shown with the yellow outline is an important part of each example, be it inertial or unrestricted. As such, in this scenario, the dashed $C_{t+20}$ becomes part of the input to the FCN.} \label{fig:bolus} \end{figure*} \begin{figure*}[t] \includegraphics[width=\textwidth]{carbs-nbeats} \caption{The N-BEATS inspired deep residual architecture for carbohydrate recommendation. A similar architecture is used for bolus and bolus given carbs recommendations.} \label{fig:nbeats} \end{figure*} \subsection{LSTM Models for Carbohydrate and Insulin Recommendation} \label{sec:lstm} While simple to compute and use at test time, the two baselines are likely to give suboptimal performance, as their predictions ignore the history of BGL values, insulin (boluses and basal rates), and meals, all of which could significantly modulate the effect a future meal and/or bolus might have on the BGL. To utilize this information, we first introduce the general LSTM-based network architecture shown in Figure~\ref{fig:carbs} for carb recommendation and Figure~\ref{fig:bolus} for bolus recommendation. The first component in the architecture is a recurrent neural network instantiated using Long Short-Term Memory (LSTM) cells \cite{hochreiter:nc97}, which is run over the previous 6 hours of data, up to and including the present time $t$. At each time step (every 5 minutes), this LSTM$_1$ network takes as input the BGL, the carbs, and the insulin dosages recorded at that time step. While sufficient for processing {\it inertial} examples, the same LSTM cannot be used to process events that may appear in the prediction window $(t, t+10+\tau)$ of {\it unrestricted} examples, because BGL values are not available in the future. Therefore, when training on unrestricted examples, the final state computed by the LSTM$_1$ model at time $t$ is projected using a linear transformation and used as the initial state for a second LSTM model, LSTM$_2$, that is run over all the time steps in the prediction window $(t, t+10+\tau)$. The final state computed by LSTM$_1$ (for inertial examples) is appended to the final state computed by LSTM$_2$ (for unrestricted examples) and is then used as input to a fully connected network (FCN) whose output node computes an estimate of the carbs or bolus insulin at time $t+10$. In addition to the LSTM final state(s), the input to the FCN contains the following features: \begin{itemize} \item The target blood glucose level $\tau+10$ minutes into the future, i.e., $G_{t + 10 + \tau}$. \item The prediction horizon $\tau$. \item The ToD average for the time frame that contains $t+10$. \item For the bolus given carbs scenario only, the planned amount $C_{t + 20}$ of carbohydrate becomes part of the input, too. \end{itemize} Each LSTM uses vectors of size 32 for the states and gates, whereas the FCN is built with up to 5 hidden layers, each consisting of 64 ReLU neurons, and one linear output node. Note that by using the final state of LSTM$_1$ to initialize LSTM$_2$, the latter's final state should theoretically be able to capture any useful information that is represented in the final state of LSTM$_1$, which may call into question the utility of concatenating the two final states. This architectural decision is nevertheless supported empirically through evaluations on the validation data, which show improvements in prediction performance when both states are used (Section~\ref{sec:development}). \subsection{Deep Residual Models for Carbohydrate and Insulin Recommendation} \label{sec:nbeats} \citet{oreshkin:nbeats} have recently introduced a new architecture for time series forecasting, the Neural Basis Expansion for Interpretable Time-Series Forecasting (N-BEATS). The basic building {\it block} of N-BEATS is a fully connected structure that initially takes as input a fixed-size {\it lookback period} of past values of the target variable and outputs both {\it forecast} (estimates of future values) and {\it backcast} (estimates of past values) vectors. Blocks are organized into {\it stacks} such that the backcast of the current block is subtracted from its input and fed as input to the next block, whereas the forecast vectors from each block are summed up to provide the overall {\it stack forecast}. The stacks themselves are chained in a pipeline where the backcast output of one stack is used as input for the next stack. The overall model forecast is then computed by accumulating the forecasts across all the stacks. The N-BEATS architecture was shown in \cite{oreshkin:nbeats} to obtain state-of-the-art performance on a wide range of time series prediction tasks, which suggests that it can serve as a model of choice for BGL prediction, too. However, in BGL prediction, time series of variables other then the primary blood glucose are also available. Correspondingly, \citet{rubin_falcone:nbeats_bgl} changed the N-BEATS block architecture to also use as input secondary, sparse variables such as meals and bolus insulin, while still backcasting only on the primary forecasting variable, blood glucose. To account for the temporal nature of the input, the fully connected structure of the basic N-BEATS block was replaced with LSTMs, followed by one fully connected layer whose output was split into the backcast and forecast vector. Additional per-block forecast and backcast loss terms were also added to provide more supervision. We adapted the deep residual network from \cite{rubin_falcone:nbeats_bgl} to perform carb or bolus recommendations by using the LSTM-based architecture from Section~\ref{sec:lstm} to instantiate each block in the stack, as shown in Figure~\ref{fig:nbeats}. Compared to the architecture from \cite{rubin_falcone:nbeats_bgl}, the most significant differences are: \begin{enumerate} \item The use of a chain of two LSTM networks in each block. \item The inclusion of additional inputs to the fully connected layers, i.e. the target BG level, the time horizon, and the ToD average. \item While backcasting is still done for blood glucose, forecasting is done for carbs or bolus, depending on the recommendation scenario. \end{enumerate} While \citet{oreshkin:nbeats} used 30 blocks and \citet{rubin_falcone:nbeats_bgl} used 10 blocks, the validation experiments for the recommendation tasks showed that the most effective deep residual architecture uses only up to 5 blocks, depending on the recommendation scenario (Section~\ref{sec:development}). \section{Using the OhioT1DM Dataset for Recommendation Examples} \label{sec:dataset} To evaluate the proposed recommendation models, we create training and test examples based on data collected from 12 subjects with type 1 diabetes that is distributed with the OhioT1DM dataset~\cite{ohiot1dm:marling:kdh20}. The 12 subjects are partitioned in two subsets as follows: \begin{enumerate} \item {\bf OhioT1DM 2018}: This is the first part of the dataset, containing data collected from 6 patients. It was used for the 2018 Blood Glucose Level Prediction (BGLP) challenge \cite{kdh-2018-proceedings}. \item {\bf OhioT1DM 2020}: This is the second part of the dataset, containing data collected from 6 additional patients. It was used for the 2020 BGLP challenge \cite{kdh-2020-proceedings}. \end{enumerate} Time series containing the basal rate of insulin, boluses, meals, and BGL readings were collected over 8 weeks, although the exact number of days varies from subject to subject. Insulin and BGL data was automatically recorded by each subject's insulin pump. Meal data was collected in two different ways. Subjects self reported meal times and estimated carbs via a smartphone interface. Subjects also entered estimated carbs into a bolus calculator when bolusing for meals, and this data was recorded by the insulin pump. \subsection{The Bolus Wizard} \label{sec:bw} To determine their insulin dosages, the subjects in the OhioT1DM study used a bolus calculator, or "Bolus Wizard (BW)," which was integrated in their insulin pumps. They used it to calculate the bolus amount before each meal as well as when using a bolus to correct for hyperglycemia. To use the BW, a subject enters their current blood glucose level and, if eating, their estimated number of grams of carbohydrate. To calculate a recommended insulin dosage, the BW uses this input from the subject, plus the amount of active insulin the subject already has in their system, along with the following three pre-programmed, patient-specific parameters: \begin{enumerate} \item The carb ratio, which indicates the number of grams of carbohydrate that are covered by a unit of insulin. \item The insulin sensitivity, which tells how much a unit of insulin is expected to lower the subject's blood glucose level. \item The target blood glucose range, which defines an individual's lower and upper boundaries for optimal blood glucose control. \end{enumerate} All three parameters may vary, for the same individual, throughout the day and over time\footnote{\url{https://www.medtronicdiabetes.com/loop-blog/4-features-of-the-bolus-wizard}}. Given this input and these parameters, the BW calculates the amount of insulin the subject should take to maintain or achieve a blood glucose level within their target range. The calculation is displayed to the subject as a recommendation, which the subject may then accept or override. Based on the inputs and the patient-specific parameters described above, the BW uses a deterministic formula to calculate the bolus amount before each meal. As such, when trained in the bolus given carbs recommendation scenario, there is the risk that the deep learning models introduced in Section~\ref{sec:models} might simply learn to reproduce this deterministic dependency between bolus and carbs, while ignoring the target BG level that is used as input. However, this is not the case in our experimental settings, for the following reasons: \begin{itemize} \item The ML models do not have access to any of the three patient-specific parameters above, which can change throughout the day and over time, and which are set based on advice from a health care professional. \item The BW uses a fixed target BG range depending on the time of day, whereas the target in the recommendation scenarios is a more specific BG level, to be achieved at a specific time in the near future. \item The amount of insulin calculated by the BW is only a recommendation, which is often overridden by subjects. We ran an analysis of the OhioT1DM dataset in which we counted how many times the amount of insulin that was actually delivered was different from the bolus recommendation. The analysis revealed that, of all the times that the BW was used, its recommendation was overridden for about a fifth of the boluses. Furthermore, there are subjects in the dataset who often did not use the BW (540 and 567), or who chose to not use the BW at all (596). \end{itemize} Therefore, the ML models will have to go beyond using solely the carbohydrate amount in the intended meal. In order to fit the bolus recommendation examples, they will need to learn the impact that a bolus has on the target BG level for the specified prediction horizon, taking into account the amount of carbohydrate in the meal as well as the history of carbs, insulin, and BG levels. This data driven approach to bolus recommendation relieves the physician from the cognitively demanding task of regularly updating parameters such as the carb ratio and the insulin sensitivity, which often requires multiple fine tuning steps. In contrast, any relevant signal that is conveyed through the carb ratio and insulin sensitivity is expected to be learned by the ML models from the data. \subsection{Pre-processing of Meals and BG Levels} \label{sec:pre-processing} While exploring the data, it was observed that self-reported meals and their associated boluses were in unexpected temporal positions relative to each other. For many meals, patients recorded a timestamp in the smartphone interface that preceded the corresponding bolus timestamp recorded in the insulin pump. This was contrary to what was recommended to the subjects by their physicians, which was to bolus shortly before the meal, and no more than 15 minutes prior to the meal. This discrepancy is likely due to subjects reporting incorrect meal times in the smartphone interface. To correct the meal events, we used the data input to the BW in the insulin pump and ran a pre-processing step that changed the timestamp of each meal associated with a bolus to be exactly 10 minutes after that bolus. For these meals, we also used the number of carbs provided to the BW, which is likely to be more accurate than the estimate provided by the subject through the smartphone interface. To determine the self-reported meal event associated with a bolus having non-zero carb input, we searched for the meal that was closest in time to the bolus, within one hour before or after it. In case there were two meals that are equally close to the bolus, we selected the one for which the number of carbs from the smartphone interface was closest to the number of carbs entered into the BW. If no self-reported meal was found within one hour of the bolus, it was assumed that the subject forgot to log their meal on the smartphone interface. As such, a meal was added 10 minutes after the bolus, using the amount of carbs specified in the BW for that bolus. Ablation results reported in Section~\ref{sec:pre-evaluation} show that this pre-processing of meal events leads to significantly more accurate predictions, which further justifies the pre-processing. All gaps in BGL data are filled in with linearly interpolated values. However, we filter out examples that meet any of the following criteria: \begin{enumerate} \item The BGL target is interpolated. \item The BGL at present time $t$ is interpolated. \item There are more than 2 interpolated BGL measurements in the one hour of data prior to time $t$. \item There are more than 12 interpolated BGL measurements in the 6 hours of data prior to time $t$. \end{enumerate} \subsection{Mapping Prototypical Recommendation Scenarios to Datasets} \label{sec:mapping} According to the definition given in Section~\ref{sec:scenarios}, the carbohydrate recommendation scenario refers to estimating the amount of carbohydrate $C_{t+10}$ to have in a meal in order to achieve a target BG value $G_{t+10+\tau}$. This is done by using the history of data up to and including the present time $t$. However, many carbohydrate intake events $C_{t+10}$ are regular meals, which means that they are preceded by a bolus event at time $t$. Since in the carbohydrate recommendation scenario we are especially interested in scenarios where the subject eats in order to correct or prevent hypoglycemia, we created two separate datasets for carbohydrate prediction: \begin{enumerate} \item Carbs$^{(\pm b)}$: this will contain examples for all carbohydrate intake events, with $(+b)$ or without $(-b)$ an associated bolus. \item Carbs$^{(-b)}$: this will contain examples only for carbohydrate intake events without $(-b)$ an associated bolus. \end{enumerate} Most of the Carbs$^{(-b)}$ examples are expected to happen in one of three scenarios: (1) when correcting for hypoglycemia; (2) before exercising; and (3) when having a bedtime snack to prevent nocturnal hypoglycemia. Given that they are only a small portion of the overall carbohdyrate events, in Section~\ref{sec:results} we present results for both Carbs$^{(\pm b)}$ and Carbs$^{(-b)}$ recommendation scenarios. Furthermore, mirroring the two bolus recommendation scenarios introduced in Section~\ref{sec:scenarios}, we introduce the following notation for the corresponding datasets: \begin{enumerate} \item Bolus$^{(\pm c)}$: this will contain examples for all bolus events, with $(+c)$ or without $(-c)$ an associated carbohydrate intake. \item Bolus$^{(+c)}$: this will contain examples only for the bolus events with $(+c)$ an associated carbohydrate intake. \end{enumerate} The three major recommendation scenarios introduced in Section~\ref{sec:scenarios} can then be mapped to the corresponding datasets as follows: \begin{enumerate} \item {\bf Carbohydrate Recommendations}: Estimate the amount of carbohydrate $C_{t+10}$ to have in a meal in order to achieve a target BG value $G_{t+10+\tau}$. \begin{itemize} \item Carbs$^{(-b)}$, inertial: this reflects the prototypical scenario where a carbohydrate intake is recommended to correct or prevent hypoglycemia. \end{itemize} \item {\bf Bolus Recommendations}: Estimate the amount of insulin $B_{t+10}$ to deliver with a bolus in order to achieve a target BG value $G_{t+10+\tau}$. \begin{itemize} \item Bolus$^{(\pm c)}$, inertial: this reflects the prototypical scenario where a bolus is recommended to correct or prevent hyperglycemia. Because in the inertial case a carb event cannot appear after the bolus, this could also be denoted as Bolus$^{(-c)}$. \end{itemize} \item {\bf Bolus Recommendations given Carbohydrates}: Expecting that a meal with $C_{t+20}$ grams of carbohydrate will be consumed 20 minutes from now, estimate the amount of insulin $B_{t+10}$ to deliver with a bolus 10 minutes before the meal in order to achieve a target BG value $G_{t+10+\tau}$. \begin{itemize} \item Bolus$^{(+c)}$, inertial: this reflects the prototypical scenario where a bolus is recommended before a meal. \end{itemize} \end{enumerate} \subsection{Carbohydrate and Bolus Statistics} \label{sec:statistics} Table~\ref{tab:meals} shows the number of carbohydrate events in each subject's pre-processed data, together with the minimum, maximum, median, average, and standard deviation for the number of carbs per meal. Overall, the average number of carbs per meal is between 22 and 69, with the exception of subjects 570 and 544 whose meal averages and standard deviations are significantly larger. Table~\ref{tab:boluses} shows similar statistics for boluses and their dosages, expressed in units of insulin. Overall, the number of boluses is more variable than the number of meals. There is also a fairly wide range of average bolus values in the data, with subject 567 having a much higher average than other subjects. It is also interesting to note that subject 570, who had the largest average carbs per meal, had more than twice the number of boluses than any other subject while at the same time having the lowest average bolus. Subject 570 also used many dual boluses, which we did not use as prediction labels because the scope of the project covers only recommendations for regular boluses. \begin{table}[t]\setlength{\tabcolsep}{4pt} \begin{center} \caption{Per subject and total meal and carbohydrate per meal statistics: Minimum, Maximum, Median, Average, and Standard Deviation (StdDev). Carbs$^{(\pm b)}$ refers to all carbohydrate intake events; Carbs$^{(-b)}$ refers to carbohydrate intakes without a bolus. Statistics are shown for the 2018 subset, the 2020 subset, and for the entire OhioT1DM dataset.} \label{tab:meals} \begin{tabular}{|crr|rrrrc|} \cline{4-8} \multicolumn{3}{c}{} & \multicolumn{5}{|c|}{Carbs Per Meal}\\ \hline Subject & \multicolumn{1}{c}{Carbs$^{(\pm b)}$} & \multicolumn{1}{c|}{Carbs$^{(-b)}$} & \multicolumn{1}{c}{Minimum} & \multicolumn{1}{c}{Maximum} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & StdDev\\ \hline 559 & 215 & 83 & 8.0 & 75.0 & 30.0 & 35.5 & 15.5\\ 563 & 225 & 28 & 5.0 & 84.0 & 31.0 & 33.8 & 18.0\\ 570 & 174 & 39 & 5.0 & 200.0 & 115.0 & 106.1 & 41.5\\ 575 & 297 & 122 & 1.0 & 110.0 & 40.0 & 40.0 & 22.0\\ 588 & 268 & 73 & 2.0 & 60.0 & 20.0 & 22.7 & 14.6\\ 591 & 264 & 60 & 3.0 & 77.0 & 28.0 & 31.5 & 14.1\\ \hline 2018 Total & 1443 & 405 & 1.0 & 200.0 & 33.0 & 41.5 & 32.7\\ \hline 540 & 234 & 14 & 1.0 & 110.0 & 40.0 & 50.2 & 29.8\\ 544 & 206 & 41 & 1.0 & 175.0 & 60.0 & 68.7 & 36.3\\ 552 & 271 & 25 & 3.0 & 135.0 & 26.0 & 36.7 & 29.3\\ 567 & 207 & 5 & 20.0 & 140.0 & 67.0 & 67.0 & 21.5\\ 584 & 233 & 44 & 15.0 & 78.0 & 60.0 & 54.6 & 11.6\\ 596 & 300 & 277 & 1.0 & 64.0 & 25.0 & 25.1 & 14.0\\ \hline 2020 Total & 1451 & 406 & 1.0 & 175.0 & 42.0 & 48.2 & 29.5\\ \hline Combined Total & 2894 & 811 & 1.0 & 200.0 & 39.0 & 44.9 & 31.3\\ \hline \end{tabular} \end{center} \end{table} \begin{table}[t]\setlength{\tabcolsep}{4pt} \begin{center} \caption{Per subject and total boluses and insulin units statistics: Minimum, Maximum, Median, Average, and Standard Deviation (StdDev). Bolus$^{(\pm c)}$ refers to all bolus events; Bolus$^{(+c)}$ refers to bolus events associated with a meal. Statistics are shown for the 2018 subset, the 2020 subset, and for the entire OhioT1DM dataset.} \label{tab:boluses} \begin{tabular}{|crr|rrrrc|} \cline{4-8} \multicolumn{3}{c|}{} & \multicolumn{5}{c|}{Insulin Per Bolus}\\ \hline Subject & \multicolumn{1}{c}{Bolus$^{(\pm c)}$} & \multicolumn{1}{c|}{Bolus$^{(+c)}$} & \multicolumn{1}{c}{Minimum} & \multicolumn{1}{c}{Maximum} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & StdDev\\ \hline 559 & 186 & 132 & 0.1 & 9.3 & 3.6 & 3.7 & 1.9\\ 563 & 424 & 197 & 0.1 & 24.7 & 7.8 & 8.0 & 4.2\\ 570 & 1,345 & 132 & 0.2 & 12.1 & 1.3 & 1.8 & 2.1\\ 575 & 271 & 175 & 0.1 & 12.8 & 4.4 & 4.1 & 3.0\\ 588 & 221 & 195 & 0.4 & 10.0 & 3.5 & 4.3 & 2.3\\ 591 & 331 & 204 & 0.1 & 9.4 & 2.9 & 3.1 & 1.8\\ \hline 2018 Total & 2,758 & 1,035 & 0.1 & 24.7 & 1.9 & 3.5 & 3.4\\ \hline 540 & 521 & 220 & 0.1 & 11.4 & 2.0 & 3.0 & 2.8\\ 544 & 264 & 149 & 0.7 & 22.5 & 5.0 & 6.5 & 4.9\\ 552 & 426 & 246 & 0.1 & 16.0 & 2.8 & 3.9 & 3.3\\ 567 & 366 & 202 & 0.2 & 25.0 & 11.4 & 12.0 & 5.8\\ 584 & 311 & 188 & 0.1 & 16.2 & 9.1 & 7.3 & 3.1\\ 596 & 230 & 0 & 0.2 & 7.6 & 3.3 & 3.0 & 1.5\\ \hline 2020 Total & 2,118 & 1,169 & 0.1 & 25.0 & 4.0 & 5.8 & 5.0\\ \hline Combined Total & 4,876 & 2,204 & 0.1 & 25.0 & 2.9 & 4.5 & 4.3\\ \hline \end{tabular} \end{center} \end{table} \subsection{From Meals and Bolus Events to Recommendation Examples} \label{sec:examples} In all recommendation scenarios, the prediction window ranges between the present time $t$ and the prediction horizon $t + 10 + \tau$. For the carbohydrate or bolus recommendation scenarios, the meal or the bolus is assumed to occur at time $t +10$. For the bolus given carbs scenario, the bolus occurs at time $t+10$ and is followed by a meal at time $t+20$, which matches the pre-processing of the meal data. For evaluation purposes, we set $\tau$ to values between 30 and 90 minutes with a step of 5 minutes, i.e, $\tau \in \{30, 35, 40, ..., 90\}$ for a total of 13 different values. As such, each meal/bolus event in the data results in 13 recommendation examples, one example for each value of $\tau$. While all 13 examples use the same value for the prediction label, e.g., $B_{t + 10}$ for bolus prediction, they will differ in terms of the target BG feature $G_{t + 10 + \tau}$ and the $\tau$ feature, both used directly as input to the FC layers in the architectures shown in Figures~\ref{fig:carbs} and~\ref{fig:bolus}. For the bolus given carbs scenario, the 13 examples are only created when there is a meal that had a bolus delivered 10 minutes prior. Due to the way the data is pre-processed, it is guaranteed that if a meal had a bolus associated with it, the bolus will be exactly 10 minutes before the meal. Table \ref{tab:c1_examples} shows the number of {\it inertial} examples for 5 prediction horizons, as well as the total over all 13 possible prediction horizons. Table \ref{tab:c2_examples} shows the number of {\it unrestricted} examples. Since the same number of unrestricted examples are available for every prediction horizon, only the totals are shown. The only exceptions would be if an event was near the end of a subject's data and the prediction horizon $t+10+\tau$ goes past the end of the dataset for some value of $\tau$. \begin{table}[ht]\setlength{\tabcolsep}{4pt} \begin{center} \caption{{\it Inertial} ({\it I}) examples by recommendation scenario and prediction horizon. Carbs$^{(\pm b)}$ refers to all carbohydrate intake events; Carbs$^{(-b)}$ refers to carbohydrate intakes without a bolus.} \label{tab:c1_examples} \begin{tabular}{|l|rrrr|rrrr|} \cline{2-9} \multicolumn{1}{c}{}& \multicolumn{4}{|c|}{Carbs$^{(\pm b)}$ recommendation} & \multicolumn{4}{c|}{Carbs$^{(-b)}$ recommendation}\\ \hline Horizon & Training & Validation & Testing & Total {\it I} & Training & Validation & Testing & Total {\it I}\\ \hline $\tau=30$ & 1,192 & 340 & 331 & 1,863 & 265 & 53 & 40 & 358\\ $\tau=45$ & 1,156 & 334 & 321 & 1,811 & 255 & 51 & 40 & 346\\ $\tau=60$ & 1,121 & 318 & 315 & 1,754 & 243 & 50 & 40 & 333\\ $\tau=75$ & 1,057 & 301 & 293 & 1,651 & 226 & 44 & 34 & 304\\ $\tau=90$ & 975 & 279 & 278 & 1,532 & 200 & 40 & 31 & 271\\ All 13 horizons & 14,343 & 4,103 & 4,007 & 22,453 & 3,100 & 620 & 486 & 4,206\\ \hline \multicolumn{5}{c}{}\\[-1.5ex] \cline{2-9} \multicolumn{1}{c}{} & \multicolumn{4}{|c|}{Bolus$^{(\pm c)}$ recommendation} & \multicolumn{4}{c|}{Bolus$^{(+ c)}$ recommendation}\\ \hline Horizon & Training & Validation & Testing & Total {\it I} & Training & Validation & Testing & Total {\it I}\\ \hline $\tau=30$ & 461 & 160 & 143 & 764 & 856 & 267 & 271 & 1,394\\ $\tau=45$ & 416 & 142 & 124 & 682 & 833 & 259 & 258 & 1,350\\ $\tau=60$ & 368 & 124 & 104 & 596 & 816 & 253 & 249 & 1,318\\ $\tau=75$ & 303 & 102 & 96 & 501 & 790 & 243 & 243 & 1,276\\ $\tau=90$ & 271 & 90 & 86 & 447 & 743 & 234 & 229 & 1,206\\ All 13 horizons & 4,732 & 1,606 & 1,423 & 7,761 & 10,514 & 3,269 & 3,249 & 17,032\\ \hline \end{tabular} \end{center} \end{table} \begin{table}[ht]\setlength{\tabcolsep}{4pt} \begin{center} \caption{{\it Unrestricted} (U) examples by recommendation scenario, also showing, in the last column, the total number of non-inertial ($U - I$) examples. Carbs$^{(\pm b)}$ refers to all carbohydrate intake events; Carbs$^{(-b)}$ refers to carbohydrate intakes without a bolus.} \label{tab:c2_examples} \begin{tabular}{|l|rrrr|r|} \hline Scenario & Training & Validation & Testing & Total $U$ & Total $U - I$\\ \hline Carbs$^{(\pm b)}$ & 17,937 & 5,106 & 4,943 & 27,986 & 5,533\\ Carbs$^{(-b)}$ & 4,140 & 853 & 624 & 5,617 & 1,411\\ Bolus$^{(\pm c)}$ & 19,640 & 6,279 & 6,136 & 32,055 & 24,294\\ Bolus$^{(+c)}$ & 12,052 & 3,784 & 3,816 & 19,652 & 2,620\\ \hline \end{tabular} \end{center} \end{table} For the carbohydrate and bolus given carbs recommendation scenarios, the gap between the number of {\it inertial} and {\it unrestricted} examples is not very large, as most examples qualify as inertial examples. However, in the bolus recommendation scenario, there is a very sizable gap between the number of inertial vs. unrestricted examples. This is because a significant number of boluses are associated with meals, and since these meals are timestamped to be 10 minutes after the bolus, the result is that a bolus at time $t + 10$ will be associated with a meal at time $t + 20$. Therefore, for preprandial boluses at $t + 10$, the meal at time $t + 20$ will prohibit the creation of inertial recommendation examples, because by definition inertial examples do not allow the presence of other events in the prediction window $(t, t + 10 + \tau)$. \section{Experimental Methodology} \label{sec:methodology} For each of the 12 subjects in the dataset, their time series data is split into three sets, as follows: \begin{itemize} \item {\it Testing}: the last 10 days of data. \item {\it Validation}: the 10 days of data preceding the testing portion. \item {\it Training}: the remainder of the data, around 30 days. \end{itemize} The blood glucose, carbs, and insulin values are all scaled to be between $[0, 1]$ by using maximum and minimum values computed over training data. When computing the performance metrics at test time, the predicted values are scaled back to the original range. The neural architecture is trained to minimize the mean squared error between the actual event (meal or bolus) value recorded in the training data and the estimated value computed by the output node of the fully connected layers in the LSTM models, or by the accumulated forecasts in the N-BEATS architecture. The Adam \cite{kingma:adam} variant of gradient descent is used for training, with the learning rate and mini-batch size being tuned on the validation data. In an effort to avoid overfitting, dropout and early stopping with a patience of 10 epochs are used in all experiments. Before training a personalized model for a specific subject, a generic model is first pre-trained on the union of all 12 subjects' training data. The generic model is then fine tuned separately for each individual subject, by continuing training on that subject's training data only. The pre-training allows the model parameters to be in a better starting position before fine tuning, allowing faster and better training. The learning rate and batch size are tuned for each subject on their validation data. For each subject, the results are aggregated over 10 models that are trained with different seedings of the random number generators. The metrics used to evaluate the models are the Root Mean Squared Error (RMSE) and the Mean Absolute Error (MAE). Two scores are reported for each of the LSTM-based and N-BEATS-based recommendation models: \begin{enumerate} \item The {\bf $\langle$model$\rangle$.mean} score calculates the average RMSE and MAE on the testing data across the 10 models trained for each subject, and then averages these scores across all subjects. \item The {\bf $\langle$model$\rangle$.best} score instead selects for each subject the model that performed best in terms of MAE on the validation data, out of the 10 models trained for that subject. The RMSE and MAE test scores are averaged over all subjects. \end{enumerate} Two sets of models were trained for each recommendation scenario: a set of models was trained and evaluated on {\it inertial} examples and a set was trained and evaluated on {\it unrestricted} examples. \subsection{Subject Selection for Testing in Each Recommendation Scenario} While using both the 2018 and 2020 subsets of the OhioT1DM Dataset \cite{ohiot1dm:marling:kdh18, ohiot1dm:marling:kdh20} provides us with data from 12 total subjects, not all 12 can be used in each scenario, due to insufficient examples in their respective development or test subsets. The subjects whose data was used or not at test time are listed below for each scenario, together with a justification: \begin{itemize} \item {\it Carbs$^{(\pm b)}$ Recommendation}: Subjects 567 and 570 were left out at test time. Subject 567 had 0 meal events in the testing portion of their data. Subject 570 frequently used dual boluses; as such, there were very few inertial examples for this subject at all. Of the few inertial examples that were available, 0 were in the testing or validation portions of the data. \item {\it Carbs$^{(-b)}$ Recommendation}: Due to the limited number of examples for this scenario, we trained and evaluated models only for the subjects whose data contained at least 50 carb events with no associated bolus. These are subjects 559, 575, 588, and 591. While subject 596 also had a sufficient number of carb events, we discovered that all carbohydrate inputs for their BW were 0. As a consequence of this missing data, it cannot be determined which boluses were used for BGL correction, and which were used to cover meals. Therefore, subject 596 cannot be used in this scenario. \item {\it Bolus$^{(\pm c)}$ Recommendation}: Subjects 544 and 567 were left out at test time. Subject 544 had few inertial examples overall, and 0 in the validation portion of the data. This is because the vast majority of bolus events in their data was used in conjunction with a meal. Similar to the carbohydrate recommendation scenario, subject 567 was not used in this scenario because of the lack of meal events in their test data. The missing meal data would make the bolus recommendation results for this subject unrealistic and also indistinguishable between the inertial and unrestricted cases. \item {\it Bolus$^{(+c)}$ Recommendation}: Subjects 567, 570, and 596 were left out at test time. As explained for other scenarios above, subject 567 had 0 meals in the test portion of their data. For subject 570, there were 0 inertial examples in the test portion. As explained for the Carbs$^{-b}$ recommendation scenario, due to missing BW data, for subject 596 it cannot be determined which boluses were used for BGL correction, and which were used to cover meals, so their data cannot be used in this scenario, either. \end{itemize} Irrespective of which subjects are used at test time, the data from all 12 patients is used for pre-training purposes in each recommendation scenario. Furthermore, the set of subjects stays consistent between the inertial and unrestricted cases for any given recommendation scenario. \subsection{Evaluating the Impact of Pre-processing of Meals} \label{sec:pre-evaluation} To determine the utility of the pre-processing of meals procedure introduced in Section~\ref{sec:pre-processing}, we trained and evaluated N-BEATS-based models for the carbohydrate recommendation scenario Carbs$^{(\pm b)}$ using the original data vs. using the pre-processed data. When training on pre-processed data, we report in Table~\ref{tab:pre-carbs} two development results: when evaluating on all the pre-processed meals in the development data (pre$^+$) vs. evaluating only on meals that were not added during pre-processing (pre$^-$). The results show that in both cases the pre-processing of meals leads to statistically significant improvements in RMSE and MAE. Pre-processing of meals also benefits the bolus recommendation scenario, as shown in Table~\ref{tab:pre-bolus}. These results can be seen as further evidence of the fact that the meal timestamps recorded in the smartphone interface are unreliable and that meal times should instead be anchored to the bolus timestamps recorded by the BW, as done in the pre-processing procedure. \begin{table}[ht] \setlength{\tabcolsep}{4pt} \caption{Results with pre-processing of meals (pre) vs. original raw data for meal events (raw), for the carbohydrate recommendation scenario Carbs$^{(\pm b)}$ on unrestricted examples. pre$^+$ refers to using all pre-processed meals (shifted original meals and added meals), whereas pre$^-$ does not use meals added by the pre-processing procedure. The symbol $\dagger$ indicates a p-value < 0.03 when using a one-tailed t-test to compare against the results without pre-processing (raw).} \begin{center} \label{tab:pre-carbs} \begin{tabular}{|l|ll|rr|} \cline{2-3} \multicolumn{1}{c|}{} & \multicolumn{2}{c|}{Pre-processing} & \multicolumn{2}{c}{} \\ \cline{2-5} \multicolumn{1}{c|}{} & Train & Devel & RMSE & MAE\\ \hline \multirow{2}{*}{N-BEATS.mean} & raw & raw & 13.42 & 10.32\\ & pre$^+$ & pre$^-$ & $^\dagger$9.38 & $^\dagger$6.59\\ & pre$^+$ & pre$^+$ & $^\dagger${\bf 8.84} & $^\dagger${\bf 6.16}\\ \hline \multirow{2}{*}{N-BEATS.best} & raw & raw & 12.32 & 9.28\\ & pre$^+$ & pre$^-$ & $^\dagger$8.48 & $^\dagger$5.90\\ & pre$^+$ & pre$^+$ & $^\dagger${\bf 8.12} & $^\dagger${\bf 5.53}\\ \hline \end{tabular} \end{center} \end{table} \begin{table}[ht] \setlength{\tabcolsep}{4pt} \caption{Results with pre-processing of meals (pre) vs. original raw data for meal events (raw), for the Bolus$^{(\pm c)}$ recommendation scenario on unrestricted examples. All meals (shifted or added) are used for the pre-processed data. The symbol $\dagger$ indicates a p-value < 0.01 when using a one-tailed t-test to compare against the results without pre-processing (raw).} \begin{center} \label{tab:pre-bolus} \begin{tabular}{|l|c|rr|} \cline{2-4} \multicolumn{1}{c|}{} & Pre-processing & RMSE & MAE\\ \hline \multirow{2}{*}{N-BEATS.mean} & raw & 1.85 & 1.41\\ & pre & $^\dagger${\bf 1.30} & $^\dagger${\bf 0.92}\\ \hline \multirow{2}{*}{N-BEATS.best} & raw & 1.81 & 1.32 \\ & pre & $^\dagger${\bf 1.22} & $^\dagger${\bf 0.84}\\ \hline \end{tabular} \end{center} \end{table} \subsection{Tuning the Architecture and the Hyper-parameters on the Development Data} \label{sec:development} Table~\ref{tab:state1} show the results of the LSTM- and N-BEATS-based models, with vs. without using the final state produced by the LSTM$_1$ component as input to the fully connected network. The results show that using the final state from LSTM$_1$ directly as input leads to a substantial improvement for the carbohydrate recommendation scenario Carbs$^{(\pm b)}$, while maintaining a comparable performance for the bolus recommendation scenario. Consequently, in all remaining experiments the architecture is set to use the final state of LSTM$_1$ as input to the FC layers. \begin{table}[ht] \caption{Performance of the LSTM- and N-BEATS-based models, with ($+$) and without ($-$) the final state $s_1$ of LSTM$_{1}$ as part of the input to the FC Layers.} \begin{center} \label{tab:ablation_lstm1} \begin{tabular}{|c|c|rr|c|c|c|rr|} \cline{3-4} \cline{8-9} \multicolumn{2}{c|}{LSTM.mean} & RMSE & MAE & \multicolumn{1}{c}{} & \multicolumn{2}{c|}{N-BEATS.mean} & RMSE & MAE\\ \cline{1-4} \cline{6-9} \multirow{2}{*}{Carbs$^{(\pm b)}$} & $- s_1$ & 10.14 & 7.56 & & \multirow{2}{*}{Carbs$^{(\pm b)}$} & $- s_1$ & 10.27 & 7.58\\ & $+ s_1$ & {\bf 8.99} & {\bf 6.57} & & & $+ s_1$ & {\bf 8.84} & {\bf 6.16}\\ \cline{1-4} \cline{6-9} \multirow{2}{*}{Bolus$^{(\pm c)}$} & $- s_1$ & {\bf 1.33} & {\bf 0.97} & & \multirow{2}{*}{Bolus$^{(\pm c)}$} & $- s_1$ & 1.33 & {\bf 0.85}\\ & $+ s_1$ & 1.41 & 1.03 & & & $+ s_1$ & {\bf 1.30} & 0.92\\ \cline{1-4} \cline{6-9} \end{tabular} \end{center} \label{tab:state1} \end{table} In the original N-BEATS model of \citet{oreshkin:nbeats}, the backcast and forecast outputs of each block are produced as the result of two separate fully connected layers. In the block architecture shown in Figures~\ref{fig:carbs},~\ref{fig:bolus}, and~\ref{fig:nbeats} however, the {\it FC Layers} component uses just one final fully connected layer to produce both backcast and forecast values. The results in Table~\ref{tab:splitting} show that, overall, using a joint final layer is competitive or better than using separate layers. \begin{table}[ht] \caption{N-BEATS-based model results, with a {\it separate} vs. {\it joint} final fully connected layer for computing backcast and forecast values.} \begin{center} \label{tab:ablation_split} \begin{tabular}{|c|c|c|c|} \cline{3-4} \multicolumn{2}{c|}{N-BEATS.mean} & RMSE & MAE\\ \hline \multirow{2}{*}{Carbs$^{(\pm b)}$} & {\it separate} & {\bf 8.77} & 6.48\\ & {\it joint} & 8.84 & {\bf 6.16}\\ \hline \multirow{2}{*}{Bolus$^{(\pm c)}$} & {\it separate} & 1.32 & 0.94\\ & {\it joint} & {\bf 1.30} & {\bf 0.92}\\ \hline \end{tabular} \end{center} \label{tab:splitting} \end{table} For each prediction scenario, the hyper-parameters for both the LSTM-based and N-BEATS-based models were tuned on development data. The inertial and unrestricted models are tuned independent of each other. The learning rate was tuned by monitoring the learning curves, using values between 0.0002 \cite{rubin_falcone:nbeats_bgl} and 0.1. After multiple experiments, a fixed learning rate of 0.001 was observed to give the best results on development data in all scenarios. The number of blocks in N-BEATS, the number of FC layers in the LSTM, and the dropout rate were then tuned in that order. The number of N-BEATS blocks was selected from \{1, ..., 10\}, the number of layers was selected from \{1, 2, 3, 4, 5\}, whereas the dropout rate was tuned with values from \{0, 0.1, 0.2, 0.3, 0.4 0.5\}. The tuned values are shown in Table~\ref{tab:hyper-lstm} for the LSTM models and Table~\ref{tab:hyper-nbeats} for the N-BEATS models. Overall, the LSTM-based models worked best with only 2 or 3 fully connected layers in all scenarios, whereas the N-BEATS-based models worked best with 4 or 5 fully connected layers. The tuned number of blocks in the N-BEATS-based models varied between 3 and 5, depending on the scenario and the unrestricted vs. inertial case. The tuned dropout rates varied a lot between scenarios for the LSTM-based models, with rates ranging from 0 to 0.5, whereas the tuned rates for N-BEATS-based models varied between 0.2 and 0.5. \begin{table}[ht] \caption{Tuned hyper-parameters for the LSTM-based models.} \label{tab:hyper-lstm} \begin{center} \begin{tabular}{|c|c|c|c|} \cline{3-4} \multicolumn{2}{l}{} & \multicolumn{2}{|c|}{Hyper-Parameters}\\ \hline Scenario & Examples & FC Layers & Dropout\\ \hline \multirow{2}{*}{Carbs$^{(\pm b)}$} & Inertial & 3 & 0.1\\ & Unrestricted & 3 & 0.1\\ \hline \multirow{2}{*}{Bolus$^{(\pm c)}$} & Inertial & 3 & 0.0\\ & Unrestricted & 2 & 0.3\\ \hline \multirow{2}{*}{Bolus$^{(+c)}$} & Inertial & 2 & 0.2\\ & Unrestricted & 2 & 0.5\\ \hline \end{tabular} \end{center} \end{table} \begin{table}[ht] \caption{Tuned hyper-parameters for the N-BEATS-based models.} \label{tab:hyper-nbeats} \begin{center} \begin{tabular}{|c|c|c|c|c|} \cline{3-5} \multicolumn{2}{l}{} & \multicolumn{3}{|c|}{Hyper-Parameters}\\ \hline Scenario & Examples & Blocks & FC Layers & Dropout\\ \hline \multirow{2}{*}{Carbs$^{(\pm b)}$} & Inertial & 5 & 2 & 0.3\\ & Unrestricted & 3 & 3 & 0.3\\ \hline \multirow{2}{*}{Bolus$^{(\pm c)}$} & Inertial & 5 & 4 & 0.2\\ & Unrestricted & 4 & 4 & 0.2\\ \hline \multirow{2}{*}{Bolus$^{(+c)}$} & Inertial & 5 & 4 & 0.5\\ & Unrestricted & 3 & 5 & 0.2\\ \hline \end{tabular} \end{center} \end{table} The size of the LSTM state was tuned to 32, whereas the size of each fully connected layer was tuned to 64, which is substantially smaller than the hidden size of 512 used in the original N-BEATS model \cite{oreshkin:nbeats}. For the carbohydrates without bolus scenario Carbs$^{(-b)}$, due to the much smaller number of examples, we reduced the number of units in the LSTM networks and fully connected layers by a factor of 2. The same hyper-parameters that were tuned on the general carbohydrate recommendation scenario Carbs$^{(\pm b)}$ were used for Carbs$^{(-b)}$. \section{Experimental Results} \label{sec:results} \begin{table*}[t]\setlength{\tabcolsep}{4pt} \caption{Results for each recommendation scenario, for both classes of examples. The simple $\dagger$ indicates a p-value < 0.05 when using a one-tailed t-test to compare against the baseline results; the double $\ddagger$ indicates statistical significance for comparison against the baselines as well as against the competing neural method; the $\uparrow$ indicates significant with respect to the Global Average baseline only.} \begin{center} \label{tab:results} \begin{tabular}{|l|rr|rr|} \cline{2-5} \multicolumn{1}{c}{} & \multicolumn{2}{|c|}{Inertial} & \multicolumn{2}{c|}{Unrestricted}\\ \hline Carbs$^{(\pm b)}$ recommendation & RMSE & MAE & RMSE & MAE\\ \hline Global Average & 20.90 & 17.30 & 20.68 & 17.10\\ ToD Average & 20.01 & 15.78 & 19.82 & 15.68\\ \hline LSTM.mean & 11.55 & 7.81 & 10.99 & 7.40\\ LSTM.best & 10.95 & 7.50 & 10.50 & 7.31\\ \hline N-BEATS.mean & $^\ddagger${\bf 9.79} & $^\ddagger${\bf 6.45} & 10.34 & 7.04\\ N-BEATS.best & 9.92 & 6.56 & $^\dagger${\bf 10.07} & $^\dagger${\bf 6.75}\\ \hline \multicolumn{5}{c}{}\\[-1.5ex] \cline{2-5} \multicolumn{1}{c}{} & \multicolumn{2}{|c|}{Inertial} & \multicolumn{2}{c|}{Unrestricted}\\ \hline Carbs$^{(-b)}$ recommendation & RMSE & MAE & RMSE & MAE\\ \hline Global Average & 15.92 & 13.71 & 14.66 & 12.19\\ ToD Average & 15.55 & 13.45 & 14.27 & 11.93\\ \hline LSTM.mean & 14.02 & 11.47 & 14.70 & 12.27\\ LSTM.best & 13.75 & 10.92 & 14.94 & 12.57\\ \hline N-BEATS.mean & {\bf 13.76} & {\bf 11.42} & $^\uparrow${\bf 13.69} & $^\uparrow${\bf 11.09}\\ N-BEATS.best & 14.52 & 11.78 & 14.17 & 11.47\\ \hline \multicolumn{5}{c}{}\\[-1.5ex] \cline{2-5} \multicolumn{1}{c}{} & \multicolumn{2}{|c|}{Inertial} & \multicolumn{2}{c|}{Unrestricted}\\ \hline Bolus$^{(\pm c)}$ recommendation & RMSE & MAE & RMSE & MAE\\ \hline Global Average & 2.40 & 2.13 & 2.84 & 2.30\\ ToD Average & 2.21 & 1.86 & 2.71 & 2.17\\ \hline LSTM.mean & 1.75 & 1.35 & 1.53 & 1.10\\ LSTM.best & 1.70 & 1.30 & 1.50 & 1.05\\ \hline N-BEATS.mean & $^\dagger${\bf 1.56} & $^\ddagger${\bf 1.20} & $^\dagger${\bf 1.49} & 1.04\\ N-BEATS.best & 1.65 & 1.26 & 1.51 & $^\dagger${\bf 1.03}\\ \hline \multicolumn{5}{c}{}\\[-1.5ex] \cline{2-5} \multicolumn{1}{c}{} & \multicolumn{2}{|c|}{Inertial} & \multicolumn{2}{c|}{Unrestricted}\\ \hline Bolus$^{(+c)}$ recommendation & RMSE & MAE & RMSE & MAE\\ \hline Global Average & 3.00 & 2.35 & 3.04 & 2.39\\ ToD Average & 2.87 & 2.21 & 2.90 & 2.25\\ \hline LSTM.mean & 1.02 & 0.73 & {\bf 1.00} & 0.73\\ LSTM.best & 0.94 & 0.67 & $^\dagger${\bf 1.00} & $^\dagger${\bf 0.72}\\ \hline N-BEATS.mean & 0.89 & 0.65 & 1.11 & 0.82\\ N-BEATS.best & $^\dagger${\bf 0.85} & $^\dagger${\bf 0.61} & 1.06 & 0.78\\ \hline \end{tabular} \end{center} \end{table*} Table~\ref{tab:results} shows the results for the two baselines and the two neural architectures: the LSTM-based (Figures~\ref{fig:carbs} and ~\ref{fig:bolus}) and the N-BEATS-based (Figure~\ref{fig:nbeats}). Across all scenarios and for both example classes, the neural models outperform both baselines, often by a wide margin. Furthermore, the N-BEATS-based models outperform their LSTM-based counterparts across all evaluations with inertial examples, which are the ones with the most practical utility. In general, there is little difference between the best model scores and the average model scores, which means that the model performance is relatively stable with respect to the random initialization of the network parameters. For the prediction of carbohydrates without an associated bolus scenario Carbs$^{(-b)}$, the improvement brought by the two neural models over the two baselines was less substantial, which is to be expected for two reasons. First, the baselines do much better in this scenario than in the more general carbohydrate recommendation scenario Carbs$^{(\pm b)}$ because most of the carb intakes are relatively small, e.g. hypo correction events where subjects are advised to eat a fixed amount of carbohydrate. Second, and most importantly, the number of training carbohydrate events and their associated examples in the Carbs$^{(-b)}$ scenario is much smaller than in the Carbs$^{(\pm b)}$ scenario (Table~\ref{tab:meals}), which makes ML models much less effective. In all experiments reported so far, one model was trained for all prediction horizons, using the value of $\tau \in \{30, 35, ..., 90\}$ as an additional input feature. This global model was then tested on examples from all prediction horizons. To determine if transfer learning happens among different prediction horizons, for each value of $\tau \in \{30, 45, 60, 75, 90\}$ at test time, we compare the performance of the globally trained model vs. the performance of a model trained only on examples for that particular prediction horizon, using inertial examples for both. We chose the inertial case for this experiment because it corresponds better to the intended use of a carbohydrate or bolus recommendation system. Furthermore, we experiment only with the N-BEATS-based model because of its better performance in the inertial case. The results in Table \ref{tab:transfer_time} show transfer learning clearly happening for the carbohydrate recommendation Carbs$^{(\pm b)}$ and bolus given carbs recommendation Bolus$^{(+c)}$ scenarios, where the models trained on all prediction horizons outperform those trained only on a specific prediction horizon when evaluated on that prediction horizon. For the bolus recommendation scenario Bolus$^{(-c)}$ (i.e. Bolus$^{(\pm c)}$ inertial) the results were mixed, with transfer learning being clear only for the short $\tau = 30$ time horizon. Transfer learning results for the Carbs$^{(-b)}$ scenario are not calculated due to the lack of a sufficient number of training examples for each prediction horizon. \begin{table}[ht] \setlength{\tabcolsep}{1.75pt} \caption{Comparison between models trained on all prediction horizons vs. one prediction horizon $\tau$, when evaluated on the prediction horizon $\tau$. The symbol $\dagger$ indicates a p-value < 0.05 when using a one-tailed t-test to compare against the one prediction horizon results.} \begin{center} \label{tab:transfer_time} \begin{tabular}{|c|c|rr|rr|rr|rr|rr|rr|rr} \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{12}{c|}{Carbs$^{(\pm b)}$ recommendation}\\ \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{2}{c|}{$\tau=30$} & \multicolumn{2}{c|}{$\tau=45$} & \multicolumn{2}{c|}{$\tau=60$} & \multicolumn{2}{c|}{$\tau=75$} & \multicolumn{2}{c|}{$\tau=90$} & \multicolumn{2}{c|}{Average}\\ \cline{2-14} \multicolumn{1}{c|}{}& Trained on & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} \\ \hline \multirow{2}{*}{N-BEATS.mean} & One $\tau$ & {\bf 9.74} & 6.72 & 10.24 & 6.89 & 10.06 & 6.85 & 10.52 & 7.19 & 9.82 & 6.73 & 10.08 & 6.88\\ & All $\tau$ & 9.96 & {\bf 6.57} & {\bf 9.98} & {\bf 6.56} & {\bf 9.84} & {\bf 6.50} & $^\dagger${\bf 9.55} & $^\dagger${\bf 6.30}& {\bf 9.37} & {\bf 6.22} & {\bf 9.74} & {\bf 6.43}\\ \hline \multirow{2}{*}{N-BEATS.best} & One $\tau$ & 9.92 & 6.70 & 10.39 & 6.90 & 10.21 & 6.88 & 10.62 & 7.18 & 9.92 & 6.66 & 10.21 & 6.86\\ & All $\tau$ & {\bf 9.84} & {\bf 6.50} & {\bf 9.94} & {\bf 6.56} & {\bf 10.02} & {\bf 6.57} & {\bf 9.76} & $^\dagger${\bf 6.34} & {\bf 9.43} & {\bf 6.08} & {\bf 9.80} & {\bf 6.41}\\ \hline \multicolumn{14}{c}{}\\[-1.5ex] \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{12}{c|}{Bolus$^{(-c)}$ recommendation}\\ \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{2}{c|}{$\tau=30$} & \multicolumn{2}{c|}{$\tau=45$} & \multicolumn{2}{c|}{$\tau=60$} & \multicolumn{2}{c|}{$\tau=75$} & \multicolumn{2}{c|}{$\tau=90$} & \multicolumn{2}{c|}{Average}\\ \cline{2-14} \multicolumn{1}{c|}{}& Trained on & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} \\ \hline \multirow{2}{*}{N-BEATS.mean} & One $\tau$ & 1.82 & 1.42 & {\bf 1.57} & {\bf 1.24} & 1.51 & 1.24 & {\bf 1.37} & {\bf 1.10} & 1.40 & 1.17 & 1.53 & 1.23\\ & All $\tau$ & {\bf 1.75} & {\bf 1.33} & 1.61 & {\bf 1.24} & {\bf 1.47} & $^\dagger${\bf 1.17} & 1.38 & {\bf 1.10} & {\bf 1.28} & $^\dagger${\bf 1.03} & {\bf 1.50} & $^\dagger${\bf 1.17}\\ \hline \multirow{2}{*}{N-BEATS.best} & One $\tau$ & 1.77 & 1.37 & {\bf 1.54} & {\bf 1.21} & {\bf 1.51} & {\bf 1.23} & {\bf 1.38} & {\bf 1.10} & {\bf 1.34} & {\bf 1.11} & {\bf 1.51} & {\bf 1.20}\\ & All $\tau$ & {\bf 1.72} & {\bf 1.28} & 1.75 & 1.33 & 1.58 & {\bf 1.23} & 1.45 & 1.12 & 1.44 & 1.13 & 1.59 & 1.22\\ \hline \multicolumn{14}{c}{}\\[-1.5ex] \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{12}{c|}{Bolus$^{(+c)}$ recommendation}\\ \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{2}{c|}{$\tau=30$} & \multicolumn{2}{c|}{$\tau=45$} & \multicolumn{2}{c|}{$\tau=60$} & \multicolumn{2}{c|}{$\tau=75$} & \multicolumn{2}{c|}{$\tau=90$} & \multicolumn{2}{c|}{Average}\\ \cline{2-14} \multicolumn{1}{c|}{}& Trained on & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} \\ \hline \multirow{2}{*}{N-BEATS.mean} & One $\tau$ & 0.98 & 0.73 & 0.91 & 0.69 & 0.91 & 0.69 & 0.95 & 0.74 & 0.93 & 0.72 & 0.94 & 0.71\\ & All $\tau$ & {\bf 0.95} & {\bf 0.68} & {\bf 0.87} & {\bf 0.65} & {\bf 0.86} & {\bf 0.65} & $^\dagger${\bf 0.87} & $^\dagger${\bf 0.65} & $^\dagger${\bf 0.86} & $^\dagger${\bf 0.64} & $^\dagger${\bf 0.88} & $^\dagger${\bf 0.65}\\ \hline \multirow{2}{*}{N-BEATS.best} & One $\tau$ & {\bf 0.94} & 0.69 & 0.91 & 0.69 & 0.92 & 0.68 & 0.93 & 0.71 & 0.91 & 0.70 & 0.92 & 0.69\\ & All $\tau$ & {\bf 0.94} & {\bf 0.66} & {\bf 0.84} & $^\dagger${\bf 0.62} & $^\dagger${\bf 0.82} & $^\dagger${\bf 0.59} & $^\dagger${\bf 0.82} & $^\dagger${\bf 0.61} & $^\dagger${\bf 0.83} & $^\dagger${\bf 0.61} & $^\dagger${\bf 0.85} & $^\dagger${\bf 0.62}\\ \hline \end{tabular} \end{center} \end{table} \section{Conclusion and Future Directions} \label{sec:conclusion} We have introduced a general LSTM-based neural architecture, composed of two chained LSTMs and a fully connected network, with the purpose of training models for making recommendations with respect to any type of quantitative events that may impact blood glucose levels, in particular, carbohydrate amounts and bolus insulin dosages. A deep residual N-BEATS-based architecture was also developed, using the chained LSTMs as a component in its block structure. Experimental evaluations show that the proposed neural architectures substantially outperform a global average baseline as well as a time of day dependent baseline, with the N-BEATS-based models outperforming the LSTM-based counterparts in all evaluations with inertial examples. The trained models are shown to benefit from transfer learning and from a pre-processing of meal events that anchors their timestamps shortly after their corresponding boluses. Overall, these results suggest that the proposed recommendation approaches hold significant promise for easing the complexity of self-managing blood glucose levels in type 1 diabetes. Potential future research directions include investigating the proposed pre-processing of carbohydrate events for blood glucose level prediction and exploring the utility of the two neural architectures for recommending exercise. \authorcontributions{Jeremy Beauchamp contributed with respect to conceptualization, investigation, methodology, software, validation, writing - original draft, and writing - review \& editing. Razvan Bunescu contributed with respect to conceptualization, formal analysis, funding acquisition, methodology, project administration, resources, software, supervision, validation, visualization, writing - original draft, and writing - review \& editing. Cindy Marling contributed with respect to conceptualization, data curation, investigation, funding acquisition, and writing - review \& editing. Zhongen Li contributed with respect to methodology, software, and validation. Chang Liu contributed with respect to resources and supervision.} \funding{This research was funded by grant 1R21EB022356 from the National Institutes of Health (NIH).} \acknowledgments{Conversations with Josep Vehi helped shape the research directions presented herein. The contributions of physician collaborators Frank Schwartz, MD, and Amber Healy, DO, are gratefully acknowledged. We would also like to thank the anonymous people with type 1 diabetes who provided their blood glucose, insulin, and meal data.} \conflictsofinterest{The authors declare no conflict of interest. The funders had no role in the design of the study, in the collection, analyses, or interpretation of data, in the writing of the manuscript, or in the decision to publish the results.} \externalbibliography{yes} \section{Introduction and Motivation} Diabetes self-management is a time-consuming, yet critical, task for people with type 1 diabetes. To avoid serious diabetic complications, these individuals must continually manage their blood glucose levels (BGLs), keeping them as close to normal as possible. They must avoid both low BGLs, or hypoglycemia, and high BGLs, or hyperglycemia, for their physical safety and well-being. Diabetes self-management entails carefully monitoring BGLs throughout the day, by testing blood obtained from finger sticks and/or by using a continuous glucose monitoring (CGM) system. It also entails making numerous daily decisions about the timing and dosage of insulin and the timing, ingredients, and quantity of food consumed. Current diabetes self-management may be characterized as \emph{reactive}, rather than \emph{proactive}. When BGLs are too high, individuals may take insulin to lower them, and when BGLs are too low, they may eat a snack or take glucose tablets to raise them. The ability to accurately predict BGLs could enable people with type 1 diabetes to take preemptive actions \emph{before} experiencing the negative effects of hypoglycemia or hyperglycemia. There have been efforts to model BGLs for the purpose of determining insulin dosages dating back to the 1960s \cite{boutayeb2016}. There has been much recent work in BGL prediction for the purpose of providing support for diabetes self-management, including our own \cite{bunescu:icmla13,plis:maiha14}. Accounts of some of the most recent BGL prediction efforts can be found in the proceedings of two international BGL prediction challenges \cite{kdh-2018-proceedings,kdh-2020-proceedings}. It should be noted that, even with the benefit of accurate BGL predictions, individuals still need to determine how much to eat, how much insulin to take, and what other actions they can take to prevent hypoglycemia or hyperglycemia. The broad goal of the research presented here is to essentially reverse the BGL prediction problem, and instead predict how many grams of carbohydrate (carbs) an individual should eat or how much insulin they should take in order to achieve a desired BGL target. We have previously introduced in \cite{mirshekarian:embc19} an LSTM-based neural architecture that was trained to answer {\it what-if} questions of the type “What will my BGL be in 60 minutes if I eat a snack with 30 carbs 10 minutes from now?”. By using the BGL target as a feature and the carbohydrates or insulin as labels, we have shown in subsequent work \cite{beauchamp:kdh20} that a similar LSTM-based architecture can be trained instead to predict the number of carbs that should be consumed or the amount of insulin that should be taken during the prediction window in order to reach that BGL target. Preliminary results were reported in \cite{beauchamp:kdh20} only for the task of carbohydrate recommendation, where the aim was to achieve a desired target BGL 30 or 60 minutes into the future. The timing of the meal was variable within the prediction window and was used as one of the inputs to the model. In this paper, we update the task definition to make it more applicable to the type of situations that are frequently encountered in the self-management of type 1 diabetes. As such, the timing of the bolus or meal is now fixed at 10 minutes into the future, based on the assumption that patients are most interested in using the system right before making a meal or bolus decision. To achieve the desired BGL, the user can specify any time horizon between 30 and 90 minutes, giving them more flexibility in terms of how fast they want their BGL to change. Furthermore, we improve the LSTM-based architecture from \cite{beauchamp:kdh20} and use it as a repeating residual block in a deep residual forecasting network derived from the BGL prediction architecture recently proposed by \citet{rubin_falcone:nbeats_bgl}. The neural architecture from \cite{rubin_falcone:nbeats_bgl} is in turn a modified version of the N-BEATS architecture \cite{oreshkin:nbeats} that was shown to obtain state-of-the-art results on a wide array of time series forecasting problems. Overall, the new recommendation approach using the integrated deep network is generic in the sense that it can be trained to make recommendations about any variable that can impact BGLs, in particular, carbohydrates and insulin. Carbohydrate recommendations are potentially useful when someone wants to prevent hypoglycemia well in advance or when someone wants to achieve a higher target BGL before physical exercise that is expected to lower it. Bolus recommendations are useful prior to meals and also for lowering BGLs when individuals experience hyperglycemia. The rest of the paper is organized as follows: Section~\ref{sec:related} presents related work in blood glucose level prediction and automated bolus calculators, and positions our work in relation to recent developments in these areas. Three major recommendation scenarios are introduced in Section~\ref{sec:scenarios}, followed in Section~\ref{sec:models} by a description of a set of baseline models and neural architectures that are designed to make recommendations in each of these scenarios. Section~\ref{sec:dataset} introduces the OhioT1DM dataset and explains how recommendation examples were derived from it. The experimental methodology and results are presented in Sections~\ref{sec:methodology} and~\ref{sec:results}, respectively. The paper concludes in Section~\ref{sec:conclusion} with a summary of our contributions and ideas for future work. \section{Related Work} \label{sec:related} Bolus calculators have been in use since 2003 \cite{gross:calculator}, wherein a standard formula is used to calculate a recommended insulin dosage, taking into count parameters such as carbohydrate intake, carbohydrate-to-insulin ratio, insulin on board, and target BGL. \citet{walsh:jdst18} discuss some major sources of errors and the potential improvements that could be made to bolus advisors. One such improvement mentioned was the utilization of the massive amount of clinical data that is collected from these bolus advisor systems. AI techniques have been used to take advantage of this data to create more intelligent and personalized insulin recommendation systems. \citet{pesl:case_based} describe a bolus advisor system based on case-based reasoning that personalizes an individual's bolus calculations. The system gathers simple information, such as the range of recent blood glucose levels and the time of day, and compares the current situation to situations from the past to find similar cases. The system then uses the bolus recommendation from a similar previous case and adapts it to the current scenario. The work by \citet{tyler:knn} shows a K-nearest-neighbors based system that provides weekly recommendations to improve the effectiveness of an individual's multiple daily injection therapy. With the amount of clinical data collected from CGM systems and wearable sensors, deep learning is a natural fit for insulin advisor systems. The work in \citet{stavroula:dtt} represents an early attempt at creating insulin recommendations by utilizing neural networks. \citet{cappon:jdst18} observe that the standard formula approach to bolus calculation ignores potentially important preprandial conditions, such as the glucose rate of change. To address this, they propose a simple feed-forward neural network that utilizes CGM data and other easily accessible factors to personalize the bolus calculation. The experimental evaluations on simulated data show a small, but statistically significant improvement in the blood glucose risk index. Simulated data is also used by \citet{sun:jbhi19}, where a basal-bolus advisor is trained using reinforcement learning in order to provide personalized suggestions to people with type 1 diabetes taking multiple daily injections of insulin. \citet{zhu:bolus_drl} also utilize simulated type 1 diabetes data for their deep reinforcement learning approach to personalizing bolus calculations. They use the UVA/Padova type 1 diabetes simulator \cite{dalla_man:simulator} to train models to learn how to reduce or amplify the bolus dose recommended by a bolus calculator to provide more personalized recommendations. In contrast with previous work that used a type 1 diabetes simulator \cite{cappon:jdst18,sun:jbhi19,zhu:bolus_drl}, the systems described in this paper are trained and evaluated on data acquired from people with type 1 diabetes, derived from the OhioT1DM dataset \cite{ohiot1dm:marling:kdh18} as explained in Section~\ref{sec:dataset}. The case-based reasoning system introduced by \citet{pesl:case_based} also makes use of real-patient data; however, their system does not learn directly from this data. Instead, it learns from clinical experts' advice, requiring also that the system is tweaked on a regular basis. Elsewhere \cite{mirshekarian:embc19}, we have shown that patterns that are learned from simulated data do not always transfer to real data, and vice-versa. By training and evaluating on real data, the results reported in this paper are expected to be more representative of the actual performance of the recommendation system if it were to be deployed in practice. Most of the related work on bolus recommendations presented above use global means of evaluating system performance, such as the percentage of time BGLs are in a target range \cite{sun:jbhi19,zhu:bolus_drl}, or the blood glucose risk index \cite{cappon:jdst18}. In contrast, our approaches are evaluated retrospectively on how close their recommendations are to the actual carbohydrate content or bolus dosages that led to a particular target BGL. As such, the trained models can be used to make recommendations in order to achieve a specific BGL. The neural architectures that we propose in this paper are also general in the sense that they can be used to make recommendations for any type of discrete intervention that may impact BGLs. While, in this paper, they are evaluated on bolus, carbs, and bolus given carbs recommendations, we also see them as applicable for recommending other relevant variables, such as exercise. \section{Three Recommendation Scenarios} \label{sec:scenarios} We assume that blood glucose levels are measured at 5 minute intervals through a CGM system. We also assume that discrete deliveries of insulin (boluses) and continuous infusions of insulin (basal rates) are recorded. Subjects provide the timing of meals and estimates of the number of grams of carbohydrate in each meal. Given the available data up to and including the present (time $t$), the system aims to estimate how much a person should eat or bolus 10 minutes from now (time $t+10$) such that their blood glucose will reach a target level $\tau$ minutes after that action (time $t + 10 + \tau$). A system that computes these estimates could then be used in the following three recommendation scenarios: \begin{enumerate} \item {\bf Carbohydrate Recommendations}: Estimate the amount of carbohydrate $C_{t+10}$ to have in a meal in order to achieve a target BG value $G_{t+10+\tau}$. \item {\bf Bolus Recommendations}: Estimate the amount of insulin $B_{t+10}$ to deliver with a bolus in order to achieve a target BG value $G_{t+10+\tau}$. \item {\bf Bolus Recommendations given Carbohydrates}: Expecting that a meal with $C_{t+20}$ grams of carbohydrate will be consumed 20 minutes from now, estimate the amount of insulin $B_{t+10}$ to deliver with a bolus 10 minutes before the meal in order to achieve a target BG value $G_{t+10+\tau}$. \end{enumerate} These recommendation scenarios were designed to align with decision-making situations commonly encountered by people with type 1 diabetes. In particular, the corresponding recommendation systems would help an individual to estimate how much to eat or bolus for the purpose of raising or lowering their BGL (scenarios 1 and 2), as well as how much to bolus for a planned meal (scenario 3). In the following Section~\ref{sec:models}, we describe a number of baseline models and neural architectures, all implementing the three types of recommendations. The neural architectures use Long Short-Term Memory (LSTM) networks either in a standalone prediction model (Section~\ref{sec:lstm}) or integrated as basic repeating blocks in a deep residual network (Section~\ref{sec:nbeats}). The models are trained on examples extracted from the OhioT1DM dataset~\cite{ohiot1dm:marling:kdh18}, as explained in Section~\ref{sec:dataset}. Ideally, to match the intended use of these recommendations in practice, training examples should not have any extra meals or boluses in the prediction window $[t, t + 10 + \tau]$. Following the terminology from \cite{mirshekarian:embc19}, we call these examples {\it inertial}. However, to benefit from a larger number of training examples, we also train and evaluate models on a more general class of {\it unrestricted} examples, in which other bolus or meal events are allowed to appear in the prediction window. Correspondingly, experimental results for inertial vs. unrestricted examples are presented in Section~\ref{sec:results}. \section{Baseline Models and Neural Architectures} \label{sec:models} Given training data containing time series of blood glucose levels, meals with their carbohydrate intake, and boluses with their corresponding insulin dosages, we define the following two baselines: \begin{enumerate} \item {\bf Global average}: For the carbohydrate recommendation scenario, the average number $\mu$ of carbs over all of the meals in the subject's training data is computed and used as the estimate for all future predictions for that subject, irrespective of the context of the example. Analogously, for the bolus and bolus given carbs recommendation scenarios, $\mu$ is the average amount of insulin dosage over all boluses in the subject's training data. This is a fairly simple baseline, as it predicts the same average value for every test example for a particular subject. \item {\bf ToD average}: In this Time-of-Day (ToD) dependent baseline, an average number of carbs or an average amount of bolus insulin is computed for each of the following five time windows during a day: \begin{itemize} \item 12am-6am: $\mu_1$ = early breakfast / late snacks. \item 6am-10am: $\mu_2$ = breakfast. \item 10am-2pm: $\mu_3$ = lunch. \item 2pm-6pm: $\mu_4$ = dinner. \item 6pm-12am: $\mu_5$ = late dinner / post-dinner snacks. \end{itemize} The average for each ToD interval is calculated over all of the meals or boluses appearing in the corresponding time frame in the subject's training data. At test time, to make a recommendation for time $t+10$, we first determine the ToD interval that contains $t+10$ and output the corresponding ToD average. \end{enumerate} Given sufficient historical data, the ToD baseline is expected to perform well for individuals who tend to eat very consistently and have regular diets. However, it is expected to perform poorly for individuals who have a lot of variation in their diets. \begin{figure*}[t] \includegraphics[width=\textwidth]{carbs-block} \caption{The general neural network architecture for the carbohydrate recommendation scenario. The dashed blue line in the graph represents a subject's BGL, while the solid brown line represents the basal rate of insulin. The gray star represents the meal at time $t+10$. The other meals are represented by squares, and boluses are represented by circles. Meals and boluses with a red outline cannot appear in {\it inertial} examples, but are allowed in {\it unrestricted} examples. The blue units in $\text{LSTM}_{1}$ receive input from different time steps in the past. The green units in $\text{LSTM}_{2}$ receive input from the prediction window. The purple trapezoid represents the 5 fully connected layers, whereas the output node at the end computes the prediction.} \label{fig:carbs} \end{figure*} \begin{figure*}[t] \includegraphics[width=\textwidth]{bolus-block} \caption{The general neural network architecture for the bolus and bolus given carbs recommendation scenarios. The architecture itself is similar to that shown in Figure~\ref{fig:carbs}. The grey star now represents the bolus at time $t+10$. For the bolus recommendation scenario, the events outlined in red or orange are not allowed in {\it inertial} examples. However, in the bolus given carbs scenario, the meal event $C_{t+20}$ shown with the yellow outline is an important part of each example, be it inertial or unrestricted. As such, in this scenario, the dashed $C_{t+20}$ becomes part of the input to the FCN.} \label{fig:bolus} \end{figure*} \begin{figure*}[t] \includegraphics[width=\textwidth]{carbs-nbeats} \caption{The N-BEATS inspired deep residual architecture for carbohydrate recommendation. A similar architecture is used for bolus and bolus given carbs recommendations.} \label{fig:nbeats} \end{figure*} \subsection{LSTM Models for Carbohydrate and Insulin Recommendation} \label{sec:lstm} While simple to compute and use at test time, the two baselines are likely to give suboptimal performance, as their predictions ignore the history of BGL values, insulin (boluses and basal rates), and meals, all of which could significantly modulate the effect a future meal and/or bolus might have on the BGL. To utilize this information, we first introduce the general LSTM-based network architecture shown in Figure~\ref{fig:carbs} for carb recommendation and Figure~\ref{fig:bolus} for bolus recommendation. The first component in the architecture is a recurrent neural network instantiated using Long Short-Term Memory (LSTM) cells \cite{hochreiter:nc97}, which is run over the previous 6 hours of data, up to and including the present time $t$. At each time step (every 5 minutes), this LSTM$_1$ network takes as input the BGL, the carbs, and the insulin dosages recorded at that time step. While sufficient for processing {\it inertial} examples, the same LSTM cannot be used to process events that may appear in the prediction window $(t, t+10+\tau)$ of {\it unrestricted} examples, because BGL values are not available in the future. Therefore, when training on unrestricted examples, the final state computed by the LSTM$_1$ model at time $t$ is projected using a linear transformation and used as the initial state for a second LSTM model, LSTM$_2$, that is run over all the time steps in the prediction window $(t, t+10+\tau)$. The final state computed by LSTM$_1$ (for inertial examples) is appended to the final state computed by LSTM$_2$ (for unrestricted examples) and is then used as input to a fully connected network (FCN) whose output node computes an estimate of the carbs or bolus insulin at time $t+10$. In addition to the LSTM final state(s), the input to the FCN contains the following features: \begin{itemize} \item The target blood glucose level $\tau+10$ minutes into the future, i.e., $G_{t + 10 + \tau}$. \item The prediction horizon $\tau$. \item The ToD average for the time frame that contains $t+10$. \item For the bolus given carbs scenario only, the planned amount $C_{t + 20}$ of carbohydrate becomes part of the input, too. \end{itemize} Each LSTM uses vectors of size 32 for the states and gates, whereas the FCN is built with up to 5 hidden layers, each consisting of 64 ReLU neurons, and one linear output node. Note that by using the final state of LSTM$_1$ to initialize LSTM$_2$, the latter's final state should theoretically be able to capture any useful information that is represented in the final state of LSTM$_1$, which may call into question the utility of concatenating the two final states. This architectural decision is nevertheless supported empirically through evaluations on the validation data, which show improvements in prediction performance when both states are used (Section~\ref{sec:development}). \subsection{Deep Residual Models for Carbohydrate and Insulin Recommendation} \label{sec:nbeats} \citet{oreshkin:nbeats} have recently introduced a new architecture for time series forecasting, the Neural Basis Expansion for Interpretable Time-Series Forecasting (N-BEATS). The basic building {\it block} of N-BEATS is a fully connected structure that initially takes as input a fixed-size {\it lookback period} of past values of the target variable and outputs both {\it forecast} (estimates of future values) and {\it backcast} (estimates of past values) vectors. Blocks are organized into {\it stacks} such that the backcast of the current block is subtracted from its input and fed as input to the next block, whereas the forecast vectors from each block are summed up to provide the overall {\it stack forecast}. The stacks themselves are chained in a pipeline where the backcast output of one stack is used as input for the next stack. The overall model forecast is then computed by accumulating the forecasts across all the stacks. The N-BEATS architecture was shown in \cite{oreshkin:nbeats} to obtain state-of-the-art performance on a wide range of time series prediction tasks, which suggests that it can serve as a model of choice for BGL prediction, too. However, in BGL prediction, time series of variables other then the primary blood glucose are also available. Correspondingly, \citet{rubin_falcone:nbeats_bgl} changed the N-BEATS block architecture to also use as input secondary, sparse variables such as meals and bolus insulin, while still backcasting only on the primary forecasting variable, blood glucose. To account for the temporal nature of the input, the fully connected structure of the basic N-BEATS block was replaced with LSTMs, followed by one fully connected layer whose output was split into the backcast and forecast vector. Additional per-block forecast and backcast loss terms were also added to provide more supervision. We adapted the deep residual network from \cite{rubin_falcone:nbeats_bgl} to perform carb or bolus recommendations by using the LSTM-based architecture from Section~\ref{sec:lstm} to instantiate each block in the stack, as shown in Figure~\ref{fig:nbeats}. Compared to the architecture from \cite{rubin_falcone:nbeats_bgl}, the most significant differences are: \begin{enumerate} \item The use of a chain of two LSTM networks in each block. \item The inclusion of additional inputs to the fully connected layers, i.e. the target BG level, the time horizon, and the ToD average. \item While backcasting is still done for blood glucose, forecasting is done for carbs or bolus, depending on the recommendation scenario. \end{enumerate} While \citet{oreshkin:nbeats} used 30 blocks and \citet{rubin_falcone:nbeats_bgl} used 10 blocks, the validation experiments for the recommendation tasks showed that the most effective deep residual architecture uses only up to 5 blocks, depending on the recommendation scenario (Section~\ref{sec:development}). \section{Using the OhioT1DM Dataset for Recommendation Examples} \label{sec:dataset} To evaluate the proposed recommendation models, we create training and test examples based on data collected from 12 subjects with type 1 diabetes that is distributed with the OhioT1DM dataset~\cite{ohiot1dm:marling:kdh20}. The 12 subjects are partitioned in two subsets as follows: \begin{enumerate} \item {\bf OhioT1DM 2018}: This is the first part of the dataset, containing data collected from 6 patients. It was used for the 2018 Blood Glucose Level Prediction (BGLP) challenge \cite{kdh-2018-proceedings}. \item {\bf OhioT1DM 2020}: This is the second part of the dataset, containing data collected from 6 additional patients. It was used for the 2020 BGLP challenge \cite{kdh-2020-proceedings}. \end{enumerate} Time series containing the basal rate of insulin, boluses, meals, and BGL readings were collected over 8 weeks, although the exact number of days varies from subject to subject. Insulin and BGL data was automatically recorded by each subject's insulin pump. Meal data was collected in two different ways. Subjects self reported meal times and estimated carbs via a smartphone interface. Subjects also entered estimated carbs into a bolus calculator when bolusing for meals, and this data was recorded by the insulin pump. \subsection{The Bolus Wizard} \label{sec:bw} To determine their insulin dosages, the subjects in the OhioT1DM study used a bolus calculator, or "Bolus Wizard (BW)," which was integrated in their insulin pumps. They used it to calculate the bolus amount before each meal as well as when using a bolus to correct for hyperglycemia. To use the BW, a subject enters their current blood glucose level and, if eating, their estimated number of grams of carbohydrate. To calculate a recommended insulin dosage, the BW uses this input from the subject, plus the amount of active insulin the subject already has in their system, along with the following three pre-programmed, patient-specific parameters: \begin{enumerate} \item The carb ratio, which indicates the number of grams of carbohydrate that are covered by a unit of insulin. \item The insulin sensitivity, which tells how much a unit of insulin is expected to lower the subject's blood glucose level. \item The target blood glucose range, which defines an individual's lower and upper boundaries for optimal blood glucose control. \end{enumerate} All three parameters may vary, for the same individual, throughout the day and over time\footnote{\url{https://www.medtronicdiabetes.com/loop-blog/4-features-of-the-bolus-wizard}}. Given this input and these parameters, the BW calculates the amount of insulin the subject should take to maintain or achieve a blood glucose level within their target range. The calculation is displayed to the subject as a recommendation, which the subject may then accept or override. Based on the inputs and the patient-specific parameters described above, the BW uses a deterministic formula to calculate the bolus amount before each meal. As such, when trained in the bolus given carbs recommendation scenario, there is the risk that the deep learning models introduced in Section~\ref{sec:models} might simply learn to reproduce this deterministic dependency between bolus and carbs, while ignoring the target BG level that is used as input. However, this is not the case in our experimental settings, for the following reasons: \begin{itemize} \item The ML models do not have access to any of the three patient-specific parameters above, which can change throughout the day and over time, and which are set based on advice from a health care professional. \item The BW uses a fixed target BG range depending on the time of day, whereas the target in the recommendation scenarios is a more specific BG level, to be achieved at a specific time in the near future. \item The amount of insulin calculated by the BW is only a recommendation, which is often overridden by subjects. We ran an analysis of the OhioT1DM dataset in which we counted how many times the amount of insulin that was actually delivered was different from the bolus recommendation. The analysis revealed that, of all the times that the BW was used, its recommendation was overridden for about a fifth of the boluses. Furthermore, there are subjects in the dataset who often did not use the BW (540 and 567), or who chose to not use the BW at all (596). \end{itemize} Therefore, the ML models will have to go beyond using solely the carbohydrate amount in the intended meal. In order to fit the bolus recommendation examples, they will need to learn the impact that a bolus has on the target BG level for the specified prediction horizon, taking into account the amount of carbohydrate in the meal as well as the history of carbs, insulin, and BG levels. This data driven approach to bolus recommendation relieves the physician from the cognitively demanding task of regularly updating parameters such as the carb ratio and the insulin sensitivity, which often requires multiple fine tuning steps. In contrast, any relevant signal that is conveyed through the carb ratio and insulin sensitivity is expected to be learned by the ML models from the data. \subsection{Pre-processing of Meals and BG Levels} \label{sec:pre-processing} While exploring the data, it was observed that self-reported meals and their associated boluses were in unexpected temporal positions relative to each other. For many meals, patients recorded a timestamp in the smartphone interface that preceded the corresponding bolus timestamp recorded in the insulin pump. This was contrary to what was recommended to the subjects by their physicians, which was to bolus shortly before the meal, and no more than 15 minutes prior to the meal. This discrepancy is likely due to subjects reporting incorrect meal times in the smartphone interface. To correct the meal events, we used the data input to the BW in the insulin pump and ran a pre-processing step that changed the timestamp of each meal associated with a bolus to be exactly 10 minutes after that bolus. For these meals, we also used the number of carbs provided to the BW, which is likely to be more accurate than the estimate provided by the subject through the smartphone interface. To determine the self-reported meal event associated with a bolus having non-zero carb input, we searched for the meal that was closest in time to the bolus, within one hour before or after it. In case there were two meals that are equally close to the bolus, we selected the one for which the number of carbs from the smartphone interface was closest to the number of carbs entered into the BW. If no self-reported meal was found within one hour of the bolus, it was assumed that the subject forgot to log their meal on the smartphone interface. As such, a meal was added 10 minutes after the bolus, using the amount of carbs specified in the BW for that bolus. Ablation results reported in Section~\ref{sec:pre-evaluation} show that this pre-processing of meal events leads to significantly more accurate predictions, which further justifies the pre-processing. All gaps in BGL data are filled in with linearly interpolated values. However, we filter out examples that meet any of the following criteria: \begin{enumerate} \item The BGL target is interpolated. \item The BGL at present time $t$ is interpolated. \item There are more than 2 interpolated BGL measurements in the one hour of data prior to time $t$. \item There are more than 12 interpolated BGL measurements in the 6 hours of data prior to time $t$. \end{enumerate} \subsection{Mapping Prototypical Recommendation Scenarios to Datasets} \label{sec:mapping} According to the definition given in Section~\ref{sec:scenarios}, the carbohydrate recommendation scenario refers to estimating the amount of carbohydrate $C_{t+10}$ to have in a meal in order to achieve a target BG value $G_{t+10+\tau}$. This is done by using the history of data up to and including the present time $t$. However, many carbohydrate intake events $C_{t+10}$ are regular meals, which means that they are preceded by a bolus event at time $t$. Since in the carbohydrate recommendation scenario we are especially interested in scenarios where the subject eats in order to correct or prevent hypoglycemia, we created two separate datasets for carbohydrate prediction: \begin{enumerate} \item Carbs$^{(\pm b)}$: this will contain examples for all carbohydrate intake events, with $(+b)$ or without $(-b)$ an associated bolus. \item Carbs$^{(-b)}$: this will contain examples only for carbohydrate intake events without $(-b)$ an associated bolus. \end{enumerate} Most of the Carbs$^{(-b)}$ examples are expected to happen in one of three scenarios: (1) when correcting for hypoglycemia; (2) before exercising; and (3) when having a bedtime snack to prevent nocturnal hypoglycemia. Given that they are only a small portion of the overall carbohdyrate events, in Section~\ref{sec:results} we present results for both Carbs$^{(\pm b)}$ and Carbs$^{(-b)}$ recommendation scenarios. Furthermore, mirroring the two bolus recommendation scenarios introduced in Section~\ref{sec:scenarios}, we introduce the following notation for the corresponding datasets: \begin{enumerate} \item Bolus$^{(\pm c)}$: this will contain examples for all bolus events, with $(+c)$ or without $(-c)$ an associated carbohydrate intake. \item Bolus$^{(+c)}$: this will contain examples only for the bolus events with $(+c)$ an associated carbohydrate intake. \end{enumerate} The three major recommendation scenarios introduced in Section~\ref{sec:scenarios} can then be mapped to the corresponding datasets as follows: \begin{enumerate} \item {\bf Carbohydrate Recommendations}: Estimate the amount of carbohydrate $C_{t+10}$ to have in a meal in order to achieve a target BG value $G_{t+10+\tau}$. \begin{itemize} \item Carbs$^{(-b)}$, inertial: this reflects the prototypical scenario where a carbohydrate intake is recommended to correct or prevent hypoglycemia. \end{itemize} \item {\bf Bolus Recommendations}: Estimate the amount of insulin $B_{t+10}$ to deliver with a bolus in order to achieve a target BG value $G_{t+10+\tau}$. \begin{itemize} \item Bolus$^{(\pm c)}$, inertial: this reflects the prototypical scenario where a bolus is recommended to correct or prevent hyperglycemia. Because in the inertial case a carb event cannot appear after the bolus, this could also be denoted as Bolus$^{(-c)}$. \end{itemize} \item {\bf Bolus Recommendations given Carbohydrates}: Expecting that a meal with $C_{t+20}$ grams of carbohydrate will be consumed 20 minutes from now, estimate the amount of insulin $B_{t+10}$ to deliver with a bolus 10 minutes before the meal in order to achieve a target BG value $G_{t+10+\tau}$. \begin{itemize} \item Bolus$^{(+c)}$, inertial: this reflects the prototypical scenario where a bolus is recommended before a meal. \end{itemize} \end{enumerate} \subsection{Carbohydrate and Bolus Statistics} \label{sec:statistics} Table~\ref{tab:meals} shows the number of carbohydrate events in each subject's pre-processed data, together with the minimum, maximum, median, average, and standard deviation for the number of carbs per meal. Overall, the average number of carbs per meal is between 22 and 69, with the exception of subjects 570 and 544 whose meal averages and standard deviations are significantly larger. Table~\ref{tab:boluses} shows similar statistics for boluses and their dosages, expressed in units of insulin. Overall, the number of boluses is more variable than the number of meals. There is also a fairly wide range of average bolus values in the data, with subject 567 having a much higher average than other subjects. It is also interesting to note that subject 570, who had the largest average carbs per meal, had more than twice the number of boluses than any other subject while at the same time having the lowest average bolus. Subject 570 also used many dual boluses, which we did not use as prediction labels because the scope of the project covers only recommendations for regular boluses. \begin{table}[t]\setlength{\tabcolsep}{4pt} \begin{center} \caption{Per subject and total meal and carbohydrate per meal statistics: Minimum, Maximum, Median, Average, and Standard Deviation (StdDev). Carbs$^{(\pm b)}$ refers to all carbohydrate intake events; Carbs$^{(-b)}$ refers to carbohydrate intakes without a bolus. Statistics are shown for the 2018 subset, the 2020 subset, and for the entire OhioT1DM dataset.} \label{tab:meals} \begin{tabular}{|crr|rrrrc|} \cline{4-8} \multicolumn{3}{c}{} & \multicolumn{5}{|c|}{Carbs Per Meal}\\ \hline Subject & \multicolumn{1}{c}{Carbs$^{(\pm b)}$} & \multicolumn{1}{c|}{Carbs$^{(-b)}$} & \multicolumn{1}{c}{Minimum} & \multicolumn{1}{c}{Maximum} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & StdDev\\ \hline 559 & 215 & 83 & 8.0 & 75.0 & 30.0 & 35.5 & 15.5\\ 563 & 225 & 28 & 5.0 & 84.0 & 31.0 & 33.8 & 18.0\\ 570 & 174 & 39 & 5.0 & 200.0 & 115.0 & 106.1 & 41.5\\ 575 & 297 & 122 & 1.0 & 110.0 & 40.0 & 40.0 & 22.0\\ 588 & 268 & 73 & 2.0 & 60.0 & 20.0 & 22.7 & 14.6\\ 591 & 264 & 60 & 3.0 & 77.0 & 28.0 & 31.5 & 14.1\\ \hline 2018 Total & 1443 & 405 & 1.0 & 200.0 & 33.0 & 41.5 & 32.7\\ \hline 540 & 234 & 14 & 1.0 & 110.0 & 40.0 & 50.2 & 29.8\\ 544 & 206 & 41 & 1.0 & 175.0 & 60.0 & 68.7 & 36.3\\ 552 & 271 & 25 & 3.0 & 135.0 & 26.0 & 36.7 & 29.3\\ 567 & 207 & 5 & 20.0 & 140.0 & 67.0 & 67.0 & 21.5\\ 584 & 233 & 44 & 15.0 & 78.0 & 60.0 & 54.6 & 11.6\\ 596 & 300 & 277 & 1.0 & 64.0 & 25.0 & 25.1 & 14.0\\ \hline 2020 Total & 1451 & 406 & 1.0 & 175.0 & 42.0 & 48.2 & 29.5\\ \hline Combined Total & 2894 & 811 & 1.0 & 200.0 & 39.0 & 44.9 & 31.3\\ \hline \end{tabular} \end{center} \end{table} \begin{table}[t]\setlength{\tabcolsep}{4pt} \begin{center} \caption{Per subject and total boluses and insulin units statistics: Minimum, Maximum, Median, Average, and Standard Deviation (StdDev). Bolus$^{(\pm c)}$ refers to all bolus events; Bolus$^{(+c)}$ refers to bolus events associated with a meal. Statistics are shown for the 2018 subset, the 2020 subset, and for the entire OhioT1DM dataset.} \label{tab:boluses} \begin{tabular}{|crr|rrrrc|} \cline{4-8} \multicolumn{3}{c|}{} & \multicolumn{5}{c|}{Insulin Per Bolus}\\ \hline Subject & \multicolumn{1}{c}{Bolus$^{(\pm c)}$} & \multicolumn{1}{c|}{Bolus$^{(+c)}$} & \multicolumn{1}{c}{Minimum} & \multicolumn{1}{c}{Maximum} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & StdDev\\ \hline 559 & 186 & 132 & 0.1 & 9.3 & 3.6 & 3.7 & 1.9\\ 563 & 424 & 197 & 0.1 & 24.7 & 7.8 & 8.0 & 4.2\\ 570 & 1,345 & 132 & 0.2 & 12.1 & 1.3 & 1.8 & 2.1\\ 575 & 271 & 175 & 0.1 & 12.8 & 4.4 & 4.1 & 3.0\\ 588 & 221 & 195 & 0.4 & 10.0 & 3.5 & 4.3 & 2.3\\ 591 & 331 & 204 & 0.1 & 9.4 & 2.9 & 3.1 & 1.8\\ \hline 2018 Total & 2,758 & 1,035 & 0.1 & 24.7 & 1.9 & 3.5 & 3.4\\ \hline 540 & 521 & 220 & 0.1 & 11.4 & 2.0 & 3.0 & 2.8\\ 544 & 264 & 149 & 0.7 & 22.5 & 5.0 & 6.5 & 4.9\\ 552 & 426 & 246 & 0.1 & 16.0 & 2.8 & 3.9 & 3.3\\ 567 & 366 & 202 & 0.2 & 25.0 & 11.4 & 12.0 & 5.8\\ 584 & 311 & 188 & 0.1 & 16.2 & 9.1 & 7.3 & 3.1\\ 596 & 230 & 0 & 0.2 & 7.6 & 3.3 & 3.0 & 1.5\\ \hline 2020 Total & 2,118 & 1,169 & 0.1 & 25.0 & 4.0 & 5.8 & 5.0\\ \hline Combined Total & 4,876 & 2,204 & 0.1 & 25.0 & 2.9 & 4.5 & 4.3\\ \hline \end{tabular} \end{center} \end{table} \subsection{From Meals and Bolus Events to Recommendation Examples} \label{sec:examples} In all recommendation scenarios, the prediction window ranges between the present time $t$ and the prediction horizon $t + 10 + \tau$. For the carbohydrate or bolus recommendation scenarios, the meal or the bolus is assumed to occur at time $t +10$. For the bolus given carbs scenario, the bolus occurs at time $t+10$ and is followed by a meal at time $t+20$, which matches the pre-processing of the meal data. For evaluation purposes, we set $\tau$ to values between 30 and 90 minutes with a step of 5 minutes, i.e, $\tau \in \{30, 35, 40, ..., 90\}$ for a total of 13 different values. As such, each meal/bolus event in the data results in 13 recommendation examples, one example for each value of $\tau$. While all 13 examples use the same value for the prediction label, e.g., $B_{t + 10}$ for bolus prediction, they will differ in terms of the target BG feature $G_{t + 10 + \tau}$ and the $\tau$ feature, both used directly as input to the FC layers in the architectures shown in Figures~\ref{fig:carbs} and~\ref{fig:bolus}. For the bolus given carbs scenario, the 13 examples are only created when there is a meal that had a bolus delivered 10 minutes prior. Due to the way the data is pre-processed, it is guaranteed that if a meal had a bolus associated with it, the bolus will be exactly 10 minutes before the meal. Table \ref{tab:c1_examples} shows the number of {\it inertial} examples for 5 prediction horizons, as well as the total over all 13 possible prediction horizons. Table \ref{tab:c2_examples} shows the number of {\it unrestricted} examples. Since the same number of unrestricted examples are available for every prediction horizon, only the totals are shown. The only exceptions would be if an event was near the end of a subject's data and the prediction horizon $t+10+\tau$ goes past the end of the dataset for some value of $\tau$. \begin{table}[ht]\setlength{\tabcolsep}{4pt} \begin{center} \caption{{\it Inertial} ({\it I}) examples by recommendation scenario and prediction horizon. Carbs$^{(\pm b)}$ refers to all carbohydrate intake events; Carbs$^{(-b)}$ refers to carbohydrate intakes without a bolus.} \label{tab:c1_examples} \begin{tabular}{|l|rrrr|rrrr|} \cline{2-9} \multicolumn{1}{c}{}& \multicolumn{4}{|c|}{Carbs$^{(\pm b)}$ recommendation} & \multicolumn{4}{c|}{Carbs$^{(-b)}$ recommendation}\\ \hline Horizon & Training & Validation & Testing & Total {\it I} & Training & Validation & Testing & Total {\it I}\\ \hline $\tau=30$ & 1,192 & 340 & 331 & 1,863 & 265 & 53 & 40 & 358\\ $\tau=45$ & 1,156 & 334 & 321 & 1,811 & 255 & 51 & 40 & 346\\ $\tau=60$ & 1,121 & 318 & 315 & 1,754 & 243 & 50 & 40 & 333\\ $\tau=75$ & 1,057 & 301 & 293 & 1,651 & 226 & 44 & 34 & 304\\ $\tau=90$ & 975 & 279 & 278 & 1,532 & 200 & 40 & 31 & 271\\ All 13 horizons & 14,343 & 4,103 & 4,007 & 22,453 & 3,100 & 620 & 486 & 4,206\\ \hline \multicolumn{5}{c}{}\\[-1.5ex] \cline{2-9} \multicolumn{1}{c}{} & \multicolumn{4}{|c|}{Bolus$^{(\pm c)}$ recommendation} & \multicolumn{4}{c|}{Bolus$^{(+ c)}$ recommendation}\\ \hline Horizon & Training & Validation & Testing & Total {\it I} & Training & Validation & Testing & Total {\it I}\\ \hline $\tau=30$ & 461 & 160 & 143 & 764 & 856 & 267 & 271 & 1,394\\ $\tau=45$ & 416 & 142 & 124 & 682 & 833 & 259 & 258 & 1,350\\ $\tau=60$ & 368 & 124 & 104 & 596 & 816 & 253 & 249 & 1,318\\ $\tau=75$ & 303 & 102 & 96 & 501 & 790 & 243 & 243 & 1,276\\ $\tau=90$ & 271 & 90 & 86 & 447 & 743 & 234 & 229 & 1,206\\ All 13 horizons & 4,732 & 1,606 & 1,423 & 7,761 & 10,514 & 3,269 & 3,249 & 17,032\\ \hline \end{tabular} \end{center} \end{table} \begin{table}[ht]\setlength{\tabcolsep}{4pt} \begin{center} \caption{{\it Unrestricted} (U) examples by recommendation scenario, also showing, in the last column, the total number of non-inertial ($U - I$) examples. Carbs$^{(\pm b)}$ refers to all carbohydrate intake events; Carbs$^{(-b)}$ refers to carbohydrate intakes without a bolus.} \label{tab:c2_examples} \begin{tabular}{|l|rrrr|r|} \hline Scenario & Training & Validation & Testing & Total $U$ & Total $U - I$\\ \hline Carbs$^{(\pm b)}$ & 17,937 & 5,106 & 4,943 & 27,986 & 5,533\\ Carbs$^{(-b)}$ & 4,140 & 853 & 624 & 5,617 & 1,411\\ Bolus$^{(\pm c)}$ & 19,640 & 6,279 & 6,136 & 32,055 & 24,294\\ Bolus$^{(+c)}$ & 12,052 & 3,784 & 3,816 & 19,652 & 2,620\\ \hline \end{tabular} \end{center} \end{table} For the carbohydrate and bolus given carbs recommendation scenarios, the gap between the number of {\it inertial} and {\it unrestricted} examples is not very large, as most examples qualify as inertial examples. However, in the bolus recommendation scenario, there is a very sizable gap between the number of inertial vs. unrestricted examples. This is because a significant number of boluses are associated with meals, and since these meals are timestamped to be 10 minutes after the bolus, the result is that a bolus at time $t + 10$ will be associated with a meal at time $t + 20$. Therefore, for preprandial boluses at $t + 10$, the meal at time $t + 20$ will prohibit the creation of inertial recommendation examples, because by definition inertial examples do not allow the presence of other events in the prediction window $(t, t + 10 + \tau)$. \section{Experimental Methodology} \label{sec:methodology} For each of the 12 subjects in the dataset, their time series data is split into three sets, as follows: \begin{itemize} \item {\it Testing}: the last 10 days of data. \item {\it Validation}: the 10 days of data preceding the testing portion. \item {\it Training}: the remainder of the data, around 30 days. \end{itemize} The blood glucose, carbs, and insulin values are all scaled to be between $[0, 1]$ by using maximum and minimum values computed over training data. When computing the performance metrics at test time, the predicted values are scaled back to the original range. The neural architecture is trained to minimize the mean squared error between the actual event (meal or bolus) value recorded in the training data and the estimated value computed by the output node of the fully connected layers in the LSTM models, or by the accumulated forecasts in the N-BEATS architecture. The Adam \cite{kingma:adam} variant of gradient descent is used for training, with the learning rate and mini-batch size being tuned on the validation data. In an effort to avoid overfitting, dropout and early stopping with a patience of 10 epochs are used in all experiments. Before training a personalized model for a specific subject, a generic model is first pre-trained on the union of all 12 subjects' training data. The generic model is then fine tuned separately for each individual subject, by continuing training on that subject's training data only. The pre-training allows the model parameters to be in a better starting position before fine tuning, allowing faster and better training. The learning rate and batch size are tuned for each subject on their validation data. For each subject, the results are aggregated over 10 models that are trained with different seedings of the random number generators. The metrics used to evaluate the models are the Root Mean Squared Error (RMSE) and the Mean Absolute Error (MAE). Two scores are reported for each of the LSTM-based and N-BEATS-based recommendation models: \begin{enumerate} \item The {\bf $\langle$model$\rangle$.mean} score calculates the average RMSE and MAE on the testing data across the 10 models trained for each subject, and then averages these scores across all subjects. \item The {\bf $\langle$model$\rangle$.best} score instead selects for each subject the model that performed best in terms of MAE on the validation data, out of the 10 models trained for that subject. The RMSE and MAE test scores are averaged over all subjects. \end{enumerate} Two sets of models were trained for each recommendation scenario: a set of models was trained and evaluated on {\it inertial} examples and a set was trained and evaluated on {\it unrestricted} examples. \subsection{Subject Selection for Testing in Each Recommendation Scenario} While using both the 2018 and 2020 subsets of the OhioT1DM Dataset \cite{ohiot1dm:marling:kdh18, ohiot1dm:marling:kdh20} provides us with data from 12 total subjects, not all 12 can be used in each scenario, due to insufficient examples in their respective development or test subsets. The subjects whose data was used or not at test time are listed below for each scenario, together with a justification: \begin{itemize} \item {\it Carbs$^{(\pm b)}$ Recommendation}: Subjects 567 and 570 were left out at test time. Subject 567 had 0 meal events in the testing portion of their data. Subject 570 frequently used dual boluses; as such, there were very few inertial examples for this subject at all. Of the few inertial examples that were available, 0 were in the testing or validation portions of the data. \item {\it Carbs$^{(-b)}$ Recommendation}: Due to the limited number of examples for this scenario, we trained and evaluated models only for the subjects whose data contained at least 50 carb events with no associated bolus. These are subjects 559, 575, 588, and 591. While subject 596 also had a sufficient number of carb events, we discovered that all carbohydrate inputs for their BW were 0. As a consequence of this missing data, it cannot be determined which boluses were used for BGL correction, and which were used to cover meals. Therefore, subject 596 cannot be used in this scenario. \item {\it Bolus$^{(\pm c)}$ Recommendation}: Subjects 544 and 567 were left out at test time. Subject 544 had few inertial examples overall, and 0 in the validation portion of the data. This is because the vast majority of bolus events in their data was used in conjunction with a meal. Similar to the carbohydrate recommendation scenario, subject 567 was not used in this scenario because of the lack of meal events in their test data. The missing meal data would make the bolus recommendation results for this subject unrealistic and also indistinguishable between the inertial and unrestricted cases. \item {\it Bolus$^{(+c)}$ Recommendation}: Subjects 567, 570, and 596 were left out at test time. As explained for other scenarios above, subject 567 had 0 meals in the test portion of their data. For subject 570, there were 0 inertial examples in the test portion. As explained for the Carbs$^{-b}$ recommendation scenario, due to missing BW data, for subject 596 it cannot be determined which boluses were used for BGL correction, and which were used to cover meals, so their data cannot be used in this scenario, either. \end{itemize} Irrespective of which subjects are used at test time, the data from all 12 patients is used for pre-training purposes in each recommendation scenario. Furthermore, the set of subjects stays consistent between the inertial and unrestricted cases for any given recommendation scenario. \subsection{Evaluating the Impact of Pre-processing of Meals} \label{sec:pre-evaluation} To determine the utility of the pre-processing of meals procedure introduced in Section~\ref{sec:pre-processing}, we trained and evaluated N-BEATS-based models for the carbohydrate recommendation scenario Carbs$^{(\pm b)}$ using the original data vs. using the pre-processed data. When training on pre-processed data, we report in Table~\ref{tab:pre-carbs} two development results: when evaluating on all the pre-processed meals in the development data (pre$^+$) vs. evaluating only on meals that were not added during pre-processing (pre$^-$). The results show that in both cases the pre-processing of meals leads to statistically significant improvements in RMSE and MAE. Pre-processing of meals also benefits the bolus recommendation scenario, as shown in Table~\ref{tab:pre-bolus}. These results can be seen as further evidence of the fact that the meal timestamps recorded in the smartphone interface are unreliable and that meal times should instead be anchored to the bolus timestamps recorded by the BW, as done in the pre-processing procedure. \begin{table}[ht] \setlength{\tabcolsep}{4pt} \caption{Results with pre-processing of meals (pre) vs. original raw data for meal events (raw), for the carbohydrate recommendation scenario Carbs$^{(\pm b)}$ on unrestricted examples. pre$^+$ refers to using all pre-processed meals (shifted original meals and added meals), whereas pre$^-$ does not use meals added by the pre-processing procedure. The symbol $\dagger$ indicates a p-value < 0.03 when using a one-tailed t-test to compare against the results without pre-processing (raw).} \begin{center} \label{tab:pre-carbs} \begin{tabular}{|l|ll|rr|} \cline{2-3} \multicolumn{1}{c|}{} & \multicolumn{2}{c|}{Pre-processing} & \multicolumn{2}{c}{} \\ \cline{2-5} \multicolumn{1}{c|}{} & Train & Devel & RMSE & MAE\\ \hline \multirow{2}{*}{N-BEATS.mean} & raw & raw & 13.42 & 10.32\\ & pre$^+$ & pre$^-$ & $^\dagger$9.38 & $^\dagger$6.59\\ & pre$^+$ & pre$^+$ & $^\dagger${\bf 8.84} & $^\dagger${\bf 6.16}\\ \hline \multirow{2}{*}{N-BEATS.best} & raw & raw & 12.32 & 9.28\\ & pre$^+$ & pre$^-$ & $^\dagger$8.48 & $^\dagger$5.90\\ & pre$^+$ & pre$^+$ & $^\dagger${\bf 8.12} & $^\dagger${\bf 5.53}\\ \hline \end{tabular} \end{center} \end{table} \begin{table}[ht] \setlength{\tabcolsep}{4pt} \caption{Results with pre-processing of meals (pre) vs. original raw data for meal events (raw), for the Bolus$^{(\pm c)}$ recommendation scenario on unrestricted examples. All meals (shifted or added) are used for the pre-processed data. The symbol $\dagger$ indicates a p-value < 0.01 when using a one-tailed t-test to compare against the results without pre-processing (raw).} \begin{center} \label{tab:pre-bolus} \begin{tabular}{|l|c|rr|} \cline{2-4} \multicolumn{1}{c|}{} & Pre-processing & RMSE & MAE\\ \hline \multirow{2}{*}{N-BEATS.mean} & raw & 1.85 & 1.41\\ & pre & $^\dagger${\bf 1.30} & $^\dagger${\bf 0.92}\\ \hline \multirow{2}{*}{N-BEATS.best} & raw & 1.81 & 1.32 \\ & pre & $^\dagger${\bf 1.22} & $^\dagger${\bf 0.84}\\ \hline \end{tabular} \end{center} \end{table} \subsection{Tuning the Architecture and the Hyper-parameters on the Development Data} \label{sec:development} Table~\ref{tab:state1} show the results of the LSTM- and N-BEATS-based models, with vs. without using the final state produced by the LSTM$_1$ component as input to the fully connected network. The results show that using the final state from LSTM$_1$ directly as input leads to a substantial improvement for the carbohydrate recommendation scenario Carbs$^{(\pm b)}$, while maintaining a comparable performance for the bolus recommendation scenario. Consequently, in all remaining experiments the architecture is set to use the final state of LSTM$_1$ as input to the FC layers. \begin{table}[ht] \caption{Performance of the LSTM- and N-BEATS-based models, with ($+$) and without ($-$) the final state $s_1$ of LSTM$_{1}$ as part of the input to the FC Layers.} \begin{center} \label{tab:ablation_lstm1} \begin{tabular}{|c|c|rr|c|c|c|rr|} \cline{3-4} \cline{8-9} \multicolumn{2}{c|}{LSTM.mean} & RMSE & MAE & \multicolumn{1}{c}{} & \multicolumn{2}{c|}{N-BEATS.mean} & RMSE & MAE\\ \cline{1-4} \cline{6-9} \multirow{2}{*}{Carbs$^{(\pm b)}$} & $- s_1$ & 10.14 & 7.56 & & \multirow{2}{*}{Carbs$^{(\pm b)}$} & $- s_1$ & 10.27 & 7.58\\ & $+ s_1$ & {\bf 8.99} & {\bf 6.57} & & & $+ s_1$ & {\bf 8.84} & {\bf 6.16}\\ \cline{1-4} \cline{6-9} \multirow{2}{*}{Bolus$^{(\pm c)}$} & $- s_1$ & {\bf 1.33} & {\bf 0.97} & & \multirow{2}{*}{Bolus$^{(\pm c)}$} & $- s_1$ & 1.33 & {\bf 0.85}\\ & $+ s_1$ & 1.41 & 1.03 & & & $+ s_1$ & {\bf 1.30} & 0.92\\ \cline{1-4} \cline{6-9} \end{tabular} \end{center} \label{tab:state1} \end{table} In the original N-BEATS model of \citet{oreshkin:nbeats}, the backcast and forecast outputs of each block are produced as the result of two separate fully connected layers. In the block architecture shown in Figures~\ref{fig:carbs},~\ref{fig:bolus}, and~\ref{fig:nbeats} however, the {\it FC Layers} component uses just one final fully connected layer to produce both backcast and forecast values. The results in Table~\ref{tab:splitting} show that, overall, using a joint final layer is competitive or better than using separate layers. \begin{table}[ht] \caption{N-BEATS-based model results, with a {\it separate} vs. {\it joint} final fully connected layer for computing backcast and forecast values.} \begin{center} \label{tab:ablation_split} \begin{tabular}{|c|c|c|c|} \cline{3-4} \multicolumn{2}{c|}{N-BEATS.mean} & RMSE & MAE\\ \hline \multirow{2}{*}{Carbs$^{(\pm b)}$} & {\it separate} & {\bf 8.77} & 6.48\\ & {\it joint} & 8.84 & {\bf 6.16}\\ \hline \multirow{2}{*}{Bolus$^{(\pm c)}$} & {\it separate} & 1.32 & 0.94\\ & {\it joint} & {\bf 1.30} & {\bf 0.92}\\ \hline \end{tabular} \end{center} \label{tab:splitting} \end{table} For each prediction scenario, the hyper-parameters for both the LSTM-based and N-BEATS-based models were tuned on development data. The inertial and unrestricted models are tuned independent of each other. The learning rate was tuned by monitoring the learning curves, using values between 0.0002 \cite{rubin_falcone:nbeats_bgl} and 0.1. After multiple experiments, a fixed learning rate of 0.001 was observed to give the best results on development data in all scenarios. The number of blocks in N-BEATS, the number of FC layers in the LSTM, and the dropout rate were then tuned in that order. The number of N-BEATS blocks was selected from \{1, ..., 10\}, the number of layers was selected from \{1, 2, 3, 4, 5\}, whereas the dropout rate was tuned with values from \{0, 0.1, 0.2, 0.3, 0.4 0.5\}. The tuned values are shown in Table~\ref{tab:hyper-lstm} for the LSTM models and Table~\ref{tab:hyper-nbeats} for the N-BEATS models. Overall, the LSTM-based models worked best with only 2 or 3 fully connected layers in all scenarios, whereas the N-BEATS-based models worked best with 4 or 5 fully connected layers. The tuned number of blocks in the N-BEATS-based models varied between 3 and 5, depending on the scenario and the unrestricted vs. inertial case. The tuned dropout rates varied a lot between scenarios for the LSTM-based models, with rates ranging from 0 to 0.5, whereas the tuned rates for N-BEATS-based models varied between 0.2 and 0.5. \begin{table}[ht] \caption{Tuned hyper-parameters for the LSTM-based models.} \label{tab:hyper-lstm} \begin{center} \begin{tabular}{|c|c|c|c|} \cline{3-4} \multicolumn{2}{l}{} & \multicolumn{2}{|c|}{Hyper-Parameters}\\ \hline Scenario & Examples & FC Layers & Dropout\\ \hline \multirow{2}{*}{Carbs$^{(\pm b)}$} & Inertial & 3 & 0.1\\ & Unrestricted & 3 & 0.1\\ \hline \multirow{2}{*}{Bolus$^{(\pm c)}$} & Inertial & 3 & 0.0\\ & Unrestricted & 2 & 0.3\\ \hline \multirow{2}{*}{Bolus$^{(+c)}$} & Inertial & 2 & 0.2\\ & Unrestricted & 2 & 0.5\\ \hline \end{tabular} \end{center} \end{table} \begin{table}[ht] \caption{Tuned hyper-parameters for the N-BEATS-based models.} \label{tab:hyper-nbeats} \begin{center} \begin{tabular}{|c|c|c|c|c|} \cline{3-5} \multicolumn{2}{l}{} & \multicolumn{3}{|c|}{Hyper-Parameters}\\ \hline Scenario & Examples & Blocks & FC Layers & Dropout\\ \hline \multirow{2}{*}{Carbs$^{(\pm b)}$} & Inertial & 5 & 2 & 0.3\\ & Unrestricted & 3 & 3 & 0.3\\ \hline \multirow{2}{*}{Bolus$^{(\pm c)}$} & Inertial & 5 & 4 & 0.2\\ & Unrestricted & 4 & 4 & 0.2\\ \hline \multirow{2}{*}{Bolus$^{(+c)}$} & Inertial & 5 & 4 & 0.5\\ & Unrestricted & 3 & 5 & 0.2\\ \hline \end{tabular} \end{center} \end{table} The size of the LSTM state was tuned to 32, whereas the size of each fully connected layer was tuned to 64, which is substantially smaller than the hidden size of 512 used in the original N-BEATS model \cite{oreshkin:nbeats}. For the carbohydrates without bolus scenario Carbs$^{(-b)}$, due to the much smaller number of examples, we reduced the number of units in the LSTM networks and fully connected layers by a factor of 2. The same hyper-parameters that were tuned on the general carbohydrate recommendation scenario Carbs$^{(\pm b)}$ were used for Carbs$^{(-b)}$. \section{Experimental Results} \label{sec:results} \begin{table*}[t]\setlength{\tabcolsep}{4pt} \caption{Results for each recommendation scenario, for both classes of examples. The simple $\dagger$ indicates a p-value < 0.05 when using a one-tailed t-test to compare against the baseline results; the double $\ddagger$ indicates statistical significance for comparison against the baselines as well as against the competing neural method; the $\uparrow$ indicates significant with respect to the Global Average baseline only.} \begin{center} \label{tab:results} \begin{tabular}{|l|rr|rr|} \cline{2-5} \multicolumn{1}{c}{} & \multicolumn{2}{|c|}{Inertial} & \multicolumn{2}{c|}{Unrestricted}\\ \hline Carbs$^{(\pm b)}$ recommendation & RMSE & MAE & RMSE & MAE\\ \hline Global Average & 20.90 & 17.30 & 20.68 & 17.10\\ ToD Average & 20.01 & 15.78 & 19.82 & 15.68\\ \hline LSTM.mean & 11.55 & 7.81 & 10.99 & 7.40\\ LSTM.best & 10.95 & 7.50 & 10.50 & 7.31\\ \hline N-BEATS.mean & $^\ddagger${\bf 9.79} & $^\ddagger${\bf 6.45} & 10.34 & 7.04\\ N-BEATS.best & 9.92 & 6.56 & $^\dagger${\bf 10.07} & $^\dagger${\bf 6.75}\\ \hline \multicolumn{5}{c}{}\\[-1.5ex] \cline{2-5} \multicolumn{1}{c}{} & \multicolumn{2}{|c|}{Inertial} & \multicolumn{2}{c|}{Unrestricted}\\ \hline Carbs$^{(-b)}$ recommendation & RMSE & MAE & RMSE & MAE\\ \hline Global Average & 15.92 & 13.71 & 14.66 & 12.19\\ ToD Average & 15.55 & 13.45 & 14.27 & 11.93\\ \hline LSTM.mean & 14.02 & 11.47 & 14.70 & 12.27\\ LSTM.best & 13.75 & 10.92 & 14.94 & 12.57\\ \hline N-BEATS.mean & {\bf 13.76} & {\bf 11.42} & $^\uparrow${\bf 13.69} & $^\uparrow${\bf 11.09}\\ N-BEATS.best & 14.52 & 11.78 & 14.17 & 11.47\\ \hline \multicolumn{5}{c}{}\\[-1.5ex] \cline{2-5} \multicolumn{1}{c}{} & \multicolumn{2}{|c|}{Inertial} & \multicolumn{2}{c|}{Unrestricted}\\ \hline Bolus$^{(\pm c)}$ recommendation & RMSE & MAE & RMSE & MAE\\ \hline Global Average & 2.40 & 2.13 & 2.84 & 2.30\\ ToD Average & 2.21 & 1.86 & 2.71 & 2.17\\ \hline LSTM.mean & 1.75 & 1.35 & 1.53 & 1.10\\ LSTM.best & 1.70 & 1.30 & 1.50 & 1.05\\ \hline N-BEATS.mean & $^\dagger${\bf 1.56} & $^\ddagger${\bf 1.20} & $^\dagger${\bf 1.49} & 1.04\\ N-BEATS.best & 1.65 & 1.26 & 1.51 & $^\dagger${\bf 1.03}\\ \hline \multicolumn{5}{c}{}\\[-1.5ex] \cline{2-5} \multicolumn{1}{c}{} & \multicolumn{2}{|c|}{Inertial} & \multicolumn{2}{c|}{Unrestricted}\\ \hline Bolus$^{(+c)}$ recommendation & RMSE & MAE & RMSE & MAE\\ \hline Global Average & 3.00 & 2.35 & 3.04 & 2.39\\ ToD Average & 2.87 & 2.21 & 2.90 & 2.25\\ \hline LSTM.mean & 1.02 & 0.73 & {\bf 1.00} & 0.73\\ LSTM.best & 0.94 & 0.67 & $^\dagger${\bf 1.00} & $^\dagger${\bf 0.72}\\ \hline N-BEATS.mean & 0.89 & 0.65 & 1.11 & 0.82\\ N-BEATS.best & $^\dagger${\bf 0.85} & $^\dagger${\bf 0.61} & 1.06 & 0.78\\ \hline \end{tabular} \end{center} \end{table*} Table~\ref{tab:results} shows the results for the two baselines and the two neural architectures: the LSTM-based (Figures~\ref{fig:carbs} and ~\ref{fig:bolus}) and the N-BEATS-based (Figure~\ref{fig:nbeats}). Across all scenarios and for both example classes, the neural models outperform both baselines, often by a wide margin. Furthermore, the N-BEATS-based models outperform their LSTM-based counterparts across all evaluations with inertial examples, which are the ones with the most practical utility. In general, there is little difference between the best model scores and the average model scores, which means that the model performance is relatively stable with respect to the random initialization of the network parameters. For the prediction of carbohydrates without an associated bolus scenario Carbs$^{(-b)}$, the improvement brought by the two neural models over the two baselines was less substantial, which is to be expected for two reasons. First, the baselines do much better in this scenario than in the more general carbohydrate recommendation scenario Carbs$^{(\pm b)}$ because most of the carb intakes are relatively small, e.g. hypo correction events where subjects are advised to eat a fixed amount of carbohydrate. Second, and most importantly, the number of training carbohydrate events and their associated examples in the Carbs$^{(-b)}$ scenario is much smaller than in the Carbs$^{(\pm b)}$ scenario (Table~\ref{tab:meals}), which makes ML models much less effective. In all experiments reported so far, one model was trained for all prediction horizons, using the value of $\tau \in \{30, 35, ..., 90\}$ as an additional input feature. This global model was then tested on examples from all prediction horizons. To determine if transfer learning happens among different prediction horizons, for each value of $\tau \in \{30, 45, 60, 75, 90\}$ at test time, we compare the performance of the globally trained model vs. the performance of a model trained only on examples for that particular prediction horizon, using inertial examples for both. We chose the inertial case for this experiment because it corresponds better to the intended use of a carbohydrate or bolus recommendation system. Furthermore, we experiment only with the N-BEATS-based model because of its better performance in the inertial case. The results in Table \ref{tab:transfer_time} show transfer learning clearly happening for the carbohydrate recommendation Carbs$^{(\pm b)}$ and bolus given carbs recommendation Bolus$^{(+c)}$ scenarios, where the models trained on all prediction horizons outperform those trained only on a specific prediction horizon when evaluated on that prediction horizon. For the bolus recommendation scenario Bolus$^{(-c)}$ (i.e. Bolus$^{(\pm c)}$ inertial) the results were mixed, with transfer learning being clear only for the short $\tau = 30$ time horizon. Transfer learning results for the Carbs$^{(-b)}$ scenario are not calculated due to the lack of a sufficient number of training examples for each prediction horizon. \begin{table}[ht] \setlength{\tabcolsep}{1.75pt} \caption{Comparison between models trained on all prediction horizons vs. one prediction horizon $\tau$, when evaluated on the prediction horizon $\tau$. The symbol $\dagger$ indicates a p-value < 0.05 when using a one-tailed t-test to compare against the one prediction horizon results.} \begin{center} \label{tab:transfer_time} \begin{tabular}{|c|c|rr|rr|rr|rr|rr|rr|rr} \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{12}{c|}{Carbs$^{(\pm b)}$ recommendation}\\ \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{2}{c|}{$\tau=30$} & \multicolumn{2}{c|}{$\tau=45$} & \multicolumn{2}{c|}{$\tau=60$} & \multicolumn{2}{c|}{$\tau=75$} & \multicolumn{2}{c|}{$\tau=90$} & \multicolumn{2}{c|}{Average}\\ \cline{2-14} \multicolumn{1}{c|}{}& Trained on & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} \\ \hline \multirow{2}{*}{N-BEATS.mean} & One $\tau$ & {\bf 9.74} & 6.72 & 10.24 & 6.89 & 10.06 & 6.85 & 10.52 & 7.19 & 9.82 & 6.73 & 10.08 & 6.88\\ & All $\tau$ & 9.96 & {\bf 6.57} & {\bf 9.98} & {\bf 6.56} & {\bf 9.84} & {\bf 6.50} & $^\dagger${\bf 9.55} & $^\dagger${\bf 6.30}& {\bf 9.37} & {\bf 6.22} & {\bf 9.74} & {\bf 6.43}\\ \hline \multirow{2}{*}{N-BEATS.best} & One $\tau$ & 9.92 & 6.70 & 10.39 & 6.90 & 10.21 & 6.88 & 10.62 & 7.18 & 9.92 & 6.66 & 10.21 & 6.86\\ & All $\tau$ & {\bf 9.84} & {\bf 6.50} & {\bf 9.94} & {\bf 6.56} & {\bf 10.02} & {\bf 6.57} & {\bf 9.76} & $^\dagger${\bf 6.34} & {\bf 9.43} & {\bf 6.08} & {\bf 9.80} & {\bf 6.41}\\ \hline \multicolumn{14}{c}{}\\[-1.5ex] \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{12}{c|}{Bolus$^{(-c)}$ recommendation}\\ \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{2}{c|}{$\tau=30$} & \multicolumn{2}{c|}{$\tau=45$} & \multicolumn{2}{c|}{$\tau=60$} & \multicolumn{2}{c|}{$\tau=75$} & \multicolumn{2}{c|}{$\tau=90$} & \multicolumn{2}{c|}{Average}\\ \cline{2-14} \multicolumn{1}{c|}{}& Trained on & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} \\ \hline \multirow{2}{*}{N-BEATS.mean} & One $\tau$ & 1.82 & 1.42 & {\bf 1.57} & {\bf 1.24} & 1.51 & 1.24 & {\bf 1.37} & {\bf 1.10} & 1.40 & 1.17 & 1.53 & 1.23\\ & All $\tau$ & {\bf 1.75} & {\bf 1.33} & 1.61 & {\bf 1.24} & {\bf 1.47} & $^\dagger${\bf 1.17} & 1.38 & {\bf 1.10} & {\bf 1.28} & $^\dagger${\bf 1.03} & {\bf 1.50} & $^\dagger${\bf 1.17}\\ \hline \multirow{2}{*}{N-BEATS.best} & One $\tau$ & 1.77 & 1.37 & {\bf 1.54} & {\bf 1.21} & {\bf 1.51} & {\bf 1.23} & {\bf 1.38} & {\bf 1.10} & {\bf 1.34} & {\bf 1.11} & {\bf 1.51} & {\bf 1.20}\\ & All $\tau$ & {\bf 1.72} & {\bf 1.28} & 1.75 & 1.33 & 1.58 & {\bf 1.23} & 1.45 & 1.12 & 1.44 & 1.13 & 1.59 & 1.22\\ \hline \multicolumn{14}{c}{}\\[-1.5ex] \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{12}{c|}{Bolus$^{(+c)}$ recommendation}\\ \cline{3-14} \multicolumn{2}{c|}{} & \multicolumn{2}{c|}{$\tau=30$} & \multicolumn{2}{c|}{$\tau=45$} & \multicolumn{2}{c|}{$\tau=60$} & \multicolumn{2}{c|}{$\tau=75$} & \multicolumn{2}{c|}{$\tau=90$} & \multicolumn{2}{c|}{Average}\\ \cline{2-14} \multicolumn{1}{c|}{}& Trained on & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} & \multicolumn{2}{c|}{\scriptsize RMSE MAE} \\ \hline \multirow{2}{*}{N-BEATS.mean} & One $\tau$ & 0.98 & 0.73 & 0.91 & 0.69 & 0.91 & 0.69 & 0.95 & 0.74 & 0.93 & 0.72 & 0.94 & 0.71\\ & All $\tau$ & {\bf 0.95} & {\bf 0.68} & {\bf 0.87} & {\bf 0.65} & {\bf 0.86} & {\bf 0.65} & $^\dagger${\bf 0.87} & $^\dagger${\bf 0.65} & $^\dagger${\bf 0.86} & $^\dagger${\bf 0.64} & $^\dagger${\bf 0.88} & $^\dagger${\bf 0.65}\\ \hline \multirow{2}{*}{N-BEATS.best} & One $\tau$ & {\bf 0.94} & 0.69 & 0.91 & 0.69 & 0.92 & 0.68 & 0.93 & 0.71 & 0.91 & 0.70 & 0.92 & 0.69\\ & All $\tau$ & {\bf 0.94} & {\bf 0.66} & {\bf 0.84} & $^\dagger${\bf 0.62} & $^\dagger${\bf 0.82} & $^\dagger${\bf 0.59} & $^\dagger${\bf 0.82} & $^\dagger${\bf 0.61} & $^\dagger${\bf 0.83} & $^\dagger${\bf 0.61} & $^\dagger${\bf 0.85} & $^\dagger${\bf 0.62}\\ \hline \end{tabular} \end{center} \end{table} \section{Conclusion and Future Directions} \label{sec:conclusion} We have introduced a general LSTM-based neural architecture, composed of two chained LSTMs and a fully connected network, with the purpose of training models for making recommendations with respect to any type of quantitative events that may impact blood glucose levels, in particular, carbohydrate amounts and bolus insulin dosages. A deep residual N-BEATS-based architecture was also developed, using the chained LSTMs as a component in its block structure. Experimental evaluations show that the proposed neural architectures substantially outperform a global average baseline as well as a time of day dependent baseline, with the N-BEATS-based models outperforming the LSTM-based counterparts in all evaluations with inertial examples. The trained models are shown to benefit from transfer learning and from a pre-processing of meal events that anchors their timestamps shortly after their corresponding boluses. Overall, these results suggest that the proposed recommendation approaches hold significant promise for easing the complexity of self-managing blood glucose levels in type 1 diabetes. Potential future research directions include investigating the proposed pre-processing of carbohydrate events for blood glucose level prediction and exploring the utility of the two neural architectures for recommending exercise. \authorcontributions{Jeremy Beauchamp contributed with respect to conceptualization, investigation, methodology, software, validation, writing - original draft, and writing - review \& editing. Razvan Bunescu contributed with respect to conceptualization, formal analysis, funding acquisition, methodology, project administration, resources, software, supervision, validation, visualization, writing - original draft, and writing - review \& editing. Cindy Marling contributed with respect to conceptualization, data curation, investigation, funding acquisition, and writing - review \& editing. Zhongen Li contributed with respect to methodology, software, and validation. Chang Liu contributed with respect to resources and supervision.} \funding{This research was funded by grant 1R21EB022356 from the National Institutes of Health (NIH).} \acknowledgments{Conversations with Josep Vehi helped shape the research directions presented herein. The contributions of physician collaborators Frank Schwartz, MD, and Amber Healy, DO, are gratefully acknowledged. We would also like to thank the anonymous people with type 1 diabetes who provided their blood glucose, insulin, and meal data.} \conflictsofinterest{The authors declare no conflict of interest. The funders had no role in the design of the study, in the collection, analyses, or interpretation of data, in the writing of the manuscript, or in the decision to publish the results.} \externalbibliography{yes}
{'timestamp': '2021-03-12T02:25:32', 'yymm': '2103', 'arxiv_id': '2103.06708', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06708'}
arxiv
\section{Introduction} The past ten years have witnessed a rapid development of markerless human motion capture~\cite{Davison2001,hasler2009markerless,StollHGST2011, wang2017outdoor}, which benefits various applications such as immersive VR/AR experience, sports analysis and interactive entertainment. \begin{figure}[tbp] \centering \includegraphics[width=0.9\linewidth]{figures/fig_1_teaser.pdf} \caption{Our ChallenCap approach achieves robust 3D capture of challenging human motions from a single RGB video, with the aid of multi-modal references.} \label{fig:fig_1_teaser} \vspace{-8pt} \end{figure} Multi-view solutions~\cite{StollHGST2011,liu2013markerless,joo2015panoptic,collet2015high,TotalCapture, suo2021neuralhumanfvv} achieve high-fidelity results but rely on expensive studio setup which are difficult to be deployed for daily usage. Recent learning-based techniques enables robust human attribute prediction from monocular RGB video~\cite{hmrKanazawa17,VIBE_CVPR2020,TEX2SHAPE_2019ICCV,DeepHuman_2019ICCV,PIFuHD}. The state-of-the-art monocular human motion capture approaches~\cite{LiveCap2019tog,MonoPerfCap,EventCap_CVPR2020} leverage learnable pose detections~\cite{OpenPose,Mehta2017} and template fitting to achieve space-time coherent results. However, these approaches fail to capture the specific challenging motions such as yoga or rolling on the floor, which suffer from extreme poses, complex motion patterns and severe self-occlusion under the monocular setting. Capturing such challenging human motions is essential for many applications such as training and evaluation for gymnastics, sports and dancing. Currently, optical marker-based solutions like Vicon~\cite{VICON} are widely adopted to capture such challenging professional motions. However, directly utilizing such marker-based reference into markerless capture is inapplicable since the actor needs to re-perform the challenging motion which is temporally unsynchronized to the maker-based capture. Some data-driven human pose estimation approaches~\cite{HMR18,VIBE_CVPR2020} utilize the unpaired reference in an adversarial manner, but they only extract general motion prior from existing motion capture datasets~\cite{Ionescu14a,AMASS_ICCV2019}, which fails to recover the characteristics of specific challenging motion. The recent work~\cite{DeepCap_CVPR2020} inspires to utilize the markerless multi-view reference in a data-driven manner to provide more robust 3D prior for monocular capture. However, this method is weakly supervised on the input images instead of the motion itself, leading to dedicated per-performer training. Moreover, researchers pay less attention to combine various references from both marker-based systems and sparse multi-view systems for monocular challenging motion capture. In this paper, we tackle the above challenges and present \textit{ChallenCap} -- a template-based monocular 3D capture approach for challenging human motions from a single RGB video, which outperforms existing state-of-the-art approaches significantly (See Fig.~\ref{fig:fig_1_teaser} for an overview). Our novel pipeline proves the effectiveness of embracing multi-modal references from both temporally unsynchronized marker-based system and light-weight markerless multi-view system in a data-driven manner, which enables robust human motion capture under challenging scenarios with extreme poses and complex motion patterns, whilst still maintaining a monocular setup. More specifically, we introduce a novel learning-and-optimization framework, which consists of a hybrid motion inference stage and a robust motion optimization stage. Our hybrid motion inference utilizes both the marker-based reference which encodes the accurate spatial motion characteristics but sacrifices the temporal consistency, as well as the sparse multi-view image reference which provides pair-wise 3D motion priors but fails to capture extreme poses. To this end, we first obtain the initial noisy skeletal motion map from the input monocular video. Then, a novel generation network, HybridNet, is proposed to boost the initial motion map, which utilizes a temporal encoder-decoder to extract local and global motion details from the sparse-view reference, as well as a motion discriminator to utilize the unpaired marker-based reference. Besides the data-driven 3D motion characteristics from the previous stage, the input RGB video also encodes reliable motion hints for those non-extreme poses, especially for the non-occluded regions. Thus, a robust motion optimization is further proposed to refine the skeletal motions and improve the tracking accuracy and overlay performance, which jointly utilizes the learned 3D prior from the supervised multi-modal references as well as the reliable 2D and silhouette information from the input image reference. To summarize, our main contributions include: \begin{itemize} \setlength\itemsep{0em} \item We propose a monocular 3D capture approach for challenging human motions, which utilizes multi-modal reference in a novel learning-and-optimization framework, achieving significant superiority to state-of-the-arts. \item We propose a novel hybrid motion inference module to learn the challenging motion characteristics from the supervised references modalities, as well as a robust motion optimization module for accurate tracking. \item We introduce and make available a new challenging human motion dataset with both unsynchronized marker-based and light-weight multi-image references, covering 60 kinds of challenging motions and 20 performers with 120k corresponding images. \end{itemize} \section{Overview} Our goal is to capture challenging 3D human motions from a single RGB video, which suffers from extreme poses, complex motion patterns and severe self-occlusion. Fig.~\ref{fig:overview} provides an overview of ChallenCap, which relies on a template mesh of the actor and makes full usage of multi-modal references in a learning-and-optimization framework. Our method consists of a hybrid motion inference module to learn the challenging motion characteristics from the supervised references modalities, and a robust motion optimization module to further extract the reliable motion hints in the input images for more accurate tracking. \myparagraph{Template and Motion Representation.} We use a 3D body scanner to generate the template mesh of the actor and rig it by fitting the Skinned Multi-Person Linear Model (SMPL)\cite{SMPL2015} to the template mesh and transferring the SMPL skinning weights to our scanned mesh. The kinematic skeleton is parameterized as $\textbf{S}=[\boldsymbol{\theta}, \textbf{R},\textbf{t}]$, including the joint angles $\boldsymbol{\theta} \in \mathbb{R}^{30}$ of the $N_J$ joints, the global rotation $ \textbf{R}\in\mathbb{R}^3$ and translation $\textbf{t} \in \mathbb{R}^{3}$ of the root. Furthermore, let $\textbf{Q}$ denotes the quaternions representation of the skeleton. Thus, we can formulate $\textbf{S}=\mathcal{M}(\textbf{Q},\textbf{t})$ where $\mathcal{M}$ denotes the motion transformation between various representations. \myparagraph{Hybrid Motion Inference.} Our novel motion inference scheme extracts the challenging motion characteristics from the supervised marker-based and sparse multi-view references in a data-driven manner. We first obtain the initial noisy skeletal motion map from the monocular video. Then, a novel generation network, HybridNet, is adopted to boost the initial motion map, which consists of a temporal encoder-decoder to extract local and global motion details from the sparse-view references, as well as a motion discriminator to utilize the motion characteristics from the unpaired marker-based references. To train our HybridNet, a new dataset with rich references modalities and various challenging motions is introduced (Sec. \ref{sec:mot_inference}). \myparagraph{Robust Motion Optimization.} Besides the data-driven 3D motion characteristics from the previous stage, the input RGB video also encodes reliable motion hints for those non-extreme poses, especially for the non-occluded regions. Thus, a robust motion optimization is introduced to refine the skeletal motions so as to increase the tracking accuracy and overlay performance, which jointly utilizes the learned 3D prior from the supervised multi-modal references as well as the reliable 2D and silhouette information from the input image references (Sec. \ref{sec:mot_optimization}). \section{Discussion} \myparagraph{Limitation.} As the first trial to explore challenging human motion capture with multi-modal references, the proposed ChallenCap still owns limitations as follows. First, our method relies on a pre-scanned template and cannot handle topological changes like clothes removal. Our method is also restricted to human reconstruction, without modeling human-object interactions. It's interesting to model the human-object scenarios in a physically plausible way to capture more challenging and complicated motions. Besides, our current pipeline turns to utilize the references in a two-stage manner. It’s a promising direction to formulate the challenging motion capture problem in an end-to-end learning-based framework. \myparagraph{Conclusion.} We present a robust template-based approach to capture challenging 3D human motions using only a single RGB camera, which is in a novel two-stage learning-and-optimization framework to make full usage of multi-modal references. Our hybrid motion inference learns the challenging motion details from various supervised references modalities, while our robust motion optimization further improves the tracking accuracy by extracting the reliable motion hints in the input image reference. Our experimental results demonstrate the effectiveness and robustness of ChallenCap in capturing challenging human motions in various scenarios. We believe that it is a significant step to enable robust 3D capture of challenging human motions, with many potential applications in VR/AR, and performance evaluation for gymnastics, sports, and dancing. \subsection{Robust Motion Optimization} \label{sec:mot_optimization} Besides the data-driven 3D motion characteristics from the previous stage, the input RGB video also encodes reliable motion hints for those non-extreme poses, especially for the non-occluded regions. We thus introduce this robust motion optimization to refine the skeletal motions so as to increase the tracking accuracy and overlay performance, which jointly utilizes the learned 3D prior from the supervised multi-modal references as well as the reliable 2D and silhouette information from the input image references. The optimization to refine the skeletal pose is formulated as: \begin{align} \label{eq:opt} \boldsymbol{E}_{\mathrm{total}}(\textbf{S}_t) = \boldsymbol{E}_{\mathrm{3D}} + \lambda_{\mathrm{2D}}\boldsymbol{E}_{\mathrm{2D}} + \lambda_{\mathrm{T}}\boldsymbol{E}_{\mathrm{T}} + \lambda_{\mathrm{S}}\boldsymbol{E}_{\mathrm{S}}. \end{align} Here, $\boldsymbol{E}_{\mathrm{3D}}$ makes the final motion sequence close to the output of network on occluded and invisible joints while $\boldsymbol{E}_{\mathrm{2D}}$ adds a re-projection constraint on high-confidence 2D keypoints detected. $\boldsymbol{E}_{\mathrm{T}}$ enforces the final motion to be temporally smooth, while the $\boldsymbol{E}_{\mathrm{S}}$ enforces alignment of the projected 3D model boundary with the detected silhouette. Specifically, the 3D term $\boldsymbol{E}_{\mathrm{3D}}$ is as following: \begin{align} \boldsymbol{E}_{\mathrm{3D}} = \sum^T_{t=1}\|\textbf{S}_t - \mathcal{M}(\hat{\textbf{Q}}_t,\textbf{t}_t) \|^2_2, \end{align} where $\hat{\textbf{Q}}_t$ is the regressed quaternions motion from our previous stage; $\mathcal{M}$ is the mapping from quaternions to skeletal poses; $\textbf{t}_t$ is the global translation of $\textbf{S}_t$. Note that the joint angles $\boldsymbol{\theta}_t$ of $\textbf{S}_t$ locate in the pre-defined range $[\boldsymbol{\theta}_{min}, \boldsymbol{\theta}_{max}]$ of physically plausible joint angles to prevent unnatural poses. We then propose the projected 2D term as: \begin{align} \boldsymbol{E}_{\mathrm{2D}} = \frac{1}{T}\sum^T_{t=1}\frac{1}{|C_t|}\sum_{i\in C_t }\|\Pi(J_i(\textbf{S}_t))-\mathbf{p}_{t}^{(i)}\|^2_2, \end{align} where $C_t = \{ i \ |\ c_t^{(i)} \geq thred \}$ is the set of indexes of high-confidence keypoints on the image $I_t$; $ c_t^{(i)}$ is the confidence value of the $i^{th}$ keypoint $\mathbf{p}_{t}^{(i)}$; $thred$ is 0.8 in our implementation. The projection function $\Pi$ maps 3D joint positions to 2D coordinates while $J_i$ computes the 3D position of the $i^{th}$ joint. Then, the temporal term $\boldsymbol{E}_{\mathrm{T}}$ is formulated as: \begin{align} \boldsymbol{E}_{\mathrm{T}} = \sum^{T-1}_{t=1}\|\mathcal{M}(\hat{\textbf{Q}}_t,\textbf{t}_t) - \mathcal{M}(\hat{\textbf{Q}}_{t+1},\textbf{t}_{t+1})\|^2_2, \end{align} where $\hat{\textbf{Q}}_t$ and $\hat{\textbf{Q}}_{t+1}$ are two adjacent regressed quaternions motion from our hybrid motion inference module. We utilize temporal smoothing to enable globally consistent capture in 3D space. Moreover, we follow \cite{MonoPerfCap} to formulate the silhouette term $\boldsymbol{E}_{\mathrm{S}}$ and please refer to \cite{MonoPerfCap} for more detail. The constrained optimization problem to minimize the Eqn.~\ref{eq:opt} is solved using the Levenberg-Marquardt (LM) algorithm of \textit{ceres}~\cite{ceresSolver}. In all experiments, we use the following empirically determined parameters: $\lambda_{\mathrm{2D}} = 1.0$, $\lambda_{\mathrm{T}} = 20.0$ and $\lambda_{\mathrm{S}} = 0.3$. Note that the initial $\textbf{t}_t$ for the mapping from quaternions to skeletal poses is obtained through the pre-processing stage in Sec.~\ref{sec:mot_inference}. To enable more robust optimization, we first optimize the global translation $\textbf{t}_t$ for all the frames and then optimize the $\textbf{S}_t$. Such a flip-flop optimization strategy improves the overlay performance and tracking accuracy, which jointly utilizes the 3D challenging motion characteristics from the supervised multi-modal references as well as the reliable 2D and silhouette information from the input image references. \section{Experimental Results} \label{ExperimentalResults} In this section, we introduce our new dataset and evaluate our ChallenCap in a variety of challenging scenarios. \begin{figure}[htb] \centering \includegraphics[width=\linewidth]{figures/dataset} \caption{Illustration of our capturing system and examples of our dataset. The left shows our capturing system, including four RGB cameras (blue) for sparse-view image sequences and Vicon cameras (red) for marker-based motion capture (partially annotated). The right shows the animated meshes from the rigged character-wise template models with various challenging motions.} \label{fig:dataset} \end{figure} \myparagraph{ChallenCap Dataset.} There are existing datasets for 3D pose estimation and human performance capture, such as the Human3.6M\cite{ionescu2013human3} dataset that contains 3D human poses in daily activities, but it lacks challenging motions and template human meshes. The AMASS \cite{AMASS_ICCV2019} dataset provides a variety of human motions using marker-based approach, but the corresponding RGB videos are not provided. To evaluate our method, we propose a new challenging human motion dataset containing 20 different characters with a wide range of challenging motions such as dancing, boxing, gymnastic, exercise, basketball, yoga, rolling, leap, etc(see Fig.\ref{fig:dataset}). We adopt a 12-view marker-based Vicon motion capture system to capture challenging human motions. Each challenging motion consists of data from two modalities: synchronized sparse-view RGB video sequences and marker-based reference motion captured in an unsynchronized manner. \begin{figure}[t] \centering \includegraphics[width=0.95\linewidth]{figures/comp_methods.pdf} \caption{Qualitative comparison. Our results overlay better with the input video frames than the results of other methods. } \label{fig:comp_methods} \end{figure} \begin{table}[t] \begin{center} \centering \caption{Quantitative comparision of several methods in terms of tracking accuracy and template mesh overlay.} \label{tab:Comparison} \resizebox{0.48\textwidth}{!}{ \begin{tabular}{l|cccc} \hline Method & MPJPE ($mm$)$\downarrow$ & PCK0.5($\%$)$\uparrow$ & PCK0.3$\uparrow$ & mIoU($\%$)$\uparrow$ \\ \hline HMR~\cite{HMR18} & 154.3 & 77.2 & 68.9 & 57.0 \\ VIBE~\cite{VIBE_CVPR2020} & 116.7 & 83.7 & 71.8 & 73.7 \\ MonoPerfCap~\cite{MonoPerfCap} & 134.7 & 77.4 & 65.6 & 65.5 \\ Ours & \textbf{ 52.6} & \textbf{96.6} & \textbf{87.4} & \textbf{83.6} \\ \hline \end{tabular} } \end{center} \end{table} \subsection{Comparison} Our method enables more accurate motion capture for challenging human motions. For further comparison, we do experiments to demonstrate its effectiveness. We compare the proposed ChallenCap method with several monocular 3D human motion capture methods. Specifically, we apply MonoPerfCap~\cite{MonoPerfCap} which is based on optimization. We also apply HMR~\cite{HMR18} and VIBE~\cite{VIBE_CVPR2020} where the latter also relies on an adversarial learning framework. For fair comparisons, we fine-tune HMR and VIBE with part of manually annotated data from our dataset. As shown in Fig.\ref{fig:comp_methods}, our method outperforms other methods in motion capture quality. Benefiting from multi-modal references, our method performs better on the overall scale and also gets better overlays of the captured body. \begin{figure} \centering \includegraphics[width=0.95\linewidth]{figures/comp_sideview.pdf} \caption{Qualitative comparison with side views. Our method maintains projective consistency in the side views while other methods have misalignment errors. } \label{fig:comp_sideview} \end{figure} As illustrated in Fig.\ref{fig:comp_sideview}, we perform a qualitative comparison with other methods on the main camera view and a corresponding side view. The figure shows that the side view results of other methods wrongly estimated the global position of arms or legs. This is mainly because our HybridNet promotes capture results for challenging human motions in the world frame. \begin{figure}[t] \centering \includegraphics[width=0.95\linewidth]{figures/comp_multiview.pdf} \caption{Qualitative comparison between ChallenCap (green) and MonoPerfCap (yellow) with reference-view verification. As marked in the figure, MonoPerfCap misses limbs in the reference view.} \label{fig:comp_multiview} \end{figure} Fig.\ref{fig:comp_multiview} shows the reference view verification results. We capture challenging motions in the main view and verify the result in a reference view with a rendered mesh. The figure shows that even MonoPerfCap gets almost right 3D capture results in the main camera view, the results in the reference view show the misalignments on the limbs of the human body. Tab.\ref{tab:Comparison} shows the quantitative comparisons between our method and state-of-the-art methods using different evaluation metrics. We report the mean per joint position error (MPJPE), the Percentage of Correct Keypoints (PCK), and the Mean Intersection-Over-Union (mIoU) results. Benefiting from our multi-modal references, our method gets better performance than optimization-based methods and other data-driven methods. \subsection{Evaluation} \label{paper:Evaluation} We apply two ablation experiments. One verifies that it is more effective to apply the robust optimization stage, the other validates that the diligently-designed network structure and loss functions gain for the challenge human motions by comparing with other network structures. \begin{figure}[tb] \centering \includegraphics[width=0.95\linewidth]{figures/opt.pdf} \caption{Evaluation for the optimization stage. The figure shows that our robust optimization stage improves the overlay performance.} \label{fig:fig_abla_optimize} \end{figure} \begin{table}[tb] \begin{center} \centering \caption{Quantitative evaluations on different optimization configurations. } \label{tab:optimization} \begin{tabular}{l|c|ccc} \hline Method & MPJPE$\downarrow$ & PCK0.5$\uparrow$ & PCK0.3 $\uparrow$ \\ \hline MonoPerfCap & 134.7 & 77.4 & 65.6 \\ Ours & 106.5 & 92.8 & 82.2 \\ Ours + optimization & \textbf{52.6} & \textbf{96.6} & \textbf{87.4} \\ \hline \end{tabular} \end{center} \end{table} \myparagraph{Evaluation on optimization.} Tab.\ref{tab:optimization} shows the performance of models with or without the optimization module. The baseline 3D capture method is MonoPerfCap~\cite{MonoPerfCap}. The table demonstrates that whether the robust optimization stage is applied, our method outperforms MonoPerfCap. As illustrated in Fig.\ref{fig:fig_abla_optimize}, the obvious misalignment on the limb is corrected when the robust optimization stage is applied. \myparagraph{Evaluation on network structure.} We experiment with several different network structures and loss design configurations, the results are demonstrated in Tab.\ref{tab:ablation_network}. The table shows that even only using sparse-view loss or adversarial loss, our method performs better than the simple encoder-decoder network structure without the attention pooling design. It also outperforms VIBE. When using both sparse-view loss and adversarial loss, our method gets 4\% to 5\% increase for PCK-0.5 and 12 to 32 decrease for MPJPE, compared with using only sparse-view or adversarial loss. The experiment illustrates multi-modal references contribute a lot to the improvement of results as illustrated in Fig. \ref{fig:loss}. \begin{figure}[tb] \centering \includegraphics[width=0.95\linewidth]{figures/loss_new.pdf} \caption{Evaluation of our network structure. The figure shows the effectiveness of both of our losses. Note that all experiments are applied with the robust optimization stage. Results of the full pipeline overlay more accurately with the input video frames. } \label{fig:loss} \end{figure} \begin{table}[t] \begin{center} \centering \caption{Quantitative evaluation of different network structure configurations. Our full pipeline achieves the lowest error. } \label{tab:ablation_network} \begin{tabular}{l|ccc} \hline Method & MPJPE $\downarrow$ & PCK0.5 $\uparrow$ & PCK0.3 $\uparrow$ \\ \hline Encoder-Decoder & 109.1 & 85.7 & 81.5 \\ VIBE & 94.2 & 90.2 & 82.0 \\ Ours + $\mathcal{L}_{sv}$ & 64.3 & 92.5 & 84.1 \\ Ours + $\mathcal{L}_{adv}$ & 84.6 & 91.2 & 84.1 \\ Ours + $\mathcal{L}_{sv}$ + $\mathcal{L}_{adv}$ & \textbf{52.6} & \textbf{96.6} & \textbf{87.4} \\ \hline \end{tabular} \end{center} \end{table} \section{Approach} \subsection{Hybrid Motion Inference} \label{sec:mot_inference} \myparagraph{Preprocessing.} Given an input monocular image sequence $I_t, t\in[1,T]$ of length $T$ and a well-scanned template model, we first adopt the off-the-shelf template-based motion capture approach~\cite{MonoPerfCap} to obtain the initial skeletal motion $\textbf{S}_t$ and transform it into quaternions format, denoted as $\textbf{Q}^{init}_t$. More specifically, we only adopt the 2D term from \cite{MonoPerfCap} using OpenPose~\cite{OpenPose} to obtain 2D joint detections. Please refer to \cite{MonoPerfCap} for more optimization details. Note that such initial skeletal motions suffer from severe motion ambiguity since no 3D prior is utilized, as illustrated in the pre-processing stage in Fig.~\ref{fig:overview}. After the initial optimization, we concatenate the $\textbf{Q}^{init}_t$ and the detection confidence from OpenPose~\cite{OpenPose} for all the $T$ frames into a motion map $\mathcal{Q}\in\mathbb{R}^{T\times 4N_J}$ as well as a confidence map $\mathcal{C}\in\mathbb{R}^{T\times N_J}$. \myparagraph{HybridNet Training.} Based on the initial noisy motion map $\mathcal{Q}$ and confidence map $\mathcal{C}$, we propose a novel generation network, HybridNet, to boost the initial capture results for challenging human motions. As illustrated in Fig.~\ref{fig:fig_3_network}, our HybridNet learns the challenging motion characteristics by the supervision from multi-modal references. To avoid tedious 3D pose annotation, we utilize the supervision from the optimized motions using sparse multi-view image reference. Even though such sparse-view reference still cannot recover all the extreme poses, it provides rich pair-wise overall 3D motion prior. To further extract the fine challenging motion details, we utilize adversarial supervision from the marker-based reference since it only provides accurate but temporally unsynchronized motion characteristics due to re-performing. To this end, we utilize the well-known Generative Adversarial Network (GAN) structure in our HybridNet with the generative network $\mathcal{G}$ and the discriminator network $\mathcal{D}$. Our generative module consists of a global-local motion encoder with a hierarchical attention pooling block and a GRU-based decoder to extract motion details from the sparse-view references, which takes the concatenated $\mathcal{Q}$ and $\mathcal{C}$ as input. In our encoder, we design two branches to encode the global and local skeletal motion features independently. Note that we mainly use 1D convolution layers during the encoding process to extract corresponding temporal information. We apply three layers of 1D convolution for the global branch while splitting the input motion map into $N_J$ local quaternions for the local branch inspired by \cite{taew}. Differently, we utilize a hierarchy attention pooling layer to connect the feature of adjacent joints and compute the latent codes from five local body regions, including the four limbs and the torso. We concatenate the global and local feature of two branches as the final latent code, and decode them to the original quaternions domain with three linear layers in our GRU-based decoder (see Fig.~\ref{fig:fig_3_network} for detail). Here, the loss of our generator $\mathcal{G}$ is formulated as: \begin{align} \mathcal{L}_{\mathcal{G}} = \mathcal{L}_{sv} + \mathcal{L}_{adv}, \end{align} where $\mathcal{L}_{sv}$ is the sparse-view loss and $\mathcal{L}_{adv}$ is the adversarial loss. Our sparse-view loss is formulated as: \begin{align} & \mathcal{L}_{sv} = \sum_{t=1}^T \left\|\hat{\textbf{Q}}_t - \textbf{Q}^{sv}_t\right\|_2^2 + \lambda_{quat}\sum_{t=1}^T\sum^{N_J}_{i=1}(\|\hat{\textbf{Q}}_t^{(i)}\| - 1)^2. \end{align} Here, the first term is the $L_2$ loss between the regressed output motion $\hat{\textbf{Q}}_t$ and the 3D motion prior $\textbf{Q}^{sv}_t$ from sparse-views reference. Note that we obtain $\textbf{Q}^{sv}_t$ from the reference sparse multi-view images by directly extending the same optimization process to the multi-view setting. The second regular term forces the network output quaternions to represent a rotation. Besides, $N_J$ denotes the number of joints which is 15 in our case while $\lambda_{quat}$ is set to be $1\times 10^{-5}$. Our motion discriminator $\mathcal{D}$ further utilizes the motion characteristics from the unpaired marker-based references, which maps the motion map $\mathcal{\hat{Q}}$ corrected by the generator to a value $\in [0, 1]$ to represent the probability $\mathcal{\hat{Q}}$ is a plausible human challenging motion. Specifically, we follow the video motion capture approach VIBE~\cite{VIBE_CVPR2020} to design two losses, including the adversarial loss $\mathcal{L}_{adv}$ to backpropagate to the generator $\mathcal{G}$ and the discriminator loss $\mathcal{L}_{\mathcal{D}}$ for the discriminator $\mathcal{D}$: \begin{align} &\mathcal{L}_{adv} = \mathbb{E}_{\mathcal{\hat{Q}} \sim p_{\mathcal{G}}}\left[\left(\mathcal{D}(\mathcal{\hat{Q}})-1\right)^{2}\right],\\ &\mathcal{L}_{\mathcal{D}} = \mathbb{E}_{\mathcal{Q}^{mb} \sim p_{V}}\left[\left(\mathcal{D}(\mathcal{Q}^{mb})-1\right)^{2}\right]+\mathbb{E}_{\mathcal{\hat{Q}} \sim p_{\mathcal{G}}}\left[\left(\mathcal{D}(\mathcal{\hat{Q}})\right)^{2}\right]. \end{align} Here, the adversarial loss $\mathcal{L}_{adv}$ is the expectation that $\mathcal{\hat{Q}}$ belongs to a plausible human challenging motion, while $p_{\mathcal{G}}$ and $p_V$ represents the corrected motion sequence the corresponding captured maker-based challenging motion sequence, respectively. Note that $\mathcal{Q}^{mb}$ denotes the accurate but temporally unsynchronized motion map captured by the marker-based system. Compared to VIBE~\cite{VIBE_CVPR2020} which extracts general motion prior, our scheme can recover the characteristics of more specific challenging motion. \myparagraph{Training Details.} We train our HybridNet for 500 epochs with Adam optimizer~\cite{kingma2014adam}, and set the dropout ratio as 0.1 for the GRU layers. We apply Exponential Linear Unit (ELU) activation and batch normalization layer after every our 1D convolutional layer with kernel size 7, except the final output layer before the decoder. During training, four NVidia 2080Ti GPUs are utilized. The batch size is set to be 32, while the learning rate is set to be $1 \times 10^{-3}$ for the generator and $1 \times 10^{-2}$ for the discriminator, the decay rate is 0.1 (final 100 epochs). To train our HybridNet, a new dataset with rich references modalities and various challenging motions and performers is further introduced and more details about our dataset are provided in Sec.~\ref{ExperimentalResults} Our hybrid motion inference utilizes multi-modal references to extract fine motion details for challenging human motions in a data-driven manner. At test time, our method can robustly boost the tracking accuracy of the initial noisy skeletal motions via a novel generation network. Since our learning scheme is not directly supervised on the input images of specific performers, it's not restricted by per-performer training. Instead, our approach focus on extracting the characteristics of challenging motions directly. \begin{figure*} \centering \includegraphics[width=0.95\linewidth]{figures/rs_gallery.pdf} \caption{3D capturing results on challenging human motions. For each body motions, the top row shows the input images, the middle row shows the captured body results on camera view, and the bottom row shows the rendering result of the captured body from side view. } \label{fig:rs_gallery} \end{figure*} \section{Related Work} As an alternative to the widely used marker-based solutions~\cite{VICON,Xsens,Vlasic2007}, markerless motion capture~\cite{BreglM1998,AguiaSTAST2008,TheobASST2010} technologies alleviate the need for body-worn markers and have been widely investigated. In the following, we focus on the field of marker-less 3D human motion capture. \myparagraph{Parametric Model-based Capture.} Many general human parametric models~\cite{SCAPE2005,SMPL2015,SMPLX2019,STAR_ECCV2020} learned from thousands of high-quality 3D scans have been proposed in the last decades, which factorize human deformation into pose and shape components. Deep learning is widely used to obtain skeletal pose and human shape prior through model fitting~\cite{TAM_3DV2017,Lassner17,keepitSMPL,Kolotouros_2019_CVPR} or directly regressing the model parameters from the input~\cite{HMR18,Kanazawa_2019CVPR,VIBE_CVPR2020,zanfir2020neural}. Besides, various approaches~\cite{detailHuman_2019CVPR,DetailDepth_2019ICCV,People3D_2019ICCV,TEX2SHAPE_2019ICCV,DeepHuman_2019ICCV} propose to predict detailed human geometry by utilizing parametric human model as a basic estimation. Beyond human shape and pose, recent approaches further include facial and hand models~\cite{Xiang_2019_CVPR,TotalCapture,SMPLX2019,MonoExpressive_ECCV2020} for expressive reconstruction or leverage garment and clothes modeling on top of parametric human model~\cite{ClothCap,bhatnagar2019mgn,TailorNet_CVPR2020,LearnToDress_CVPR2020}. But these methods are still limited to the parametric model and cannot provide space-time coherent results for loose clothes. Instead, our method is based on person-specific templates and focuses on capturing space-time coherent challenging human motions using multi-modal references. \myparagraph{Free-form Volumetric Capture.} Free-form volumetric capture approaches with real-time performance have been proposed by combining the volumetric fusion \cite{Curless1996} and the nonrigid tracking~\cite{sumner2007embedded,li2009robust,zollhofer2014real,guo2015robust} using depth sensors. The high-end solutions~\cite{dou-siggraph2016,motion2fusion,UnstructureLan,TheRelightables} rely on multi-view studios which are difficult to be deployed. The most handy monocular approaches for general non-rigid scenes~\cite{Newcombe2015,innmann2016volume,guo2017real,KillingFusion2017cvpr,slavcheva2018cvpr,slavcheva2020pami,FlyFusion} can only capture small, controlled, and slow motions. Researchers further utilize parametric model~\cite{BodyFusion,DoubleFusion,UnstructureLan,robustfusion} or extra body-worn sensors~\cite{HybridFusion} into the fusion pipeline to increase the tracking robustness. However, these fusion approaches rely on depth cameras which are not as cheap and ubiquitous as color cameras. Recently, the learning-based techniques enable free-form human reconstruction from monocular RGB input with various representations, such as volume~\cite{DeepHuman_2019ICCV}, silhouette~\cite{SiCloPe_CVPR2019} or implicit representation~\cite{PIFU_2019ICCV,PIFuHD,MonoPort,Chibane_2020CVPR,Implicit_ECCV2020}. However, such data-driven approaches do not recover temporal-coherent reconstruction, especially under the challenging motion setting. In contrast, our template-based approach can explicitly obtain the per-vertex correspondences over time even for challenging motions. \myparagraph{Template-based Capture.} A good compromising settlement between from-form capture and parametric Modal-based Capture is to utilize a specific human template mesh as prior. Early solutions~\cite{Gall2010,StollHGST2011,liu2013markerless,Robertini:2016,Pavlakos17,Simon17,FlyCap} require multi-view capture to produce high quality skeletal and surface motions but synchronizing and calibrating multi-camera systems is still cumbersome. Recent work only relies on a single-view setup~\cite{MonoPerfCap,LiveCap2019tog,EventCap_CVPR2020} achieve space-time coherent capture and even achieves real-time performance~\cite{LiveCap2019tog}. However, these approaches fail to capture the challenging motions such as yoga or rolling on the floor, which suffer from extreme poses and severe self-occlusion under the monocular setting. The recent work~\cite{DeepCap_CVPR2020} utilizes weekly supervision on multi-view images directly so as to improve the 3D tracking accuracy during test time. However, their training strategy leads to dedicated per-performer training. Similarly, our approach also employs a person-specific template mesh. Differently, we adopt a specific learning-and-optimization framework for challenging human motion capture. Our learning module is supervised on the motion itself instead of the input images of specific performers for improving the generation performance to various performers and challenging motions. \begin{figure*}[t] \centering \includegraphics[width=\linewidth]{figures/fig_3_network} \caption{Illustration of our hybrid motion network, HybridNet, which encodes the global and local temporal motion information with the losses on both the generator and the discriminator. Note that the attention pooling operation is performed by applying element-wise addition (blue branches) on the features of the adjacent body joints. The features after attention pooling are concatenated together with the global feature as input to the fully connected layers.} \label{fig:fig_3_network} \end{figure*}
{'timestamp': '2021-03-30T02:49:09', 'yymm': '2103', 'arxiv_id': '2103.06747', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06747'}
arxiv
\subsection{Additional Experiments} Some measures we could consider: \begin{itemize} \item Wasserstein loss (approximated with second discriminator) in-sample and out-of-sample \item Inception score (for image data only?) \item JS distance \item For Gaussians, measure KDE error? \item Success on downstream prediction tasks \end{itemize} It seems like empirical (Wasserstein, JS) loss is often measured with respect to the training data, but I think we should focus on out of sample performance. An interesting result would be if privacy actually helps with generalization. Worth looking further into metrics discussed here: \cite{arora2017generalization}. One point this paper makes is that polynomial samples won't well-approximate the true distribution w.r.t\ JS or Wasserstein distance, and as such they argue that these are poor generalization measures. I somewhat disagree --- I think a more natural benchmark would be to consider e.g.\ Wasserstein distance with respect to a second sample of the same size, permitting more of an apples to apples comparison. If it hasn't been done already, it seems possible to prove generalization bounds for Wasserstein distance when training privately with respect to a second sample of the same size. \wb{Upon closer inspection, their point is a little more subtle --- the class of 1-Lipschitz functions is too large to apply uniform convergence, } Batch normalization? \wb{LFW, IDC (used in \cite{wu2019generalization}) ?} Use ``standard architectures'' for each dataset to start, then evaluate on random architectures as a stretch goal (there's gotta be starter code out there for doing this). We consider both weight clipping and gradient penalties as regularization methods for enforcing the Lipschitz constraint on the discriminator required by the Wasserstein distance. \subsection{Evaluating synthetic data quality} For each dataset, but beginning with the simplest ones: \begin{itemize} \item Evaluate each descent method (measure: Wasserstein loss using second discriminator, trained after termination on final model, using $N$ fake samples, against $N$ test points) \item Holding $\epsilon$, $\delta$, and minibatch size fixed, vary number of steps vs noise amount (for both 1:1 and 5:1) \end{itemize} \subsection{Membership detection attacks} Show the extent to which membership attacks succeed Ideally, we should show that generated points are often very close to training data points even when training with optimism. Seems like there are sensible handcrafted measures we could use, such as quantiles for norm distance to closest point. Will also dig around to see if there are any standards for this task. \subsection{Limit cycles when training GANs with DP-SGD} If we're seeing good initial results with optimistic methods, we could try to recreate the experiments from \cite{daskalakis2017training} which show a sharp distinction between OMD and GD for convergence on simple distributions. Will do more lit review on the limit cycles problem, would be good to understand how this is ``observed'' in practice. What are the standard approaches for choosing when to sample, if training doesn't converge? Can we simultaneously avoid membership detection issues while improving stability of training with POMD? \section{Proof of Theorem \ref{thm:accuracy_theorem}} \label{sec:proof_accuracy_theorem} \begin{proof} We reduce to the (unrelaxed) projection mechanism, which has the following guarantee proven by \cite{projection}: for any dataset $D$ consisting of $n$ elements from a \emph{finite} data universe $\mathcal{X}$, and for any set of $m$ statistical queries $q$, the projection mechanism results in a dataset $D'$ such that: $\sqrt{\frac{1}{m}||q(D')-q(D)||_2^2} \leq \alpha$ for $$\alpha = O\left(\frac{(\ln(|\mathcal{X}|/\beta)\ln(1/\delta))^{1/4}}{\sqrt{\epsilon n}}\right).$$ Consider a finite data universe $\mathcal{X}^\eta = \{0, \eta, 2\eta, \ldots, 1\}^{d'}$ for some discretization parameter $0 < \eta < 1/k$. Given a dataset $D' \in \mathcal{X}^r$, let $D'_\eta \in \mathcal{X}^{\eta}$ be the dataset that results from ``snapping'' each real-valued $x \in D$ to its closest discrete valued point $x_\eta \in \mathcal{X}^r$. Observe that by construction, $||x-x(\eta)||_\infty \leq \eta$, and as a result, for $k$-way product query $q_i$, we have $|q_i(D') - q_i(D'_\eta)| \leq O(\eta k)$. Now let $\hat D' = \arg\min_{\hat D' \in (\mathcal{X}^r)^*}||a - q(\hat D')||$ and $D'' = \arg\min_{D'' \in (\mathcal{X}^\eta)^*}||a - q(D'')||$. From above, we know that $\sqrt{\frac{1}{m}||q(D'') - q(\hat D')||} \leq O(\eta k)$, and hence from an application of the triangle inequality, we have that $\sqrt{\frac{1}{m}||q(D) - q(\hat D')||_2^2} \leq O\left(\frac{(\ln(|\mathcal{X}^\eta|/\beta)\ln(1/\delta))^{1/4}}{\sqrt{\epsilon n}} + \eta k\right)$. Finally, for any dataset $\hat D' \in (\mathcal{X}^r)^*$, there exists a dataset $D' \in (\mathcal{X}^r)^{n'}$ such that $\sqrt{\frac{1}{m}||q(D') - q(\hat D')||_2^2} \leq O(\frac{\sqrt{\log k}}{\sqrt{n'}})$ (This follows from a sampling argument, and is proven formally in \cite{BLR08}.) Hence, a final application of the triangle inequality yields: $$\sqrt{\frac{1}{m}||q(D) - q(D')||_2^2} \leq$$$$ O\left(\frac{(\ln(|\mathcal{X}^\eta|/\beta)\ln(1/\delta))^{1/4}}{\sqrt{\epsilon n}} + \eta k + \frac{\sqrt{\log k}}{\sqrt{n'}} \right)$$ Choosing $\eta = \frac{\sqrt{\log k}}{k \sqrt{n'}}$ and noting that $|\mathcal{X}^\eta| = (\frac{1}{\eta})^{d'}$ yields the bound in our theorem. \end{proof} \section{Proof of Theorem \ref{thm:privacy}} \label{sec:proof_privacy} \begin{proof} The privacy of Algorithm \ref{alg:main} follows straightforwardly from the tools we introduced in Section \ref{sec:prelims}. First consider the case of $T = 1$. The algorithm makes $m$ calls to the Gaussian mechanism, each of each satisfies $\rho/m$-zCDP by construction and Lemma \ref{lem:gaussian}. In combination, this satisfies $\rho$-zCDP by the composition Lemma (Lemma \ref{lem:composition}). It then makes a call to the relaxed projection algorithm $RP$, which is a postprocessing of the Gaussian mechanism, and hence does not increase the zCDP parameter, by Lemma \ref{lem:post}. Hence the algorithm is $\rho$-zCDP, and by our choice of $\rho$ and Lemma \ref{lem:conversion}, satisfies $(\epsilon,\delta)$ differential privacy. Now consider the case of $T > 1$. Each iteration of the inner loop makes one call to report noisy max, and one call to the Gaussian mechanism. By construction and by Lemmas \ref{lem:gaussian} and \ref{lem:RNM}, each of these calls satisfies $\frac{\rho}{2TK}$-zCDP, and together by the composition Lemma \ref{lem:composition}, satisfy $\frac{\rho}{TK}$-zCDP. The algorithm then makes a call to the relaxed projection algorithm $RP$, which is a post-processing of the composition of the Gaussian mechanism with report noisy max, and so does not increase the zCDP parameter by Lemma \ref{lem:post}. The inner loop runs $T\cdot K$ times, and so the entire algorithm satisfies $\rho$-zCDP by the composition Lemma \ref{lem:composition}. By our choice of $\rho$ and Lemma \ref{lem:conversion}, our algorithm satisfies $(\epsilon,\delta)$ differential privacy as desired. \end{proof} \section{Additional Plots} \label{sec:extraplots} \begin{figure}[t] \begin{tabular}{cc} \includegraphics[width=.48\columnwidth]{marginal_figs/total_queries_3.png} & \includegraphics[width=.48\columnwidth]{marginal_figs/total_queries_5.png} \end{tabular} \vspace{-.5cm} \caption{Total number of queries consistent with the selected random 3-way and 5-way marginals on ADULT and LOANS datasets. Y-axis in log scale.} \label{fig:queries} \end{figure} Figure \ref{fig:queries} provides the correspondence between the workload size and the number of marginal queries preserved in our experiments. Note that LOANS is a higher dimensional dataset, and so the number of queries continues to increase with the workload, whereas for large enough workloads, we saturate all available queries on ADULT. Figure \ref{fig:runtime} docuemnts our investigation of the run-time and accuracy of our algorithm as a function of the synthetic dataset size $n'$. $n'$ is a hyperparameter that we can use to trade of the representation ability of our synthetic data (larger $n'$ allows the synthetic data to represent richer sets of answer vectors) with optimization cost. In Figure \ref{fig:runtime} we plot a) the run-time per iteration, b) the total run-time (over all iterations), and c) the error on several datasets and workloads, all as a function of $n'$. We find that although (as expected) the run-time per iteration is monotonically increasing in $n'$, the overall run-time is not --- it grows for sufficiently large $n'$, but also grows for $n'$ that is very small. This seems to be because as our optimization problem becomes sufficiently under-parameterized, the optimization becomes more difficult, and thus our algorithm needs to run for more iterations before convergence. We find that $n' = 1000$ is generally a good choice across datasets and query workloads, simultaneously achieving near minimal error and run-time. Hence we use $n' = 1000$ for all of our other experiments. \begin{figure}[t] \begin{tabular}{p{0.5\columnwidth}p{0.5\columnwidth}} \includegraphics[width=.5\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{marginal_figs/average_running_time.png} & \includegraphics[width=.5\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{marginal_figs/stacked_log_scale_running_time.png} \\ \textbf{(a)} Per-iteration run-time as a function of $n'$ & \textbf{(b)}Total run-time as a function of $n'$ \\[6pt] \includegraphics[width=.5\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{marginal_figs/stacked_log_scale.png} & \\ & \\ \textbf{(c)} Error as a function of $n'$ & \\[6pt] \end{tabular} \vspace{-.5cm} \caption{Run time and error as a function of the synthetic dataset size $n'$. At $n' = 1000$, both total run-time and overall error are near optimal across all settings.} \label{fig:runtime} \end{figure} \section{Linear Threshold Functions} In the body of the paper, we focused on \emph{marginal} queries because of their centrality in the differential privacy literature. But our techniques easily extend to other classes of statistical queries --- all that is required is that we can write python code to evaluate (a differentiable surrogate for) queries in our class. Here we do this for a natural class of linear threshold functions: $t$-out-of-$k$ threshold functions. \begin{definition} A $t$-out-of-$k$ threshold queries is defined by a subset $S \subseteq [d]$ of $|S| = k$ features, a particular value for each of the features $y \in \prod_{i \in S} \mathcal{X}_i$, and a threshold $t \leq k$. Given such a pair $(S, y,t)$, the corresponding statistical query $q_{S,y,t}$ is defined as: $$q_{S,y,t}(x) = \mathbbm{1}(\sum_{i \in S} \mathbbm{1}(x_i = y_i) \geq t)$$ Observe that for each collection of features $S$, there are $\prod_{i \in S}|\mathcal{X}_i|$ many $t$-out-of-$k$ threshold queries for each threshold $t$. \end{definition} In words, a $t$-out-of-$k$ threshold query evaluates to 1 exactly when at least $t$ of the $k$ features indexed by $S$ take the values indicated by $y$. These generalize the marginal queries that we studied in the body of the paper: A marginal query is simply the special case of a $t$-out-of-$k$ threshold query for $t = k$. To use our approach to generate synthetic data for $t$-out-of-$k$ linear threshold functions, we need an extended differentiable query class for them. It will be convenient to work with the same one-hot-encoding function $h:\mathcal{X}\rightarrow \{0,1\}^{d'}$ from the body of the paper, that maps $d$-dimensional vectors of categorical features to $d'$-dimensional vectors of binary features. Our statistical queries are then binary functions defined on the hypercube. We can generically find a differentiable surrogate for our query class by polynomial interpolation: in fact for every boolean function that depends on $k$ variables, there always exists a polynomial of degree $k$ that matches the function on boolean variables, but also extends it in a differentiable manner to the reals. $t$-out-of-$k$ threshold functions are such a class, and so can always be represented by polynomials of degree $k$. \begin{lemma} Any boolean class of queries that depends on at most $k$ variables (i.e. a `$k$-junta') has an equivalent extended differentiable query that is a polynomial of degree $k$. \end{lemma} In our experiments we will consider $1$-out-of-$k$ queries, which have an especially simple extended differentiable representation. \begin{definition} Given a subset of features $T \subseteq [d']$, the $1$-out-of-$k$ polynomial query $q_T:\mathcal{X}^r\rightarrow \mathbb{R}$ is defined as: $q_T(x) = 1 - \prod_{i \in T} (1-x_i)$. \end{definition} It is easy to see that $1$-out-of-$k$ polynomials are extended differentiable queries equivalent to $1$-out-of-$k$ threshold queries. They are differentiable because they are polynomials. A $1$-out-of-$k$ threshold query corresponding to a set of $k$ binary features $T$ (i.e. the one-hot encoded indices for the categorical feature values $y_i$) evaluates to $0$ exactly when \emph{every} binary feature $x_i \in T$ takes value $x_i = 0$ --- i.e. exactly when $\prod_{i \in T}(1-x_1) = 1$. Our $1$-out-of-$k$ polynomials are the negation of this monomial on binary valued inputs. The code to evaluate such queries is similarly easy to write --- see Figure \ref{fig:python_snippet2}. \begin{figure} \begin{lstlisting}[language=Python, linewidth=\columnwidth,breaklines=true, basicstyle=\small] import jax.numpy as np def threeway_thresholded_marginals(D): return (D.shape[0] - np.einsum('ij,ik,il->jkl', 1-D, 1-D, 1-D))/D.shape[0] \end{lstlisting} \caption{Python function used to compute (an extended equivalent differentiable query for) 1-out-of-3 linear threshold functions} \label{fig:python_snippet2} \end{figure} We repeat our experiments on the Adult and Loans datasets using $1$-out-of-$3$ threshold queries in place of $3$-way marginals. All other experimental details remain the same. In Figure \ref{fig:threshold_queries}, we report the results on a workload of size 64, with $\delta$ fixed to $1/n^2$, and $\epsilon$ ranging from 0.1 to 1.0. \begin{figure}[h!] \center \includegraphics[width=\columnwidth]{marginal_figs/stacked_threshold_1.png} \caption{Max error for increasing $\epsilon$ of 1-out-of-3 threshold queries with workload 64} \label{fig:threshold_queries} \end{figure} \section{Ablation studies} Our paper contains two innovations on top of the projection mechanism of Nikolov et al. The 1st is to turn the projection into a differentiable optimization problem, and the 2nd is to perform this projection iteratively, restricted to a small number of the highest error remaining queries. The 1st idea is required to make the algorithm implementable, but is not enough to make it competitive with prior work --- See Figure \ref{fig:epsilons}(d) in which we plot the error distribution of the nonadaptive $(T=1)$ version of our algorithm. \begin{figure}[t] \begin{tabular}{cc} {\includegraphics[width=.98\columnwidth]{figs/non_adaptive_comparison.png}} \end{tabular} \caption{Box plots of query error distributions on Adult 64 3-way marginals for the nonadaptive ($T=1$) version of our algorithm.} \label{fig:epsilons} \end{figure} \section{Relaxing the Projection Mechanism} \label{sec:relax} The projection mechanism of \cite{projection} can be described simply in our language. Given a collection of $m$ statistical queries $q$ and zCDP parameter $\rho$, it consists of two steps: \begin{enumerate} \item For each $i$, evaluate $q_i$ on $D$ using the Gaussian mechanism: $\hat a_i = G(D,q_i,\rho/m)$. \item Find the synthetic dataset\footnote{In fact, in \cite{projection}, the projection is onto a set of datasets that allows datapoints to have positive or negative weights --- but their analysis also applies to projections onto the set of synthetic datasets in our sense. A statement of this can be found as Lemma 5.3 in \cite{proj2}.} $D'$ whose query values are closest to $\hat a$ in $\ell_2$ norm --- i.e., let $D' = \arg\min_{D' \in \mathcal{X}^*} ||q(D') - \hat a||_2$. \end{enumerate} The output of the mechanism is the synthetic dataset $D'$, which implicitly encodes the answer vector $a' = q(D')$. Because the perturbation in Step 1 is Gaussian, and the projection is with respect to the $\ell_2$ norm, $D'$ is the maximum likelihood estimator for the dataset $D$ given the noisy statistics $\hat a$. The projection also serves to enforce consistency constraints across all query answers, which perhaps counter-intuitively, is accuracy-improving. For intuition, the reader can consider the case in which all queries $q_i$ are identical: in this case, the scale of the initial Gaussian noise is $\Omega(\sqrt{m}/n)$, which is sub-optimal, because the single query of interest could have been privately answered with noise scaling only as $O(1/n)$. But the effect of the projection will be similar to \emph{averaging} all of the perturbed answers $\hat a_i$, because $q_i(D')$ will be constrained to take a fixed value across all $i$ (since the queries are identical), and the mean of a vector of noisy estimates minimizes the Euclidean distance to those estimates. This has the effect of averaging out much of the noise, recovering error $O(1/n)$. The projection mechanism is easily seen to be $\rho$-zCDP --- the $m$ applications of $(\rho/m)$-zCDP instantiations of the Gaussian mechanism in Step 1 compose to satisfy $\rho$-zCDP by the composition guarantee of zCDP (Lemma \ref{lem:composition}), and Step 2 is a post-processing operation, and so by Lemma \ref{lem:post} does not increase the privacy cost. This mechanism is nearly optimal amongst the class of all differentially private mechanisms, as measured by $\ell_2$ error, in the worst case over the choice of statistical queries \cite{projection}. Unfortunately, Step 2 is in general an intractable computation, since it is a minimization of a non-convex and non-differentiable objective over an exponentially large discrete space. The first idea that goes into our algorithm (Algorithm \ref{alg:proj}) is to relax the space of datasets $\mathcal{X}^n$ to be a continuous space, and to generalize the statistical queries $q_i$ to be differentiable over this space. Doing so allows us to apply powerful GPU-accelerated tools for differentiable optimization to the projection step 2. \paragraph{From Categorical to Real Valued Features} Our first step is to embed categorical features into \emph{binary} features using a one-hot encoding. This corresponds to replacing each categorical feature $\mathcal{X}_i$ with $t_i$ binary features $\mathcal{X}_i^1\times\ldots\times\mathcal{X}_i^{t_i} = \{0,1\}^{t_i}$, for each $x \in \mathcal{X}$. Exactly one of these new $t_i$ binary features corresponding to categorical feature $i$ is set to 1 for any particular data point $x \in \mathcal{X}$: If $x_i = v_j$ for some $v_j \in \mathcal{X}_i$, then we set $\mathcal{X}_i^j = 1$ and $\mathcal{X}_i^{j'} = 0$ for all $j' \neq j$. Let $d' = \sum_{i=1}^d t_i$ be the dimension of a feature vector that has been encoded using this one-hot encoding. Under this encoding, the datapoints $x$ are embedded in the binary feature space $\{0,1\}^{d'}$. We will aim to construct synthetic data that lies in a continuous relaxation of this binary feature space. For example, choosing $\mathcal{X}^{r} = [0,1]^{d'}$ is natural. In our experiments, we choose $\mathcal{X}^{r} =[-1,1]^{d'}$, which empirically leads to an easier optimization problem. We further apply a SparseMax~\cite{martins2016softmax} transformation to convert this relaxed data domain into the set of (sparse) probability distributions over one-hot encodings. In addition to improving accuracy, this transformation allows us to apply randomized rounding to recover a dataset in the original schema: we discuss this further in Section~\ref{sec:sparse_max_projection}. Let $h:\mathcal{X}\rightarrow \{0,1\}^{d'}$ represent the function that maps a $x \in \mathcal{X}$ to its one-hot encoding. We abuse notation and for a dataset $D \in \mathcal{X}^n$, write $h(D)$ to denote the one-hot encoding of every $x \in D$. \paragraph{From Discrete to Differentiable Queries} Consider a marginal query $q_{S,y}:\mathcal{X}\rightarrow \{0,1\}$ defined by some $S \subseteq [d]$ and $y \in \prod_{i\in S} \mathcal{X}_i$. Such a query can be evaluated on a vector of categorical features $x \in \mathcal{X}$ in our original domain. Our goal is to construct an \emph{equivalent extended differentiable query} $\hat q_{S,y}:\mathcal{X}^r\rightarrow \mathbb{R}$ that has two properties: \begin{definition}[Equivalent Extended Differentiable Query] Given a statistical query $q_i : \mathcal{X}\rightarrow [0,1]$, we say that $\hat q_i : \mathcal{X}^r\rightarrow \mathbb{R}$ is an extended differentiable query that is equivalent to $q_i$ if it satisfies the following two properties: \begin{enumerate} \item $\hat q_i$ is differentiable over $\mathcal{X}^r$ --- i.e. for every $x \in \mathcal{X}^r$, $\nabla q_i(x)$ is defined, and \item $\hat q_i$ agrees with $q_i$ on every feature vector that results from a one-hot encoding. In other words, for every $x \in \mathcal{X}$: $q_i(x) = \hat q_{i} (h(x))$. \end{enumerate} \end{definition} We will want to give equivalent extended differentiable queries for the class of $k$-way marginal queries. Towards this end, we define a product query: \begin{definition} Given a subset of features $T \subseteq [d']$, the product query $q_T:\mathcal{X}^r\rightarrow \mathbb{R}$ is defined as: $q_T(x) = \prod_{i \in T} x_i$. \end{definition} By construction, product queries satisfy the first requirement for being extended differentiable queries: they are defined over the entire relaxed feature space $\mathcal{X}^r$, and are differentiable (since they are monomials over a real valued vector space). It remains to observe that for every marginal query $q_{S,y}$, there is an equivalent product query $\hat q_{S,y}$ that takes value $q_{S,y}(x)$ on the one-hot encoding $h(x)$ of $x$ for every $x$. \begin{lemma} Every $k$-way marginal query has an equivalent extended differentiable query in the class of product queries. In other words, for every $k$-way marginal query $q_{S,y}:\mathcal{X}^n\rightarrow \{0,1\}$, there is a corresponding product query $\hat q_{S,y} = q_T(y):\mathcal{X}^r\rightarrow \mathbb{R}$ with $|T| = k$ such that for every $x \in \mathcal{X}$: $q_{S,y}(x) = q_T(h(x))$. \label{test} \end{lemma} \begin{proof} We construct $T$ in the straightforward way: for every $i \in S$, we include in $T$ the coordinate corresponding to $y_i \in \mathcal{X}_i$. Now consider any $x$ such that $q_{S,y}(x) = 1$. It must be that for every $i \in S$, $x_i = y_i$. By construction, the product $q_T(h(x)) = \prod_{j \in T} h(x)_j = 1$ because all terms in the product evaluate to 1. Similarly, if $q_{S,y}(x) = 0$, then it must be that for at least one coordinate $j \in T$, $h(x)_j = 0$, and so $q_T(h(x)) = \prod_{j \in T} h(x)_j = 0$. \end{proof} \input{statpreservation} \section{Empirical Evaluation} \input{marginal_results} \section{Conclusion} We have presented a new, extensible method for privately answering large numbers of statistical queries, and producing synthetic data consistent with those queries. Our method relies on a continuous, differentiable relaxation of the projection mechanism, which allows us to use existing powerful tooling developed for deep learning. We demonstrate on a series of experiments that our method out-performs existing techniques across a wide range of parameters in the large workload regime. \section{Conclusion} In this work, we proposed a novel approach DCO for synhtetic data generation with privacy guarantees. We used both Zero-Sum and $\ell_{infty}$-norm as and objective and showed that the Zero-Sum DCO performs better than $\ell_{infty}$-norm DCO. We also provided a holistic view of GAN-based approaches. Our results show that simple Zero-Sum DCO approach performs as well as GAN-based approaches for linearly separable datasets. However, GAN-based approaches perform better to learn more complex representations. \section{Experiments} \subsection{Experimental Setup} \paragraph{Datasets.} We conduct experiments on a number of synthetic datasets --- a grid of Gaussians, intersecting crescents, nested circles, and imbalanced blobs --- as well as several image and tabular datasets, including MNIST, CIFAR-10, and the Breast Cancer, Forest Fires, Blog Feedback, and Adult Income datasets from the UCI Machine Learning Repository \cite{Dua:2019}. For tabular datasets, we restrict to numerical or binary columns. We also conduct experiments with the image datasets MNIST and CIFAR-10. \wb{KK: add citations} \paragraph{Model architectures.} For each of the datasets, we use standard feedforward networks with ReLU activation, with 6 layers for the generator and 8 for the discriminator, all of width 512, and an input space of 256 dimensions for the generator. We use the Wasserstein distance with gradient penalty as our loss function. \paragraph{Evaluation benchmarks.} For toy datasets, we evaluate quality by estimating the Wasserstein distance between the learned and target distributions using a second discriminator network (trained non-privately with Adam, using the same architecture), as well as through manual inspection of samples. \wb{KK: Can we not directly measure the distance by generating the same number of synthetic data points as the original ones?}\wb{I don't believe computing Wasserstein/optimal transport is poly-time tractable for arbitrary domains even with fixed sample sizes, as it requires taking a maximum over all 1-Lipschitz functions, or a minimum over all joint distributions with the correct marginals.} Additionally, for real datasets we evaluate quality by measuring the performance of machine learning models trained on generated data. \paragraph{Model selection.} For the Wasserstein and prediction objectives, we take the maximum over models saved periodically over training. For visualizing samples from toy datasets we use the final model. \iffalse Which model or combination of models should be used for generating synthetic data? For initial experiments we have simply used the final model \wb{KK: what does this mean?}, but additional selection methods may be useful in improving performance for a given privacy budget, such as: \begin{itemize} \item Choosing the best model for the evaluation metric using private selection. An example being \cite{jingcheng2019PrivateSelection} which allows for model choice without too much additional loss in privacy \item Using the historical distribution over models (this is "theoretically correct" in linear games, and mixtures have generalization benefits \cite{arora2017generalization}) \item Averaging the parameters of learned models (often used in practice, see e.g. \cite{yazc2018unusual}) \item Post-GAN Boosting \cite{neunhoeffer2020private} \end{itemize} We intend to explore these with further experimentation. \fi \paragraph{Parameters affecting privacy.} The privacy loss $\epsilon$ is computed as a function of the number of training samples ($N$), the number of discriminator minibatch steps, minibatch and microbatch sizes, the amount of noise added to gradient estimates, and the target additive privacy loss $\delta$. The scale of noise is governed by a multiplier $\sigma$ as well as the gradient clipping bound $C$. The privacy loss does not depend on $C$, but calibrating it correctly is important as it results in excessive noise if it is too large and damages gradients if too small. As such, for a fixed dataset and target privacy loss, we have a number of degrees of freedom in satisfying the privacy guarantee. Understanding this calibration process is a major goal of our work. \paragraph{Implementation.} We train our networks with PyTorch, using the Pyvacy library \cite{Waites2019PyVacyTP} for privacy enforcement. Pyvacy handles the batching of the dataset into mini- and microbatches, gradient manipulation and privacy accounting. The authors implemented the optimistic versions of SGD and Adam. \subsection{\wb{Experiment: }Visualizing Toy Data} Training on \textasciitilde 1M points, we are able to achieve reasonable-looking synthetic data using Optimistic Adam, with values of $\epsilon$ ranging from \textasciitilde 2500-5000, shown in \Cref{fig:toydata}. This is, admittedly, a very high $\epsilon$, yet it can be improved by adjusting the L2 clipping norm of the gradients to the median of gradients in non-private training. These toy datasets are also \textit{hard}, non-Gaussian datasets. Results are comparable with Adam and worse with other optimizers. Here, dots denote the "real data" and pluses denote the synthetic data, where color is a feature. For the grid of Gaussians, we display the kernel density estimation for synthetic data. \wb{KK: Will be helpful to state the parameters involved, e.g., mean/variance values} \begin{figure} \centering \includegraphics[width=5.5cm]{figs/1048577_OptAdam_privTrue_i30001_mb64_n0.05_7-29-2020_4_9train.png} \includegraphics[width=5.5cm]{figs/1048577_OptAdam_privTrue_i40001_mb64_n0.05_7-29-2020_0_6train.png} \includegraphics[width=5.5cm]{figs/1048576_OptAdam_privTrue_i50001_mb64_n0.04_7-29-2020_5_27train.png} \includegraphics[width=5.5cm]{figs/1048577_OptAdam_privTrue_i50001_mb64_n0.04_7-29-2020_4_55train.png} \caption{Private GANs Trained on Toy Data} \label{fig:toydata} \end{figure} \subsection{\wb{Experiment: }Choosing the Best Optimizer for GANs} In \Cref{fig:wloss}, we show the progress of several training algorithms over time on Gaussian grid toy data, for varying levels of the noise parameter $\sigma$ for gradient estimates, evaluating by periodically computing the Wasserstein distance for the network. Performance degrades as noise increases, resulting in more iterations before convergence, and training fails to converge for all optimizers for $\sigma = 0.1$. Adam, Optimistic Adam, and RMSprop perform comparably well across noise levels, whereas Adagrad fails to converge in each instance. For the latter three optimizers we evaluate different ratios for discriminator and generator steps, and find that a ratio of 5, particularly for Adam, consistently results in better performance. \begin{figure} \centering \includegraphics[width=5.5cm]{figs/many_opts_001.png} \includegraphics[width=5.5cm]{figs/many_opts_003.png} \includegraphics[width=5.5cm]{figs/many_opts_05.png} \includegraphics[width=5.5cm]{figs/many_opts_0.1.png} \includegraphics[width=5.5cm]{figs/BESTOPT4_gaussiangrid_0.1.png} \includegraphics[width=5.5cm]{figs/BESTOPT4_gaussiangrid_0.05.png} \includegraphics[width=5.5cm]{figs/BESTOPT4_gaussiangrid_0.01.png} \caption{Wasserstein Loss across Optimizers and Noise Levels} \label{fig:wloss} \end{figure} \wb{ \paragraph{Proposal.} For the Gaussian Grid, MNIST, and Breast Cancer datasets, we plot the estimated Wasserstein loss over training, for $\sigma \in \{0.01, 0.05, 0.1\}$, using the Adam, OptAdam, and RMSProp optimizers, both for G-D ratios 1 and 5 (9 plots total). } \subsection{\wb{Experiment: }GANs for Downstream ML} In addition to evaluating with Wasserstein loss, another useful metric is understanding the usefulness of synthetic data for machine learning. Using Adam with a ratio of 5, for the Crescents, Breast Cancer, and Adult datasets, we we generate synthetic data using GANs, which we then use to train a set of classification models, whose performance we evaluate on the original data. For each dataset, we train a GAN for 25K iterations using $\sigma \in \{0.01, 0.05, 0.1, 0.5, 1.5 \}$. For each $\sigma$, we train using all clipping parameters $C \in \{0.2, 0.5, 1, 2.5\}$. For any fixed $\epsilon$ and $\sigma$, there is some prefix of the sequence of 25K iterations for which the privacy budget is not exhausted. For each $\epsilon$, we select the best result by searching over $\sigma$, $C$, and the corresponding prefix sequence. The (best) performance of several classifiers, for both accuracy and F1 score, is plotted as a function of $\epsilon$ and displayed in \Cref{fig:gan_best_ml_eps}. Results for some fixed parameter settings, benchmarked with the performance of classifiers trained directly on the data, are shown in \Cref{fig:gan-classification}. \begin{figure} \centering \includegraphics[width=5.5cm]{figs/cancer_eps_best_ML_2.png} \includegraphics[width=5.5cm]{figs/crescents_eps_best_ML_3.png} \includegraphics[width=5.5cm]{figs/adult_eps_best_ML_3.png} \caption{GAN Classification Evaluations vs $\epsilon$ (Cancer, Crescents, Adult)} \label{fig:gan_best_ml_eps} \end{figure} \begin{figure} \centering \includegraphics[width=5.5cm]{figs/test_MLplotPRIV10e6.png} \includegraphics[width=5.5cm]{figs/test_MLplotPRIV10e8.png} \includegraphics[width=5.5cm]{figs/test_MLplotPRIV10e14.png} \includegraphics[width=5.5cm]{figs/test_MLplot_NONPRIV.png} \caption{Classification using Synthetic Data from GANs ($\epsilon = [10^6, 10^8, 10^{14}, \infty]$)} \label{fig:gan-classification} \end{figure} The results demonstrate that the utility of the synthetic data increases as the privacy parameter $\epsilon$ (low privacy) increases as expected due to privacy and utility trade-off. \subsection{\wb{Experiment: }Direct Consistency Optimization for Downstream ML} We also evaluate the usefulness of synthetic data generated by direct consistency optimization, computed both using the zero-sum game approach and gradient descent on the $\ell_{\infty}$ norm. As we did for GANs, results for increasing $\epsilon$ are shown in \Cref{fig:zs_dco_best_ml_eps} and \Cref{fig:linf_dco_best_ml_eps}, for the zero-sum game and $\ell_{\infty}$ optimization methods, respectively. Fixed-parameter comparisons to non-private training are shown in \Cref{fig:dco-classification}. In the appendix, we visualize the generated synthetic Crescents data for each method (in \Cref{fig:dco-crescents}). Results in \Cref{fig:zs_dco_best_ml_eps} show that the utility of the synthetic data increases as the parameter $\epsilon$ increases for both datasets when Zero-Sum DCO is used. However, $\ell_{\infty}$-norm DCO performs poorly for both datasets. \begin{figure} \centering \includegraphics[width=5.5cm]{figs/cancer_eps_best_ML_ALL_game.png} \includegraphics[width=5.5cm]{figs/crescents_eps_best_ML_ALL_game.png} \caption{Zero-Sum DCO Classification Evaluations vs $\epsilon$ (Cancer, Crescents)} \label{fig:zs_dco_best_ml_eps} \end{figure} \begin{figure} \centering \includegraphics[width=5.5cm]{figs/cancer_eps_best_ML_ALL_opt.png} \includegraphics[width=5.5cm]{figs/crescents_eps_best_ML_ALL_opt.png} \caption{$\ell_{\infty}$-norm DCO Classification Evaluations vs $\epsilon$ (Cancer, Crescents)} \label{fig:linf_dco_best_ml_eps} \end{figure} \begin{figure} \centering \includegraphics[width=5.5cm]{figs/ML_evals_game.png} \includegraphics[width=5.5cm]{figs/ML_evals_opt.png} \caption{Classification using Synthetic Data from DCO (Zero-Sum and $\ell_{\infty}$-norm, $\epsilon = 1000$)} \label{fig:dco-classification} \end{figure} \wb{ We can do this concurrently with the previous experiment. Plot organization will be equivalent, except factored by $\sigma$, as we are computing several losses for each. One question to explore will be the extent to which success across the two metrics is correlated. } \subsection{GANs vs DCO} On the whole, we find that GANs are often capable of generating data which is useful for classification subject to some degree of differential privacy. A barrier to strong results for the Cancer dataset is that we train on only $2^9$ points, which requires adding substantial noise for maintaining privacy. Here, DCO reaches almost 80\% accuracy at $\epsilon=8$, whereas this is not attained until $\epsilon=64$ for GANs. For the Crescents dataset (which has balanced labels) with $2^{15}$ points, we are able to obtain results above 80\% even at $\epsilon=1$ and can approach perfect classification as $\epsilon$ increases. DCO does not result in nearly as high levels of accuracy even for large $\epsilon$, but the generated data can be sufficient for approximating the performance of the best non-private {\it linear} model at smaller values of $\epsilon$. The crescents example is particularly telling, as labels are separable by a low-degree polynomial but not by a linear classifier. Holistically, we find that when there is enough data, GANs are more powerful for creating synthetic datasets which preserve more complex structures (non-Gaussian features, non-linear feature relationships) in datasets. However, if data is limited and linear models are appropriate for the classification task, DCO can create data preserving these relationships at a modest privacy cost. \section{Introduction} \label{sec:intro} A basic problem in differential privacy is to accurately answer a large number $m$ of statistical queries (also known as \emph{linear} and \emph{counting} queries), which have the form, ``how many people in private dataset $D$ have property $P$?'' Marginal queries (also known as \emph{conjunctions}) --- which ask how many people in the dataset have particular combinations of feature values --- are one of the most useful and most studied special cases. The simplest technique for answering such queries is to compute each answer on the private dataset, and then perturb them with independent Gaussian noise. For a dataset of size $n$, this results in error scaling as $\tilde O\left(\frac{\sqrt{m}}{n}\right)$ \cite{delta}. This simple technique is useful for answering small numbers of queries. But it has been known since \cite{BLR08} that \emph{in principle}, it is possible to privately and accurately answer very large classes of queries (of size exponential in $n$), and that an attractive way of doing so is to encode the answers in a \emph{synthetic dataset}. Synthetic datasets have several advantages: most basically, they are a concise way of representing the answers to large numbers of queries. But they also permit one to evaluate queries \emph{other} than those that have been explicitly answered by the mechanism, and to take advantage of \emph{generalization}. Unfortunately, it is also known that improving on the error of the simple Gaussian perturbation technique is computationally hard in the worst case \cite{hardquery}. Moreover, constructing synthetic datasets is hard even when it would be possible to provide accurate answers with simple perturbation \cite{hardsynthetic} for simple classes of queries such as the set of all $d \choose 2$ marginal queries restricted to 2 out of $d$ binary features (so-called $2$-way marginals). As a result we cannot hope for a differentially private algorithm that can provably answer large numbers of statistical queries or generate interesting synthetic data in polynomial time. Nevertheless, there has been a resurgence of interest in private synthetic data generation and large-scale private queries due to the importance of the problem. Recent methods offer provable privacy guarantees, but have run-time and accuracy properties that must be evaluated empirically. \subsection{Our Contributions} Our starting point is the (computationally inefficient) \emph{projection mechanism} of \cite{projection}, which is informally described as follows. We begin with a dataset $D \in \mathcal{X}^n$. First, the values of each of the $m$ queries of interest $q_i$ are computed on the private dataset: $a = q(D) \in [0,1]^m$. Next, a privacy preserving vector of noisy answers $\hat a \in \mathbb{R}^m$ is computed using simple Gaussian perturbation. Finally, the vector of noisy answers $\hat a$ is \emph{projected} into the set of answer vectors that are consistent with some dataset to obtain a final vector of answers $a'$ --- i.e., the projection guarantees that $a' = q(D')$ for \emph{some} $D' \in \mathcal{X}^n$. This corresponds to solving the optimization problem of finding the synthetic dataset $D' \in \mathcal{X}^n$ that minimizes error $||q(D') - \hat a||_2$. This is known to be a near optimal mechanism for answering statistical queries \cite{projection} but for most data and query classes, the projection step corresponds to a difficult discrete optimization problem. We remark that the main purpose of the projection is not (only) to construct a synthetic dataset, but to improve accuracy. This is analogous to how learning with a restricted model class like linear classifiers can improve accuracy if the data really is labeled by some linear function, i.e., the projection improves accuracy because by projecting into a set that contains the \emph{true} vector of answers $a$, it is imposing constraints that we know to be satisfied by the true (unknown) vector of answers. Our core algorithm is based on a continuous relaxation of this projection step. This allows us to deploy first-order optimization methods, which empirically work very well despite the non-convexity of the problem. A further feature of this approach is that we can take advantage of sophisticated existing tooling for continuous optimization --- including autodifferentiation (to allow us to easily handle many different query classes) and GPU acceleration, which has been advanced by a decade of research in deep learning. This is in contrast to related approaches like \cite{dualquery,Vietri2019NewOA} which use integer program solvers and often require designing custom integer programs for optimizing over each new class of queries. We then extend our core algorithm by giving an adaptive variant that is able to make better use of its privacy budget, by taking advantage of generalization properties. Rather than answering \emph{all} of the queries up front, we start by answering a small number of queries, and then project them onto a vector of answers consistent with a relaxed synthetic dataset --- i.e., a dataset in a larger domain than the original data --- but one that still allows us to evaluate queries. At the next round, we use a private selection mechanism to find a small number of additional queries on which our current synthetic dataset performs poorly; we answer those queries, find a new synthetic dataset via our continuous projection, and then repeat. If the queries we have answered are highly accurate, then we are often able to find synthetic data representing the original data well after only having explicitly answered a very small number of them (i.e., we \emph{generalize} well to new queries). This forms a virtuous cycle, because if we only need to explicitly answer a very small number of queries, we can answer them highly accurately with our privacy budget. By taking our relaxed data domain to be the set of \emph{probability distributions} over one-hot encodings of the original data domain, we can finally apply randomized rounding to output a synthetic dataset in the original schema. We evaluate our algorithm on several datasets, comparing it to two state-of-the-art algorithms from the literature. A key advantage of our algorithm is that we can scale to large query workloads (in our experiments we answer roughly 20 million queries on some datasets and do not hit computational bottlenecks). We outperform the state of the art algorithm FEM (``Follow-the-Perturbed-Leader with Exponential Mechanism'') from \cite{Vietri2019NewOA}, which is one of the few previous techniques able to scale to large workloads. We also compare to algorithms that are unable to scale to large workloads, comparing to one of the state of the art methods, optimized variants of the HDMM (``High Dimensional Matrix Mechanism'') from \cite{mckenna2019graphical}. When run on a workload of roughly 65 thousand queries provided by the authors of \cite{mckenna2019graphical}, HDMM outperforms our algorithm. The result is an algorithm that we believe to be state of the art for large query workloads, albeit one that can be outperformed for smaller workloads. \subsection{Additional Related Work} Differential privacy offers a formal semantics for data privacy and was introduced by \cite{Dwork2006CalibratingNT}. The differential privacy literature is far too large to survey here; see \cite{privacybook} for a textbook introduction. The problem of answering large numbers of queries on a private dataset (often via synthetic data generation) dates back to \cite{BLR08}. A line of early theoretical work \cite{BLR08,RR10,HR10,GRU12,projection} established statistical rates for answering very general classes of queries, showing that it is possible in principle (i.e., ignoring computation) to provide answers to \emph{exponentially many} queries in the size of the dataset. This line of work establishes statistically optimal rates for the problem (i.e., matching statistical lower bounds), but provides algorithms that have running time that is generally \emph{exponential} in the data dimension, and hence impractical for even moderately high dimensional data. Moreover, this exponential running time is known to be necessary in the worst case \cite{DNRRV09,hardsynthetic,hardquery}. As a result, a line of work has emerged that tries to avoid this exponential running time in practice. The ``Multiplicative Weights Exponential Mechanism'' \cite{MWEM} uses optimizations to avoid exponentially large representations when the query class does not require it. Dwork, Nikolov, and Talwar give a theoretical analysis of a convex relaxation of the projection mechanism that can answer $k$-way marginals in time polynomial in $d^k$ --- albeit with accuracy that is sub-optimal by a factor of $d^{k/2}$ \cite{efficientmarginals}.``Dual Query'' \cite{dualquery} used a dual representation of the optimization problem implicitly solved by \cite{RR10,HR10,MWEM} to trade off the need to manipulate exponentially large state with the need to solve concisely defined but NP-hard integer programs. This was an ``oracle efficient'' algorithm. The theory of oracle efficient synthetic data release was further developed in \cite{neel2019use}, and \cite{Vietri2019NewOA} give further improvements on oracle efficient algorithms in this dual representation, and promising experimental results. We compare against the algorithm from \cite{Vietri2019NewOA} in our empirical results. We remark that marginal queries (the focus of our experimental evaluation) have been considered a canonical special case of the general query release problem, and the explicit focus of a long line of work \cite{marginals1,marginals2,marginals3,marginals4,marginals5}. A parallel line of work on \emph{matrix mechanisms} focused on optimizing error within a restricted class of mechanisms. Informally speaking, this class answers a specially chosen set of queries explicitly with simple perturbation, and then deduces the answers to other queries by taking linear combinations of those that were explicitly answered. One can optimize the error of this approach by optimizing over the set of queries that are explicitly answered \cite{matrix1}. Doing this exactly is also intractable, because it requires manipulating matrices that are exponential in the data dimension. This line of work too has seen heuristic optimizations, and the ``high dimensional matrix mechanism'' \cite{HDMM} together with further optimizations \cite{mckenna2019graphical} is able to scale to higher dimensional data and larger collections of queries --- although to date the size of the query classes that these algorithms can answer is smaller by several orders of magnitude compared to our algorithm and others in the oracle efficient line of work. Finally, there is a line of work that has taken modern techniques for distribution learning (GANs, VAEs, etc.) and has made them differentially private, generally by training using private variants of stochastic gradient descent \cite{gan1,gan2,gan3,gan4,vae}. This line of work has shown some promise for image data as measured by visual fidelity, and for limited kinds of downstream machine learning tasks --- but generally has not shown promising results for enforcing consistency with simple classes of statistics like marginal queries. As a result we do not compare to approaches from this line of work. \section{Proof of Theorem \ref{thm:accuracy_theorem}} \label{sec:proof_accuracy_theorem} \begin{proof} We reduce to the (unrelaxed) projection mechanism, which has the following guarantee proven by \cite{projection}: for any dataset $D$ consisting of $n$ elements from a \emph{finite} data universe $\mathcal{X}$, and for any set of $m$ statistical queries $q$, the projection mechanism results in a dataset $D'$ such that: $\sqrt{\frac{1}{m}||q(D')-q(D)||_2^2} \leq \alpha$ for $$\alpha = O\left(\frac{(\ln(|\mathcal{X}|/\beta)\ln(1/\delta))^{1/4}}{\sqrt{\epsilon n}}\right).$$ Consider a finite data universe $\mathcal{X}^\eta = \{0, \eta, 2\eta, \ldots, 1\}^{d'}$ for some discretization parameter $0 < \eta < 1/k$. Given a dataset $D' \in \mathcal{X}^r$, let $D'_\eta \in \mathcal{X}^{\eta}$ be the dataset that results from ``snapping'' each real-valued $x \in D$ to its closest discrete valued point $x_\eta \in \mathcal{X}^r$. Observe that by construction, $||x-x(\eta)||_\infty \leq \eta$, and as a result, for $k$-way product query $q_i$, we have $|q_i(D') - q_i(D'_\eta)| \leq O(\eta k)$. Now let $\hat D' = \arg\min_{\hat D' \in (\mathcal{X}^r)^*}||a - q(\hat D')||$ and $D'' = \arg\min_{D'' \in (\mathcal{X}^\eta)^*}||a - q(D'')||$. From above, we know that $\sqrt{\frac{1}{m}||q(D'') - q(\hat D')||} \leq O(\eta k)$, and hence from an application of the triangle inequality, we have that $\sqrt{\frac{1}{m}||q(D) - q(\hat D')||_2^2} \leq O\left(\frac{(\ln(|\mathcal{X}^\eta|/\beta)\ln(1/\delta))^{1/4}}{\sqrt{\epsilon n}} + \eta k\right)$. Finally, for any dataset $\hat D' \in (\mathcal{X}^r)^*$, there exists a dataset $D' \in (\mathcal{X}^r)^{n'}$ such that $\sqrt{\frac{1}{m}||q(D') - q(\hat D')||_2^2} \leq O(\frac{\sqrt{\log k}}{\sqrt{n'}})$ (This follows from a sampling argument, and is proven formally in \cite{BLR08}.) Hence, a final application of the triangle inequality yields: $$\sqrt{\frac{1}{m}||q(D) - q(D')||_2^2} \leq$$$$ O\left(\frac{(\ln(|\mathcal{X}^\eta|/\beta)\ln(1/\delta))^{1/4}}{\sqrt{\epsilon n}} + \eta k + \frac{\sqrt{\log k}}{\sqrt{n'}} \right)$$ Choosing $\eta = \frac{\sqrt{\log k}}{k \sqrt{n'}}$ and noting that $|\mathcal{X}^\eta| = (\frac{1}{\eta})^{d'}$ yields the bound in our theorem. \end{proof} \section{Proof of Theorem \ref{thm:privacy}} \label{sec:proof_privacy} \begin{proof} The privacy of Algorithm \ref{alg:main} follows straightforwardly from the tools we introduced in Section \ref{sec:prelims}. First consider the case of $T = 1$. The algorithm makes $m$ calls to the Gaussian mechanism, each of each satisfies $\rho/m$-zCDP by construction and Lemma \ref{lem:gaussian}. In combination, this satisfies $\rho$-zCDP by the composition Lemma (Lemma \ref{lem:composition}). It then makes a call to the relaxed projection algorithm $RP$, which is a postprocessing of the Gaussian mechanism, and hence does not increase the zCDP parameter, by Lemma \ref{lem:post}. Hence the algorithm is $\rho$-zCDP, and by our choice of $\rho$ and Lemma \ref{lem:conversion}, satisfies $(\epsilon,\delta)$ differential privacy. Now consider the case of $T > 1$. Each iteration of the inner loop makes one call to report noisy max, and one call to the Gaussian mechanism. By construction and by Lemmas \ref{lem:gaussian} and \ref{lem:RNM}, each of these calls satisfies $\frac{\rho}{2TK}$-zCDP, and together by the composition Lemma \ref{lem:composition}, satisfy $\frac{\rho}{TK}$-zCDP. The algorithm then makes a call to the relaxed projection algorithm $RP$, which is a post-processing of the composition of the Gaussian mechanism with report noisy max, and so does not increase the zCDP parameter by Lemma \ref{lem:post}. The inner loop runs $T\cdot K$ times, and so the entire algorithm satisfies $\rho$-zCDP by the composition Lemma \ref{lem:composition}. By our choice of $\rho$ and Lemma \ref{lem:conversion}, our algorithm satisfies $(\epsilon,\delta)$ differential privacy as desired. \end{proof} \section{Additional Plots} \label{sec:extraplots} \begin{figure}[t] \begin{tabular}{cc} \includegraphics[width=.48\columnwidth]{marginal_figs/total_queries_3.png} & \includegraphics[width=.48\columnwidth]{marginal_figs/total_queries_5.png} \end{tabular} \vspace{-.5cm} \caption{Total number of queries consistent with the selected random 3-way and 5-way marginals on ADULT and LOANS datasets. Y-axis in log scale.} \label{fig:queries} \end{figure} Figure \ref{fig:queries} provides the correspondence between the workload size and the number of marginal queries preserved in our experiments. Note that LOANS is a higher dimensional dataset, and so the number of queries continues to increase with the workload, whereas for large enough workloads, we saturate all available queries on ADULT. Figure \ref{fig:runtime} documents our investigation of the run-time and accuracy of our algorithm as a function of the synthetic dataset size $n'$. $n'$ is a hyperparameter that we can use to trade of the representation ability of our synthetic data (larger $n'$ allows the synthetic data to represent richer sets of answer vectors) with optimization cost. In Figure \ref{fig:runtime} we plot a) the run-time per iteration, b) the total run-time (over all iterations), and c) the error on several datasets and workloads, all as a function of $n'$. We find that although (as expected) the run-time per iteration is monotonically increasing in $n'$, the overall run-time is not --- it grows for sufficiently large $n'$, but also grows for $n'$ that is very small. This seems to be because as our optimization problem becomes sufficiently under-parameterized, the optimization becomes more difficult, and thus our algorithm needs to run for more iterations before convergence. We find that $n' = 1000$ is generally a good choice across datasets and query workloads, simultaneously achieving near minimal error and run-time. Hence we use $n' = 1000$ for all of our other experiments. \begin{figure}[t] \begin{tabular}{p{0.5\columnwidth}p{0.5\columnwidth}} \includegraphics[width=.5\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{marginal_figs/average_running_time.png} & \includegraphics[width=.5\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{marginal_figs/stacked_log_scale_running_time.png} \\ \textbf{(a)} Per-iteration run-time as a function of $n'$ & \textbf{(b)}Total run-time as a function of $n'$ \\[6pt] \includegraphics[width=.5\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{marginal_figs/stacked_log_scale.png} & \\ & \\ \textbf{(c)} Error as a function of $n'$ & \\[6pt] \end{tabular} \vspace{-.5cm} \caption{Run time and error as a function of the synthetic dataset size $n'$. At $n' = 1000$, both total run-time and overall error are near optimal across all settings.} \label{fig:runtime} \end{figure} \section{Linear Threshold Functions} In the body of the paper, we focused on \emph{marginal} queries because of their centrality in the differential privacy literature. But our techniques easily extend to other classes of statistical queries --- all that is required is that we can write python code to evaluate (a differentiable surrogate for) queries in our class. Here we do this for a natural class of linear threshold functions: $t$-out-of-$k$ threshold functions. \begin{definition} A $t$-out-of-$k$ threshold query is defined by a subset $S \subseteq [d]$ of $|S| = k$ features, a particular value for each of the features $y \in \prod_{i \in S} \mathcal{X}_i$, and a threshold $t \leq k$. Given such a pair $(S, y,t)$, the corresponding statistical query $q_{S,y,t}$ is defined as: $$q_{S,y,t}(x) = \mathbbm{1}(\sum_{i \in S} \mathbbm{1}(x_i = y_i) \geq t)$$ Observe that for each collection of features $S$, there are $\prod_{i \in S}|\mathcal{X}_i|$ many $t$-out-of-$k$ threshold queries for each threshold $t$. \end{definition} In words, a $t$-out-of-$k$ threshold query evaluates to 1 exactly when at least $t$ of the $k$ features indexed by $S$ take the values indicated by $y$. These generalize the marginal queries that we studied in the body of the paper: A marginal query is simply the special case of a $t$-out-of-$k$ threshold query for $t = k$. To use our approach to generate synthetic data for $t$-out-of-$k$ linear threshold functions, we need an extended differentiable query class for them. It will be convenient to work with the same one-hot-encoding function $h:\mathcal{X}\rightarrow \{0,1\}^{d'}$ from the body of the paper, that maps $d$-dimensional vectors of categorical features to $d'$-dimensional vectors of binary features. Our statistical queries are then binary functions defined on the hypercube. We can generically find a differentiable surrogate for our query class by polynomial interpolation: in fact for every boolean function that depends on $k$ variables, there always exists a polynomial of degree $k$ that matches the function on boolean variables, but also extends it in a differentiable manner to the reals. $t$-out-of-$k$ threshold functions are such a class, and so can always be represented by polynomials of degree $k$. \begin{lemma} Any boolean class of queries that depends on at most $k$ variables (i.e. a `$k$-junta') has an equivalent extended differentiable query that is a polynomial of degree $k$. \end{lemma} In our experiments we will consider $1$-out-of-$k$ queries (equivalently, disjunctions), which have an especially simple extended differentiable representation. \begin{definition} Given a subset of features $T \subseteq [d']$, the $1$-out-of-$k$ polynomial query $q_T:\mathcal{X}^r\rightarrow \mathbb{R}$ is defined as: $q_T(x) = 1 - \prod_{i \in T} (1-x_i)$. \end{definition} It is easy to see that $1$-out-of-$k$ polynomials are extended differentiable queries equivalent to $1$-out-of-$k$ threshold queries. They are differentiable because they are polynomials. A $1$-out-of-$k$ threshold query corresponding to a set of $k$ binary features $T$ (i.e. the one-hot encoded indices for the categorical feature values $y_i$) evaluates to $0$ exactly when \emph{every} binary feature $x_i \in T$ takes value $x_i = 0$ --- i.e. exactly when $\prod_{i \in T}(1-x_1) = 1$. Our $1$-out-of-$k$ polynomials are the negation of this monomial on binary valued inputs. The code to evaluate such queries is similarly easy to write --- see Figure \ref{fig:python_snippet2}. \begin{figure} \begin{lstlisting}[language=Python, linewidth=\columnwidth,breaklines=true, basicstyle=\small] import jax.numpy as np def threeway_thresholded_marginals(D): return (D.shape[0] - np.einsum('ij,ik,il->jkl', 1-D, 1-D, 1-D))/D.shape[0] \end{lstlisting} \caption{Python function used to compute (an extended equivalent differentiable query for) 1-out-of-3 linear threshold functions} \label{fig:python_snippet2} \end{figure} We repeat our experiments on the Adult and Loans datasets using $1$-out-of-$3$ threshold queries in place of $3$-way marginals. All other experimental details remain the same. In Figure \ref{fig:threshold_queries}, we report the results on a workload of size 64, with $\delta$ fixed to $1/n^2$, and $\epsilon$ ranging from 0.1 to 1.0. \begin{figure}[h!] \center \includegraphics{marginal_figs/stacked_threshold_1.png} \caption{Max error for increasing $\epsilon$ of 1-out-of-3 threshold queries with workload 64} \label{fig:threshold_queries} \end{figure} \end{document} \subsection{Implementation and Hyperparameters} We implement\footnote{\href{https://www.github.com/amazon-research/relaxed-adaptive-projection}{github.com/amazon-research/relaxed-adaptive-projection}} Algorithm~\ref{alg:main} in Python \cite{python}, using the JAX library~\cite{jax2018github} for auto-differentiation of queries and the Adam optimizer~\cite{kingma2015adam} (with learning rate $0.001$) for the call to RP (Algorithm~\ref{alg:proj}). For each call to RP, we do early stopping if the relative improvement on the loss function between consecutive Adam steps is less than $10^{-7}$. The number of maximum Adam steps per RP round is set to $5000$. Fig.~\ref{fig:python_snippet} contains a Jax code snippet, which computes 3-way product queries on a dataset $D$. A benefit of using JAX (or other packages with autodifferentiation capabilities) is that to instantiate the algorithm for a new query class, all that is required is to write a new python function which computes queries in the class --- we do not need to perform any other reasoning about the class. In contrast, approaches like \cite{dualquery,Vietri2019NewOA} require deriving an integer program to \emph{optimize} over each new class of interest, and approaches like \cite{mckenna2019graphical} require performing an expensive optimization over each new workload of interest. This makes our method more easily extensible. \begin{figure} \begin{lstlisting}[language=Python, linewidth=\columnwidth,breaklines=true, basicstyle=\small] import jax.numpy as np def threeway_marginals(D): return np.einsum('ij,ik,il->jkl', D, D, D)/D.shape[0] \end{lstlisting} \caption{Python function used to compute 3-way product queries} \label{fig:python_snippet} \end{figure} JAX also has the advantages of being open source and able to take advantage of GPU acceleration. We run our experiments for Algorithm~\ref{alg:main} on an EC2 p2.xlarge instance (1 GPU, 4 CPUs, 61 GB RAM). For FEM we use the code from the authors of~\cite{Vietri2019NewOA} available at~\url{https://github.com/giusevtr/fem}, using the hyperparameters given in their tables 2 and 3 for the experimental results we report in Figures \ref{fig:epsilons} and \ref{fig:workloads}, respectively. Their code requires the Gurobi integer program solver; we were able to obtain a license to Gurobi for a personal computer, but not for EC2 instances, and so we run FEM on a 2019 16" MacBook Pro (6 CPUs, 16GB RAM) (Gurobi does not support GPU acceleration) --- as a result we do not report timing comparisons. We remark that an advantage of our approach is that it can leverage the robust open-source tooling (like JAX and Adam) that has been developed for deep learning, to allow us to easily take advantage of large-scale distributed GPU accelerated computation. For HDMM+LSS and HDMM+PGM implementations, we used code provided by the authors of \cite{mckenna2019graphical} which was hard-coded with a query strategy for a particular set of 62876 marginal queries on the Adult dataset, which we also run on a MacBook Pro. For most experiments, we set the size of the synthetic data $n' = 1000$ --- significantly smaller than $n$ for both of our datasets (see Table \ref{tab:datasets}). See Appendix \ref{sec:extraplots} for an investigation of performance as a function of $n'$. For the remaining hyperparameters $K$ and $T$, we optimize over a small grid of values (see Table~\ref{tab:hyperparams}) and report the combination with the smallest error. This is also how error is reported for FEM. For all experiments we optimize over $\mathcal{X}^r = [-1,1]^{d'}$, which empirically had better convergence rates compared to using $\mathcal{X}^r = [0,1]^{d'}$ --- likely because gradients of our queries vanish at $0$. \subsection{Selecting Marginals} For our main set of experiments comparing to the FEM algorithm of \cite{Vietri2019NewOA}, we mirror their experimental design in \cite{Vietri2019NewOA}, and given $k$, we select a number of marginals $S$ (i.e., subsets of categorical features), referred to as the {\it workload}, at random, and then enumerate all queries consistent with the selected marginals (i.e., we enumerate all $y \in \prod_{i \in S} \mathcal{X}_i$). For each experiment, we fix the query selection process and random seed so that both algorithms in our comparisons are evaluated on exactly the same set of queries. See Fig.~\ref{fig:queries} in Appendix \ref{sec:extraplots} for the total number of selected queries across different workloads on both of our datasets, which vary in a range between $10^5$ and $10^8$. For our comparison to the HDMM variants of \cite{mckenna2019graphical}, we compare on the particular set of 62876 3-way marginal queries on Adult for which the hard-coded query strategy in their provided code is optimized on. \subsection{Experimental Results} We evaluate both our algorithm and FEM on the two datasets used by \cite{Vietri2019NewOA} in their evaluation: ADULT and LOANS ~\cite{Dua2019}. Just as in~\cite{Vietri2019NewOA}, both datasets are transformed so that all features are categorical --- real valued features are first bucketed into a finite number of categories. The algorithms are then run on a one-hot encoding of the discrete features, as we described in Section \ref{sec:relax}. To ensure consistency, we use the pre-processed data exactly as it appears in their repository for \cite{Vietri2019NewOA}. See Table~\ref{tab:datasets} for a summary of the datasets. \begin{table} \centering {\begin{tabular}{cccc} Dataset & Records & Features & Transformed Binary Features\\ \hline ADULT & 48842 & 15 & 588 \\ LOANS & 42535 & 48 & 4427 \\ \end{tabular}} \caption{Datasets. Each dataset starts with the given number of original (categorical and real valued) features. After our transformation, it is encoded as a dataset with a larger number of binary features.} \label{tab:datasets} \end{table} \begin{table} \centering {\begin{tabular}{ccc} Parameter & Description & Values \\ \hline $K$ & Queries per round & 5 10 25 50 100\\ $T$ & Number of iterations & 2 5 10 25 50\\ \end{tabular}} \caption{RAP hyperparameters tested in our experiments} \label{tab:hyperparams} \end{table} We mirror the evaluation in \cite{Vietri2019NewOA} and focus our experiments comparing to FEM on answering 3-way and 5-way marginals. We also compare to the High Dimensional Matrix Mechanism (HDMM) with Local Least Squares (HDMM+LLS) and Probabilistic Graphical Model (HDMM+PGM) inference from \cite{mckenna2019graphical}, but these mechanisms do not scale to large workloads, and the existing implementations are hard-coded with optimizations for a fixed set of queries on Adult. Hence in our comparison to HDMM+LSS and HDMM+PGM, we can only run these algorithms on the fixed set of 62876 3-way marginals defined on the Adult dataset that the code supports. We use the maximum error between answers to queries on the synthetic data and the correct answers on the real data across queries ($\max_i | q_i(D’) - q_i(D) |$) as a performance measure. For calibration, we also report a naive baseline corresponding to the error obtained by answering every query with ``0''. Error above this naive baseline is uninteresting. For all experiments, we fix the privacy parameter $\delta$ to $\frac{1}{n^2}$, where $n$ is the number of records in the dataset, and vary $\epsilon$ as reported. \begin{figure}[t] \center \subfloat[][\small{ADULT dataset on 3-way marginals}]{\includegraphics[width=.488\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{gumbel_plots/ADULT3_max_error_eps.png}} \hfill \subfloat[][\small{LOANS dataset on 3-way marginals} ]{\includegraphics[width=.488\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{gumbel_plots/LOANS3_max_error_eps.png}} \\ \subfloat[][\small{ADULT dataset on 5-way marginals} ]{\includegraphics[width=.488\columnwidth]{gumbel_plots/ADULT5_max_error_eps.png}} \hfill \subfloat[][\small{LOANS dataset on 5-way marginals} ]{\includegraphics[width=.488\columnwidth]{gumbel_plots/LOANS5_max_error_eps.png}} \caption{Max-error for 3 and 5-way marginal queries on different privacy levels. The number of marginals is fixed at 64.} \label{fig:epsilons} \end{figure} In Figs.~\ref{fig:epsilons}-\ref{fig:amalgam}(a) we show how our performance scales with the privacy budget $\epsilon$ for a fixed number of marginals. Figs.~\ref{fig:workloads},~\ref{fig:workloads0_05} show our performance for a fixed privacy budget as we increase the number of marginals being preserved. We significantly outperform FEM in all comparisons considered, and performance is particularly strong in the important high-privacy and high workload regimes (i.e., when $\epsilon$ is small and $m$ is large). However, both HDMM+PGM and HDMM+LLS outperform RAP in the small workload regime in the comparison we are able to run. \begin{figure}[h!] \center \subfloat[][\small{ADULT dataset on 3-way marginals}]{\includegraphics[width=.488\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{gumbel_plots/ADULT3_max_error_eps0_1.png}} \hfill \subfloat[][\small{LOANS dataset on 3-way marginals} ]{\includegraphics[width=.488\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{gumbel_plots/LOANS3_max_error_eps0_1.png}} \\ \subfloat[][\small{ADULT dataset on 5-way marginals} ]{\includegraphics[width=.488\columnwidth]{gumbel_plots/ADULT5_max_error_eps0_1.png}} \hfill \subfloat[][\small{LOANS dataset on 5-way marginals} ]{\includegraphics[width=.488\columnwidth]{gumbel_plots/LOANS5_max_error_eps0_1.png}} \caption{Max error for increasing number of 3 and 5-way marginal queries with $\epsilon = 0.1$} \label{fig:workloads} \end{figure} \begin{figure}[h!] \center \subfloat[][\small{ADULT dataset on 3-way marginals}]{\includegraphics[width=.488\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{gumbel_plots/ADULT3_max_error_eps0_05.png}} \hfill \subfloat[][\small{LOANS dataset on 3-way marginals} ]{\includegraphics[width=.488\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{gumbel_plots/LOANS3_max_error_eps0_05.png}} \\ \subfloat[][\small{ADULT dataset on 5-way marginals} ]{\includegraphics[width=.488\columnwidth]{gumbel_plots/ADULT5_max_error_eps0_05.png}} \hfill \subfloat[][\small{LOANS dataset on 5-way marginals} ]{\includegraphics[width=.488\columnwidth]{gumbel_plots/LOANS5_max_error_eps0_05.png}} \caption{Max error for increasing number of 3 and 5-way marginal queries with $\epsilon=0.05$} \label{fig:workloads0_05} \end{figure} \begin{figure}[h!] \center \subfloat[][\small{}]{\includegraphics[width=.488\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{gumbel_plots/hdmm_pgm_max.png}} \hfill \subfloat[][\small{} ]{\includegraphics[width=.488\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{gumbel_plots/rand_sampling_error.png}} \caption{(a):Max-error of HDMM variants and RAP for the set of 15 3-way marginal queries on ADULT provided by \cite{mckenna2019graphical} at different privacy levels. (b) Max Error of RAP before and after randomized rounding with different levels of oversampling.} \label{fig:amalgam} \end{figure} Figure~\ref{fig:amalgam} (b) shows how randomized rounding, when applied on the synthetic dataset generated by RAP and SparseMax, affects the error on the marginals for different levels of oversampling. The error after randomly rounding each data point $5$ times (obtaining a synthetic dataset of size $n' = 5,000$) approaches the error before applying randomized rounding and slowly converges for larger oversampling rates. We also investigate the run-time and accuracy of our algorithm as a function of the synthetic dataset size $n'$ --- see Figure \ref{fig:runtimesmall}, and Appendix \ref{sec:extraplots} for more details. Here we note two things: (i) We can take $n'$ quite small as a function of the true dataset size $n$, until a certain point (below $n' = 1000$) at which point error starts increasing, (ii) Run time also decreases with $n'$, until we take $n'$ quite small, at which point the optimization problem appears to become more difficult. Finally, as we have noted already, an advantage of our approach is its easy extensibility: to operate on a new query class, it is sufficient to write the code to evaluate queries in that class. To demonstrate this, in the Appendix we plot results for a different query class: linear threshold functions. \begin{figure}[t] \center \subfloat[][]{\includegraphics[width=.5\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{marginal_figs/stacked_log_scale.png}} \subfloat[][]{\includegraphics[width=.5\columnwidth,trim={0.5cm 0.5cm 0.5cm 0.5cm}]{marginal_figs/stacked_log_scale_running_time.png}} \caption{(a) Error and (b) run-time as a function of the synthetic dataset size $n'$.} \label{fig:runtimesmall} \end{figure} \section{Private Training Algorithms} \label{sec:privtrain} The objective of a GAN is to solve the following min-max problem: \begin{align*} \min_G \max_D \E_{x \sim p_X}[f(D(x))] + \E_{z \sim p_z} [f (1 - D(G(z)))]. \end{align*} Here, $p_X$ denotes the data distribution and $p_z$ denotes a noise distribution; the function spaces for $G$ and $D$ are typically parameterized neural nets. The {\it measuring function} $f(x)$ is $\log(x)$ in the case of traditional GANs, corresponding to Jensen-Shannon divergence for the objective, and $x$ for Wasserstein GANs, corresponding to earth mover distance (which are our focus). We are interested in training GANs subject to differential privacy. \begin{definition} A randomized algorithm $\mathcal{A} : \mathcal{X}^n \rightarrow \mathcal{R}$ with output domain $\mathcal{R}$ is $(\epsilon, \delta)$-differentially private (DP) if for all adjacent datasets $X, X' \in \mathcal{X}^n$ and for all $S \subseteq \mathcal{R}$: $P(\A(X) \in S) \leq e^{\epsilon} P(\A(X') \in S) + \delta$. \end{definition} \subsection{Private Gradient Estimation} GANs can be particulary sensitive to the choice of training algorithm, and in some cases we may be able to improve over differentially private Stochastic Gradient Descent by using a different update method. In DPSGD, gradients for each sample are clipped before aggregating into a minibatch step, which is then perturbed with Gaussian noise. We consider a similar ``privatization'' of other commonly used algorithms such as Adam, Adagrad, RMSprop, and {\it optimistic} descent algorithms (the latter are discussed in \Cref{sec:optimistic}), where we replace the gradient estimation step with that in \cite{Abadi_2016}. We prove that each of these methods results in a GAN which satisfies differential privacy. \begin{thm}\label{thm:privdescent} Any training algorithm for the discriminator which computes a gradient estimate each round using clipping and Gaussian noise, and uses an arbitrary (possibly adaptively selected) combination of historical gradient estimates to make updates, satisfies the same privacy guarantee as DPSGD. \end{thm} \subsection{Optimistic Methods and Last-Iterate Convergence} \label{sec:optimistic} GANs are attempting to find an equilibrium of a zero-sum game. While many algorithms, including gradient descent, converge in zero-sum games when taking the average of action sequences (see e.g.\ \cite{cesabianchilugosi}), for GANs we typically aim to use a fixed network (often the final step), and so this theory does not apply even in the convex-concave setting . In \cite{daskalakis2017training}, {\it optimistic gradient descent} is shown to have last-iterate convergence when used in bilinear games, and is proposed as a method for training GANs for this reason. Extensive experimentation is also conducted with an optimistic variant of Adam, which they show often outperforms other methods. In standard training via stochastic gradient descent, the two players update their weights as follows: \begin{align*} w_{t+1} =&\; w_{t} + \eta \cdot \hat{\nabla}_{w,t} \\ \theta_{t+1} =&\; \theta_{t} - \eta \cdot \hat{\nabla}_{\theta,t} \end{align*} Optimistic SGD uses the following update rule: \begin{align*} w_{t+1} =&\; w_{t} + 2 \eta \cdot \hat{\nabla}_{w,t} - \eta \cdot \hat{\nabla}_{w,t-1} \\ \theta_{t+1} =&\; \theta_{t} - 2 \eta \cdot \hat{\nabla}_{w,t} + \eta \cdot \hat{\nabla}_{w,t-1} \end{align*} Optimistic Adam replaces $\hat{\nabla}$ with the standard Adam update, and our private variants replace these gradient estimates with their clipped and perturbed analogues. The theory of last-iterate convergence has been extended to handle stochastic updates and even to settings which are not convex-concave. If we have an {\it a priori} bound on the norm of the gradients during training, and the game satisfies we can take Theorem 4.3 in \cite{mertikopoulos2018optimistic} to imply that Optimistic SGD with a decaying learning rate will converge to a saddle point, provided that that the function satisfies a property called {\it coherence}, which includes many non-convex-concave games. Beyond goals of protecting sensitive data, private GANs also have benefits in preventing overfitting by memorization. A folklore theorem in the theory of differential privacy is that private learning algorithms cannot overfit, as a result of leave-one-out stability. The implication of this for training GANs is discussed in \cite{wu2019generalization}, but they do not conduct experiments involving private training. \fi \iffalse An alternate approach for private synthetic data generation, given an original dataset $D \in. R^{d \times n}$ is to aim to approximately preserve a set of functions $\Ff$ on the dataset in hopes that these functions capture important features for downstream analysis (in the form of an explicit dataset rather than a list of queries). We show a method for achieving this, given access to an oracle for non-convex optimization. First we recall the Laplace mechanism from \cite{Dwork2006CalibratingNT}, a key ingredient in this approach. \wb{replace w Gaussian} \subsection{The Laplace Mechanism} The Laplace mechanism, introduced in \cite{Dwork2006CalibratingNT}, allows accurate private computation of statistics $f$ on a dataset when each $f$ is not too sensitive to changes in a single entry. \begin{definition}[$\ell_1$-Sensitivity] The $\ell_1$ sensitivity of a function $f: \N^{\abs{\X}} \rightarrow \R^k$ is: \begin{align*} \Delta f =&\; \max_{x, y \in \N^{\abs{\X}}, \norm{x-y}_1 = 1} \norm{f(x) - f(y)}_1. \end{align*} If we think of $f$ as a query to a dataset, this captures the maximum amount that the output of the query can change as a result of changing a single person's entry. \end{definition} The extent to which we can accurately answer queries subject to differential privacy depends on the sensitivity of the queries we care about. \iffalse \begin{definition}[Laplace Distribution] The Laplace Distribution (centered at 0) with scale parameter $b$ is the distribution with probability density function: \begin{align*} \text{Lap}(x|b) =&\; \frac{1}{2b}\exp{(-\frac{\abs{x}}{b})}. \end{align*} The variance of this distribution is $\sigma^2 = 2b^2$ We can refer to a random variable sampled from this as $Y \sim \text{Lap}(b)$. If you've seen the exponential distribution before, this is a symmetric version of it. \end{definition} \fi \begin{definition}[Laplace Mechanism] Given any function $f: \N^{\abs{\X}} \rightarrow \R^k$, the Laplace mechanism is defined as: \begin{align*} \M_L(x, f(\cdot), \epsilon) =&\; f(x) + (Y_1, \ldots, Y_k) \end{align*} where each $Y_i$ is drawn i.i.d from $\text{Lap}(\Delta f/\epsilon)$, with $\text{Lap}(x|b) = \frac{1}{2b}\exp{(-\frac{\abs{x}}{b})}$. \end{definition} \begin{theorem}[\cite{privacybook}] The Laplace mechanism satisfies $\epsilon$-differential privacy. \end{theorem} \begin{theorem}[\cite{privacybook}] \label{thm:lap-acc} Let $f: \N^{\abs{\X}} \rightarrow \R^k$, and let $y = \M_L(x, f(\cdot), \epsilon)$. Then for all $\delta \in (0,1]$: \begin{align*} \Pr[\norm{f(x) - y}_{\infty} \geq \ln{\big(\frac{k}{\delta}\big)}\cdot \big(\frac{\Delta f}{\epsilon}\big)] \leq&\; \delta. \end{align*} \end{theorem} \iffalse \subsection{Creating Datasets Consistent with Many Queries} Let $\Ff$ be a set of functions $f : \R^{d \times n} \rightarrow \R$, with $\abs{\Ff} = k$, with maximum sensitivity $\Delta f$. Let $\hat{\Ff} = \{ \hat{f}(D) | f \in \abs{\Ff} \}$ denote the set of function estimates computed by the Laplace mechanism on $d$. The objective for preserving answers to $f \in \Ff$ with a dataset $\D'$ in $\R^{d \times n'}$ is given by: \begin{align} \min_{D' \in \R^{d \times n'}} \max_{f \in \Ff} \abs{\hat{f}(D) - f(D') } =&\; \min_{D' \in \R^{d \times n'}} \norm{\hat{f}(D) - f(D') }_{\infty}. \label{eq:minmaxF} \end{align} If we can succeed in this optimization problem, \begin{theorem} \label{thm:dco-accuracy} Let $n' = n$, and let $\Delta f$ be the maximum sensitivity over $f \in \Ff$. Suppose we have $D'$ which is a global minimizer for \cref{eq:minmaxF}. With probability at least $1 - \delta$, we have that $\max_{f \in \Ff} \abs{{f}(D) - f(D') } \leq 2 \ln(k / \delta) \cdot (\Delta f / \epsilon)$. \end{theorem} \begin{proof} With probability $1 - \delta$, by \Cref{thm:lap-acc}, we have that $$\max_{f \in \Ff} \abs{\hat{f}(D) - f(D) } \leq \ln(k / \delta) \cdot (\Delta f / \epsilon).$$ By the existence of $D$, there must be some $D' \in \R^{d \times n}$ where $$\max_{f \in \Ff} \abs{\hat{f}(D) - f(D') } \leq \ln(k / \delta) \cdot (\Delta f / \epsilon),$$ as this holds when $D' = D$. Thus for any global minimizer $D'$, the theorem holds by the triangle inequality. \end{proof} Further, if the functions we care about are convex with respect to $D$, this optimization is tractable. \begin{theorem} \label{thm:dco-alg} If each $f \in \Ff$ is convex, and each row in $D$ has $\ell_2$ norm at most $C$, then there is an $\epsilon$-differentially private algorithm for finding a dataset $D'$ which preserves answers to each $f$ up to additive error $2 \ln(k / \delta) \cdot (\Delta f / \epsilon) + \alpha$, with probability $1 - \delta$, in time $\ppoly(n, d, C, 1/\alpha)$. \end{theorem} \begin{proof} If each $f$ is convex, then so is the maximum in \cref{eq:minmaxF}, and the domain can be bounded as a function of $C$, allowing an $\alpha$-approximate solution to be found using standard convex optimization techniques. The error bound then follows from \Cref{thm:dco-accuracy}. \end{proof} In experiments, we additionally aim to preserve classes of functions which are non-convex, incl This is hard in general, due to \cite{pcpsynthdatahard}, but we proceed using gradient descent. In particular, classes of queries we use for experiments are: \begin{itemize} \item Column means: $f_i(D) = \frac{1}{n} \norm{\cdot D e_i}_1$, where $e_i$ is the $i$th standard basis vector of length $d$. \item Column inner products: $f_{i,j} = \langle D e_i, D e_j \rangle $ \item Column correlations: $f_{i,j} = \mSigma_{i,j}$, where $\mSigma$ is the covariance matrix of $D$ \item Random projections: $[f] = D\cdot \rmW$, where $\rmW_{i,j} \sim U[-1, 1]$. \end{itemize} We also consider as an objective \begin{align*} \min_{D' \in \R^{d \times n'}} \norm{\hat{f}(D) - f(D') }_p \end{align*} for values of $p$ other than $\infty$. We use two different optimization methods for DCO: gradient descent directly on the objective, as well as simultaneous no-regret dynamics, similar to simultaneous descent as used for GANs. \wb{discuss slack parameter} \iffalse \subsection{Direct Optimization on Violations} If we can compute gradients for this objective with respect to the {\it entries} of $D'$, we can apply gradient descent directly to this objective \wb{which is not always convex...}. With $p=\infty$, the set of solutions to this optimization problem is equivalent to the set of saddle points of the zero-sum game formulation. \fi \fi \fi \section{Preliminaries} \subsection{Additional Related Work} Existing methods for generating private synthetic data generally fall into one of two categories. Some methods can generate datasets which are provably approximately consistent on large classes of queries, with modest data requirements, yet are computationally inefficient and often require exponential space. {\it Can ``oracle-efficient'' methods in [CITE] be implemented without access to the exponential mechanism?} Others can be specified to run in polynomial time, but do not come with provable guarantees and are primarily evaluated empirically. Private Generative Adversarial Networks (GANs) are a primary example of the latter... GANs Wasserstein GANs are a popular variant wherein the discriminator learns the earth mover distance between distributions \cite{arjovsky2017wasserstein}. \wb{more in Quip doc, especially in unorganized links section} \paragraph{Stability and Generalization in GANs} \paragraph{Last-Iterate Convergence} \paragraph{Private GANs} How long do we need to train for? Limit cycles problem: if the model never converges, one may need to continually train and simultaneously generate samples in order to draw from the equilibrium (and this may not even approximate the equilibrium). A common approach is to simply average the weights from many steps of training --- in theory, this only works for linear settings, but it appears to be somewhat effective in practice \cite{yazc2018unusual}. \wb{Similar kind of last-iterate guarantee for linear settings --- which works better in practice?} For non-private GANs, the only cost in training longer than usual is computational, and we may be able to afford a lack of precision in specifying the exact. However, when privacy is a concern, we must me much more cautious in specifying the length to train for in order to stay within a privacy budget. As such, we should be motivated to seek private methods for training GANs which converge to equilibrium more efficiently. Training with Gaussian DP: \cite{bu2019deep} (not specific to GANs). Mixed data types (Ankit's paper): \cite{tantipongpipat2019differentially}. Conditional GANs (generating labels): \cite{torkzadehmahani2020dpcgan}. \paragraph{Privately Answering Many Queries} \paragraph{Synthetic Data Release} \subsection{Differential Privacy} \begin{definition}[$(\epsilon,\delta)$-Differential Privacy] A mechanism $\M$ is $(\epsilon,\delta)$-differentially private... \end{definition} \subsection{Wasserstein GANs} Standard training via gradient descent: \begin{align*} w_{t+1} =&\; w_{t} + \eta \cdot \nabla_{w,t} \\ \theta_{t+1} =&\; \theta_{t} - \eta \cdot \nabla_{\theta,t} \\ \end{align*} \input{privdescent} \subsection{Optimistic Mirror Descent} Training WGANs with Optimistic Mirror Descent: \begin{align*} w_{t+1} =&\; w_{t} + 2\eta \cdot \nabla_{w,t} - \eta \cdot \nabla_{w,t-1} \\ \theta_{t+1} =&\; \theta_{t} - 2\eta \cdot \nabla_{\theta,t} + \eta \cdot \nabla_{\theta,t-1} \end{align*} In the case of a zero-sum bilinear game given by a matrix $A$, this looks like: \begin{align*} x_{t} =&\; x_{t-1} - 2\eta Ay_{t-1} + \eta Ay_{t-2} \\ y_{t} =&\; y_{t-1} + 2\eta A^T x_{t-1} - \eta \A^T x_{t-2} \end{align*} In \cite{daskalakis2017training}, it is shown in Theorem 1 that in this setting, $(x_t, y_t)$ approaches an equiilbrium as $t \rightarrow \infty$. \subsection{Private Descent Methods} \subsection{Private OMD} \begin{algorithm} \caption{Private Optimistic Mirror Descent} \label{alg1} \begin{algorithmic} \Input{} \State {\bf Initialize }$ \theta_0 \Leftarrow ...$ \For{$t \in [T]$} \State Take a random sample $L_t$ \State {\bf Compute gradient} \State \State {\bf Clip gradient} \State \State {\bf Descent} \State \EndFor \Output{} \end{algorithmic} \end{algorithm} \begin{theorem} ... satisfies $(\epsilon, \delta)$-differential privacy ... \end{theorem} \subsubsection{Last-Iterate Convergence in Bilinear Games} Does the last-iterate convergence result from \cite{daskalakis2017training} hold when gradient estimates are stochastic but unbiased? If this holds for appropriate noise distributions, then perhaps we can tell a story about last-iterate convergence in a toy GAN game which is linear but allows for a meaningful interpretation of privacy and subsampling for SGD. I'm still parsing the proof of Theorem 1 in \cite{daskalakis2017training}. My intuition is that we'd have to very carefully define a distribution over gradient estimates for everything to go through --- we'd need several statements of equality in expected value to hold for iterated matrix products. One idea is if each entry in $A$ is drawn independently for constructing updates $A^T x_t$ and $A y_t$. But I'm not sure what the story about this would be. If we think obtaining a theorem of this form would be a valuable part of a paper, I'd want to spend more time playing around with it to develop deeper intuition for what's going on. \subsection{Privacy Analysis} \section{Preliminaries} \label{sec:prelims} \subsection{Statistical Queries and Synthetic Data} Let $\mathcal{X}$ be a data domain. In this paper, we will focus on data points containing $d$ categorical features: i.e. $\mathcal{X} = \mathcal{X}_1 \times \ldots \times \mathcal{X}_d$, where each $\mathcal{X}_i$ is a set of $t_i$ categories. A \emph{dataset} (which we will denote by $D$) consists of a multiset of $n$ points from $\mathcal{X}$: $D \in \mathcal{X}^n$. \begin{definition}[Statistical Query \cite{SQ}] A \emph{statistical query} (also known as a \emph{linear query} or \emph{counting query}) is defined by a function $q_i:\mathcal{X} \rightarrow [0,1]$. Given a dataset $D$, we will abuse notation and write $q_i(D)$ to denote the average value of the function $q_i$ on $D$: $$q_i(D) = \frac{1}{n}\sum_{x \in D} q_i(x)$$ Given a collection of $m$ statistical queries $\{q_i\}_{i=1}^m$, we write $q(D) \in [0,1]^m$ to denote the vector of values $q(D) = (q_1(D),\ldots,q_m(D))$. \end{definition} An important type of statistical query is a $k$-way marginal, which counts the number of data points $x \in D$ that have a particular realization of feature values for some subset of $k$ features.\footnote{We define marginals for datasets with discrete features. In our experimental results we encode continuous features as discrete by standard binning techniques.} \begin{definition} A $k$-way marginal query is defined by a subset $S \subseteq [d]$ of $|S| = k$ features, together with a particular value for each of the features $y \in \prod_{i \in S} \mathcal{X}_i$. Given such a pair $(S, y)$, let $\mathcal{X}(S,y) = \{x \in \mathcal{X} : x_i = y_i\ \ \forall i \in S\}$ denote the set of points that match the feature value $y_i$ for each of the $k$ features in $S$. The corresponding statistical query $q_{S,y}$ is defined as: $$q_{S,y}(x) = \mathbbm{1}(x \in \mathcal{X}(S,y))$$ Observe that for each collection of features (\emph{marginal}) $S$, there are $\prod_{i \in S}|\mathcal{X}_i|$ many queries. \end{definition} Given a set of $m$ statistical queries $q$, we will be interested in vectors of answers $a' \in [0,1]^m$ that represent their answers on $D$ \emph{accurately}: \begin{definition} Given a dataset $D$, a collection of $m$ statistical queries represented as $q:\mathcal{X}^n\rightarrow [0,1]^m$, and a vector of estimated answers $a' \in [0,1]^m$, we say that $a'$ has $\ell_\infty$ or \emph{max} error $\alpha$ if $\max_{i \in [m]} |q_i(D)-a'_i| \leq \alpha$. \end{definition} In this paper we will represent vectors of estimated answers $a'$ \emph{implicitly} using some data structure $D'$ on which we can evaluate queries, and will write $q(D')$ for $a'$. If $D' \in \mathcal{X}^*$, then we refer to $D'$ as a \emph{synthetic dataset} --- but we will also make use of $D'$ lying in continuous relaxations of $\mathcal{X}^n$ (and will define how query evaluation applies to such ``relaxed datasets''). \subsection{Differential Privacy} Two datasets $D, D' \in \mathcal{X}^n$ are said to be \emph{neighboring} if they differ in at most one data point. We will be interested in \emph{randomized algorithms} $\mathcal{A}:\mathcal{X}^n\rightarrow R$ (where $R$ can be an arbitrary range). \begin{definition}[Differential Privacy \cite{Dwork2006CalibratingNT,delta}] A randomized algorithm $\mathcal{A}:\mathcal{X}^n\rightarrow R$ is $(\epsilon,\delta)$ differentially private if for all pairs of neighboring datasets $D, D' \in \mathcal{X}^n$ and for all measurable $S \subseteq R$: $$\Pr[\mathcal{A}(D) \in S] \leq \exp(\epsilon)\Pr[\mathcal{A}(D') \in S] + \delta.$$ If $\delta = 0$ we say that $\mathcal{A}$ is $\epsilon$-differentially private. \end{definition} Differential privacy is not convenient for tightly handling the degradation of parameters under composition, and so as a tool for our analysis, we use the related notion of (zero) Concentrated Differential Privacy: \begin{definition}[Zero Concentrated Differential Privacy \cite{zCDP}] An algorithm $\mathcal{A}:\mathcal{X}^n\rightarrow R$ satisfies $\rho$-zero Concentrated Differential Privacy (zCDP) if for all pairs of neighboring datasets $D, D' \in \mathcal{X}^n$, and for all $\alpha \in (0,\infty)$: $$\mathbb{D}_\alpha(\mathcal{A}(D),\mathcal{A}(D')) \leq \rho \alpha$$ where $\mathbb{D}_\alpha(\mathcal{A}(D),\mathcal{A}(D'))$ denotes the $\alpha$-Renyi divergence between the distributions $\mathcal{A}(D)$ and $\mathcal{A}(D')$. \end{definition} zCDP enjoys clean composition and postprocessing properties: \begin{lemma}[Composition \cite{zCDP}] \label{lem:composition} Let $\mathcal{A}_1:\mathcal{X}^n\rightarrow R_1$ be $\rho_1$-zCDP. Let $\mathcal{A}_2:\mathcal{X}^n\times R_1 \rightarrow R_2$ be such that $\mathcal{A}_2(\cdot, r)$ is $\rho_2$-zCDP for every $r \in R_1$. Then the algorithm $\mathcal{A}(D)$ that computes $r_1 = \mathcal{A}_1(D)$, $r_2 = \mathcal{A}_2(D,r_1)$ and outputs $(r_1,r_2)$ satisfies $(\rho_1+\rho_2)$-zCDP. \end{lemma} \begin{lemma}[Post Processing \cite{zCDP}] \label{lem:post} Let $\mathcal{A}:\mathcal{X}^n \rightarrow R_1$ be $\rho$-zCDP, and let $f:R_1 \rightarrow R_2$ be an arbitrary randomized mapping. Then $f \circ \mathcal{A}$ is also $\rho$-zCDP. \end{lemma} Together, these lemmas mean that we can construct zCDP mechanisms by modularly combining zCDP sub-routines. Finally, we can relate differential privacy with zCDP: \begin{lemma}[Conversions \cite{zCDP}]\ \label{lem:conversion} \begin{enumerate} \item If $\mathcal{A}$ is $\epsilon$-differentially private, it satisfies $(\frac{1}{2}\epsilon^2)$-zCDP. \item If $\mathcal{A}$ is $\rho$-zCDP, then for any $\delta > 0$, it satisfies $(\rho + 2\sqrt{\rho\log(1/\delta)},\delta)$-differential privacy. \end{enumerate} \end{lemma} We will make use of two basic primitives from differential privacy, which we introduce here in the context of statistical queries. The first is the Gaussian mechanism. \begin{definition}[Gaussian Mechanism] The Gaussian mechanism $G(D,q_i,\rho)$ takes as input a dataset $D \in \mathcal{X}^n$, a statistical query $q_i$, and a zCDP parameter $\rho$. It outputs $a_i = q_i(D) + Z$, where $Z \sim N(0,\sigma^2)$, where $N(0,\sigma^2)$ is the Gaussian distribution with mean $0$ and variance $\sigma^2 = \frac{1}{2 n^2 \rho}$. \end{definition} \begin{lemma}[\cite{zCDP}] \label{lem:gaussian} For any statistical query $q_i$ and parameter $\rho > 0$, the Gaussian mechanism $G(\cdot,q_i,\rho)$ satisfies $\rho$-zCDP. \end{lemma} The second is a simple private ``selection'' mechanism called report noisy max --- we define a special case here, tailored to our use of it. \begin{definition}[Report Noisy Max With Gumbel Noise] \label{def:RNM} The ``Report Noisy Max'' mechanism $RNM(D,q,a,\rho)$ takes as input a dataset $D \in \mathcal{X}^n$, a vector of $m$ statistical queries $q$, a vector of $m$ conjectured query answers $a$, and a zCDP parameter $\rho$. It outputs the index of the query with highest noisy error estimate. Specifically, it outputs $i^* = \arg\max_{i \in [m]}(|q_i(D) - a_i| + Z_i)$ where each $Z_i \sim \mathrm{Gumbel}\left(1/\sqrt{2\rho}n \right)$. \end{definition} \begin{lemma} \label{lem:RNM} For any vector of statistical queries $q$, vector of conjectured answers $a$, and zCDP parameter $\rho$, $RNM(\cdot,q,a,\rho)$ satisfies $\rho$-zCDP. \end{lemma} \begin{proof} The report noisy max mechanism with Gumbel noise is equivalent to the exponential mechanism for sensitivity 1/n queries, and hence satisfies the bounded range property as defined in \cite{BR1}. Lemma 3.2 of \cite{BR2} converts bounded range guarantees to zCDP guarantees, from which the claim follows. \end{proof} \subsection{Missing Proofs} \subsection{Hyperparameters and Architectures}\label{architecture} \begin{figure}[h] \includegraphics[width=0.5\textwidth]{figs/diagram.png} \caption{GAN Architecture for ADULT dataset experiments} \end{figure} \section{The Relaxed Adaptive Projection (RAP) Mechanism} We here introduce the ``Relaxed Adaptive Projection'' (RAP) mechanism (Algorithm \ref{alg:main}), which has three hyper-parameters: the \emph{number of adaptive rounds} $T$, the \emph{number of queries per round} $K$, and the \emph{size of the (relaxed) synthetic dataset} $n'$. In the simplest case, when $T = 1$ and $K = m$, we recover the natural relaxation of the projection mechanism: \begin{enumerate} \item We evaluate each query $q_i \in Q$ on $D$ using the Gaussian mechanism to obtain a noisy answer $\hat a_i$, and \item Find a \emph{relaxed} synthetic dataset $D' \in X^r$ whose equivalent extended differentiable query values are closest to $\hat a$ in $\ell_2$ norm: $D' = \arg\min_{D' \in (\mathcal{X}^r)^{n'}}||\hat q(D') - \hat a||_2$. \end{enumerate} Because step 2 is now optimizing a continuous, differentiable function over a continuous space (of dimension $d' \cdot n'$, we can use existing tool kits for performing the optimization -- for example, we can use auto-differentiation tools, and optimizers like Adam~\cite{kingma2015adam}. (Recall that the projection is a post-processing of the Gaussian mechanism, and so the privacy properties of the algorithm are independent of our choice of optimizer). Here $n'$ is a hyperparameter that we can choose to trade off the expressivity of the synthetic data with the running-time of the optimization: If we choose $n' = n$, then we are assured that it is possible to express $D$ exactly in our relaxed domain: as we choose smaller values of $n'$, we introduce a source of representation error, but decrease the dimensionality of the optimization problem in our projection step, and hence improve the run-time of the algorithm. In this simple case, we can recover an accuracy theorem by leveraging the results of \cite{projection}: \begin{theorem} Fix privacy parameters $\epsilon,\delta > 0$, a synthetic dataset size $n'$, and any set of $m$ $k$-way product queries $q$. If the minimization in the projection step is solved exactly, then the average error for the RAP mechanism when $T = 1$ and $K = m$ can be bounded as: $$\sqrt{\frac{1}{m}||q(D) - q(D')||_2^2} \leq$$$$ O\left(\frac{(d'(\log k + \log n')+\log(1/\beta)\ln(1/\delta))^{1/4}}{\sqrt{\epsilon n}} + \frac{\sqrt{\log k}}{\sqrt{n'}} \right)$$ with probability $1-\beta$ over the realization of the Gaussian noise. \label{thm:accuracy_theorem} \end{theorem} See Appendix \ref{sec:proof_accuracy_theorem} for proof. This is an ``oracle efficient'' accuracy theorem in the style of \cite{dualquery,Vietri2019NewOA,oraclenonconvex} in the sense that it assumes that our heuristic optimization succeeds (note that this assumption is not needed for the privacy of our algorithm, which we establish in Theorem \ref{thm:privacy}). Compared to the accuracy theorem for the FEM algorithm proven in \cite{Vietri2019NewOA}, our theorem improves by a factor of $\sqrt{d'}$. In the general case, our algorithm runs in $T$ rounds: After each round $t$, we have answered some \emph{subset} of the queries $Q_S \subseteq Q$, and perform a projection only with respect to the queries in $Q_S$ for which we have estimates, obtaining an intermediate relaxed synthetic dataset $D_t'$. At the next round, we augment $Q_S$ with $K$ additional queries $q_i$ from $Q \setminus Q_S$ chosen (using report noisy max) to maximize the disparity $|q_i(D_t') - q_i(D)|$. We then repeat the projection. In total, this algorithm only explicitly answers $T\cdot K$ queries, which might be $\ll m$. But by selectively answering queries for which the consistency constraints imposed by the projection with respect to previous queries have not correctly fixed, we aim to expend our privacy budget more wisely. Adaptively answering a small number of ``hard'' queries has its roots in a long theoretical line of work \cite{RR10,HR10,GRU12}. \begin{algorithm}[h] \caption{Relaxed Projection (RP)} \label{alg:proj} \begin{algorithmic} \STATE {\bfseries Input:} A vector of differentiable queries $q:\mathcal{X}^r\rightarrow \mathbb{R}^{m'}$, a vector of target answers $\hat a \in \mathbb{R}^{m'}$, and an initial dataset $D' \in (\mathcal{X}^r)^{n'}$. \STATE Use any differentiable optimization technique (Stochastic Gradient Descent, Adam, etc.) to attempt to find: $$D_S = \arg\min_{D' \in (\mathcal{X}^r)^{n'}} ||q(D') - \hat a||_2^2$$ \STATE Output $D_S$. \end{algorithmic} \end{algorithm} \begin{algorithm}[h] \caption{Relaxed Adaptive Projection (RAP)} \label{alg:main} \begin{algorithmic} \STATE {\bfseries Input:} A dataset $D$, a collection of $m$ statistical queries $Q$, a ``queries per round'' parameter $K \leq m$, a ``number of iterations'' parameter $T \leq m/K$, a synthetic dataset size $n'$, and differential privacy parameters $\epsilon,\delta$. \STATE Let $\rho$ be such that: $$\epsilon = \rho + 2\sqrt{\rho\log(1/\delta)}$$ \IF{$T = 1$} \FOR{$i = 1$ to $m$} \STATE Let $\hat a_i = G(D,q_i,\rho/m)$. \ENDFOR \STATE Randomly initialize $D' \in (\mathcal{X}^r)^{n'}$. \STATE Output $D'= RP(q, \hat a, D')$. \ELSE \STATE Let $Q_S = \emptyset$ and $D'_0 \in (\mathcal{X}^r)^{n'}$ be an arbitrary initialization. \FOR{$t = 1$ to $T$} \FOR{$k = 1$ to $K$} \STATE Define $\hat q^{Q \setminus Q_S}(x) = (\hat q_i(x) : q_i \in Q \setminus Q_S)$ where $\hat q_i$ is an equivalent extended differentiable query for $q_i$. \STATE Let $q_i = RNM(D,\hat q^{Q \setminus Q_S},\hat q^{Q \setminus Q_S}(D'_{t-1}),\frac{\rho}{2T\cdot K})$. \STATE Let $Q_S = Q_S \cup \{q_i\}$. \STATE Let $\hat a_i = G(D,q_i,\frac{\rho}{2T\cdot K})$. \ENDFOR \STATE Define $q^{Q_S}(x) = (q_i(x) : q_i \in Q_S)$ and $\hat a = \{\hat a_i : q_i \in Q_S\}$ where $\hat q_i$ is an equivalent extended differentiable query for $q_i$. Let $D'_t = RP(q^{Q_S}, \hat a, D_{t-1}')$. \ENDFOR \STATE Output $D'_T$. \ENDIF \end{algorithmic} \end{algorithm} \begin{theorem}\label{thm:privacy} For any query class $Q$, any set of parameters $K,T,n'$, and any privacy parameters $\epsilon,\delta > 0$, the RAP mechanism $RAP(\cdot,Q,K,T,n',\epsilon,\delta)$ (Algorithm \ref{alg:main}) is $(\epsilon,\delta)$-differentially private. \end{theorem} See Appendix \ref{sec:proof_privacy} for proof. \paragraph{Randomized Rounding to Output a Synthetic Dataset} \label{sec:sparse_max_projection} We use the SparseMax~\cite{martins2016softmax} transformation to generate relaxed synthetic data in which each set of one-hot columns, corresponding to the original features, is normalized to a (sparse) probability distribution. More specifically, after each step of the optimization technique in Algorithm.~\ref{alg:proj}, we apply SparseMax independently to each set of encoded columns in the synthetic dataset $D_{S}$. Randomized rounding (i.e. for each feature independently, selecting a one-hot encoding with probability proportional to its probability in the relaxed synthetic data) can then be applied to produce a synthetic dataset consistent with the original schema. This preserves the expected value of marginal queries, and can preserve their values exactly in the limit as we take multiple samples. As we show in our experiments, preserving the worst case error over many marginals requires only moderate oversampling in practice (5 samples per data point).
{'timestamp': '2021-06-24T02:23:04', 'yymm': '2103', 'arxiv_id': '2103.06641', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06641'}
arxiv
\section{Introduction} With the technological advances seen in recent years, functional data sets are increasingly multivariate. They can be multivariate with respect to the domain of a function, its codomain, or both. Here, we focus on multivariate functions with a one-dimensional domain $\bm{f} = (f^{(1)},..., f^{(D)}) \colon \mathcal{I} \subset \mathbb{R} \to \mathbb{R}^{D}$ with square-integrable components $f^{(d)} \in L^2(\mathcal{I}), d = 1,..., D$. For this type of data, we can distinguish two subclasses: One has interpretable separate dimensions and can be seen as several complementary modes of a common phenomenon \citep[``multimodal'' data, cf.~][]{uludaug2014general} as in the analysis of acoustic signals and articulation processes in speech production in one of our data examples. The codomain then simply is the Cartesian product $\mathcal{S} = \mathcal{S}^{(1)} \times ... \times \mathcal{S}^{(D)}$ of interpretable univariate codomains $\mathcal{S}^{(d)} \subset \mathbb{R}$. The other subclass is more ``intrinsically'' multivariate insofar as univariate analyses would not yield meaningful results. Consider for example two-dimensional movement trajectories as in one of our motivating applications, where the function measures Cartesian coordinates over time: for fixed trajectories, rotation or translation of the essentially arbitrary coordinate system would change the results of univariate analyses. For intrinsically multivariate functional data a multivariate approach is the natural and preferred mode of analysis, yielding interpretable results on the observation level. Even for multimodal functional data, a joint analysis may generate additional insight by incorporating the covariance structure between the dimensions. This motivates the development of statistical methods for multivariate functional data. We here propose multivariate functional additive mixed models to model potentially sparsely observed functions with flexible covariate effects and crossed or nested study designs. Multivariate functional data have been the interest in different statistical fields such as clustering \citep{jacques2014, park2017}, functional principal component analysis \citep{chiou2014, happ2018, backenroth2018, li2020}, and registration \citep{carroll2020, steyer2020}. There is also ample literature on multivariate functional data regression such as graphical models \citep{zhu2016}, reduced rank regression \citep{liu2020}, or varying coefficient models \citep{zhu2012, Li2017}. Yet, so far, there are only few approaches that can handle multilevel regression when the functional response is multivariate. In particular, \citet{goldsmith2016} propose a hierarchical Bayesian multivariate functional regression model that can include subject level and residual random effect functions to account for correlation between and within functions. They work with bivariate functional data observed on a regular and dense grid and assume \emph{a priori} independence between the different dimensions of the subject-specific random effects. Thus, they model the correlation between the dimensions only in the residual function. As our approach explicitely models the dependencies between dimensions for multiple functional random effects and also handles data observed on sparse and irregular grids on more than two dimensions, the model proposed by \citet{goldsmith2016} can be seen as a special case of our more general model class. Alternatively, \citet{zhu2017} use a two stage transformation with basis functions for the multivariate functional mixed model. This allows the estimation of scalar regression models for the resulting basis coefficients that are argued to be approximately independent. The proposed model is part of the so called \gls{fmm} framework \citep{morris2017}. While \glspl{fmm} use basis transformations of functional responses (observed on equal grids) at the start of the analysis, we propose a multivariate model in the \gls{famm} framework, which uses basis representations of all (effect) functions in the model \citep{scheipl2015}. The differences between these two functional regression frameworks have been extensively discussed before \citep{greven2017, morris2017}. The main advantages of our multivariate regression model, also compared to \citet{goldsmith2016} and \citet{zhu2017}, are that it is readily available for sparse and irregular functional data and that it allows to include multiple nested or crossed random processes, both of which are required in our data examples. Another important contribution is that our approach directly models the multivariate covariance structure of all random effects included in the model using multivariate \glspl{fpc} and thus implicitly models the covariances between the dimensions. This makes the model representation more parsimonious, avoids assumptions difficult to verify, and allows further interpretation of the random effect processes, such as their relative importance and their dominating modes. As part of the \gls{famm} framework, our model provides a vast toolkit of modeling options for covariate and random effects, of estimation and inference \citep{wood2017}. The proposed \gls{mfamm} extends the \gls{famm} framework combining ideas from multilevel modeling \citep{cederbaum2016} and multivariate functional data \citep{happ2018} to account for sparse and irregular functional data and different study designs. We illustrate the \gls{mfamm} on two motivating examples. The first (intrinsically multivariate) data stem from a study on the effect of a training programme for snooker players with a nested study design (shots within sessions within players) \citep{snooker2014}. The movement trajectories of a player's elbow, hand, and shoulder during a snooker shot are recorded on camera, yielding six-dimensional multivariate functional data (see Figure \ref{fig:snook_obs}). In the second data example, we analyse multimodal data from a speech production study with a crossed study design (speakers crossed with words) \citep{pouplier2016} on so-called ``assimilation'' of consonants. The two measured modes (acoustic and articulatory, see Figure \ref{fig:speech_obs}) are expected to be closely related but joint analyses have not yet incorporated the functional nature of the data. These two examples motivate the development of a regression model for sparse and irregularly sampled multivariate functional data that can incorporate crossed or nested functional random effects as required by the study design in addition to flexible covariate effects. The proposed approach is implemented in \texttt{R} \citep{rsoftware} in package \texttt{multifamm}\citep{multifammpackage}. The paper is structured as follows: Section \ref{sec:MultiFAMM} specifies the \gls{mfamm} and section \ref{sec:Estimation} its estimation process. Section \ref{sec:application} presents the application of the \gls{mfamm} to the data examples and section \ref{sec:simulation} shows the estimation performance of our proposed approach in simulations. Section \ref{sec:discussion} closes with a discussion and outlook. \section{Multivariate Functional Additive Mixed Model} \label{sec:MultiFAMM} \subsection{General Model} Let $\bm{y}^{*}_i(t) = (y_i^{*(1)}(t),..., y_i^{*(D)}(t))^{\top}$ be the multivariate functional response of unit $i=1,...,N$ over $t \in \mathcal{I}$, consisting of dimensions $d=1,...,D$. Without loss of generality, we assume a common one-dimensional interval domain $\mathcal{I} = [0,1]$ for all dimensions, and square-integrable $y_i^{*(d)}\in L^2(\mathcal{I})$. Define $L^2_{D}(\mathcal{I}) := L^2(\mathcal{I}) \times ...\times L^2(\mathcal{I})$ so that $\bm{y}^{*}_i\in L^2_D(\mathcal{I})$. The underlying smooth function $\bm{y}_i^{*}$, however, is only evaluated at (potentially sparse or dimension-specific) points $\bm{y}_{it}^{*} = (y_{it}^{*(1)}, ..., y_{it}^{*(D)})^{\top}$ and the evaluation is subject to white noise, i.e.\ $\bm{y}_{it} = \bm{y}_{it}^{*} + \bm{\epsilon}_{it}$. The residual term $\bm{\epsilon}_{it}$ reflects additional uncorrelated white noise measurement error, following a $D$-dimensional multivariate normal distribution $\mathcal{N}_D$ with zero-mean and diagonal covariance matrix $\tilde{\bm{\Sigma}} = \operatorname{diag}(\sigma_{1}^2, ..., \sigma_{D}^2)$ with dimension specific variances $\sigma_{d}^2$. We construct a multivariate functional mixed model as \begin{align} \label{eq:multivariateFLMM} \begin{split} \bm{y}_{it} &= \bm{y}_i^{*}(t) + \bm{\epsilon}_{it}= \bm{\mu}(\bm{x}_i, t) + \bm{U}(t)\bm{z}_i + \bm{\epsilon}_{it} \\ &= \bm{\mu}(\bm{x}_i, t) + \sum_{j=1}^q\bm{U_j}(t)\bm{z}_{ij} + \bm{E}_i(t) + \bm{\epsilon}_{it}, \quad t \in \mathcal{I}, \end{split} \end{align} where \begin{align*} \bm{U}_{j}(t) &= (\bm{U}_{j1}(t), ..., \bm{U}_{jV_{U_j}}(t)); j = 1,..., q,\\ \bm{U}_{jv}(t) &\stackrel{\text{ind.c.}}{\sim} MGP\left(\bm 0, K_{U_{j}}\right); v = 1,..., V_{U_j}; \forall j = 1,...,q, \\ \bm{E}_{i}(t) &\stackrel{\text{ind.c.}}{\sim} MGP\left(\bm 0, K_{E} \right); i = 1,..., N, \text{ and }\\ \bm{\epsilon}_{it} &\stackrel{\text{i.i.d.}}{\sim} \mathcal{N}_D\left(\bm 0, \tilde{\bm{\Sigma}} = \operatorname{diag}(\sigma_{1}^2, ..., \sigma_{D}^2)\right) ; i = 1,..., N; \quad t \in \mathcal{I}. \end{align*} We assume an additive predictor $\bm{\mu}(\bm{x}_i, \cdot) = \sum_{l = 1}^p \bm{f}_l (\bm{x}_{i}, \cdot)$ of fixed effects, which consists of partial predictors $\bm{f}_{l}(\bm{x}_{i}, \cdot) = (f_{l}^{(1)}(\bm{x}_{i}, \cdot), ..., f_{l}^{(D)}(\bm{x}_{i}, \cdot))^{\top}\in L^2_D(\mathcal{I}),\ l = 1,...,p$, that are multivariate functions depending on a subset of the vector of scalar covariates $\bm{x}_{i}$. This allows to include linear or smooth covariate effects as well as interaction effects between multiple covariates as in the univariate \gls{famm} \citep{scheipl2015}. Partial predictors may also depend on dimension specific subsets of covariates. For random effects $\bm{U}$, we focus on model scenarios with $q$ independent multivariate functional random intercepts for crossed and/or nested designs. For group level $v = 1,\dots, V_{U_j}$ within grouping layer $j=1,\dots,q$, these take the value $\bm{U}_{jv} \in L^2_D(\mathcal{I})$. For each layer, the $\bm{U}_{j1}, ..., \bm{U}_{jV_{U_j}}$ present independent copies of a multivariate smooth zero-mean Gaussian random process. Analogously to scalar linear mixed models, the $\bm{U}_{jv}$ model correlations between different response functions $\bm{y}_i^{*}$ within the same group as well as variation across groups. By arranging them in a $(D \times V_{U_j})$ matrix $\bm{U}_j(t)$ per $t$, the $j$th random intercept can be expressed in the common mixed model notation in (\ref{eq:multivariateFLMM}) using appropriate group indicators $\bm{z}_{ij} = (z_{ij1}, \dots, z_{ijV_{U_j}})^\top$ for the respective design. Although technically a curve-specific functional random intercept, we distinguish the smooth residuals $\bm{E}_i\in L^2_D(\mathcal{I})$ in the notation, as they model correlation within rather than between response functions. We write $\bm{E}_v \in L^2_D(\mathcal{I}), v = 1,..., V_E$ with $V_E = N$. The $\bm{E}_i$ capture smooth deviations from the group-specific mean $\bm{\mu}(\bm{x}_i, \cdot) + \sum_{j=1}^{q}\bm{U}_j(\cdot)\bm{z}_{ij}$. For a more compact representation, we can arrange all $\bm{U}_j(t)$ and $\bm{E}_i(t)$ together in a $(D \times (\sum_{j=1}^qV_{U_j} + N))$ matrix $\bm{U}(t)$ per $t$, and the group indicators for all layers in a corresponding vector $\bm{z}_i = (\bm{z}_{i1}^\top, \dots, \bm{z}_{iq}^\top, \boldsymbol{e}_i^\top)^\top$ with $\boldsymbol{e}_i$ the $i$-th unit vector. The resulting model term $\bm{U}(t) \bm{z}_i$ then comprises all smooth random functions, accounting for all correlation between/within response functions $\bm{y}_i^{*}$ given the covariates $\bm{x}_i$ as required by the respective experimental design. $\bm{E}_i$ and $\bm{U}_{jv}$ are independent copies (ind.\ c.) of random processes having multivariate $D\times D$ covariance kernels $K_E, K_{U_j}$, with univariate covariance surfaces $K_{E}^{(d,e)}(t, t') = \text{Cov}\left[E_i^{(d)}(t), E_i^{(e)}(t')\right]$ and $K_{U_{j}}^{(d,e)}(t, t') = \text{Cov}\left[U_{jv}^{(d)}(t), U_{jv}^{(e)}(t')\right]$ reflecting the covariance between the process dimensions $d$ and $e$ at $t$ and $t'$. We call these auto-covariances for $d = e$ and cross-covariance otherwise. The multivariate Gaussian processes are uniquely defined by their multivariate mean function, here the null function $\bf{0}$, and the multivariate covariance kernels $K_g$ and we write $MGP\left(\bm{0}, K_g\right), g \in \{U_1, \dots, U_q, E\}$. Note that vectorizing the matrix $\bm{U}(t)$ allows to formulate the joint distribution assumption $\operatorname{vec}(\bm{U}(t)) \sim MGP\left(\bm{0}, K_{U}\right)$ with $K_{U}(t, t')$ having a block-diagonal structure repeating each $K_{U_j}(t,t')$ for $V_{U_j}$ times and $K_E(t,t')$ for $N$ times. We assume that the different sources of variation $\bm{U}_j(t),j = 1,...,q, \bm{E}_i(t)$, and $\bm{\epsilon}_{it}$ are mutually uncorrelated random processes to assure model identification. Assuming smoothness of the covariance kernel $K_E$ further guarantees that the residual process $\bm{E}_i(t)$ can be separated from the white noise $\bm{\epsilon}_{it}$, removing the error variance from the diagonal of the smooth covariance kernel \citep[e.g.,][]{yao2005functional}. \subsection{FPC Representation of the Random Effects} Model \eqref{eq:multivariateFLMM} specifies a univariate \gls{flmm} as given in \citet{cederbaum2016} for each dimension $d$. The main difference lies in the multivariate random processes that introduce dependencies between the dimensions. In order to avoid restrictive assumptions about the structure of these multivariate covariance operators, which would typically be very difficult to elicit \emph{a priori} or verify \emph{ex post}, we estimate them directly from the data. The main difficulty then becomes computationally efficient estimation, which is already costly in the univariate case. Especially for higher dimensional multivariate functional data, accounting for the cross-covariances can become a complex task, which we tackle with \gls{mfpca}. Given the covariance operators (see Section \ref{sec:Estimation}), we represent the multivariate random effects in model \eqref{eq:multivariateFLMM} using truncated multivariate \gls{kl} expansions \begin{equation} \begin{aligned} \label{eq:truncated_KL_expansion} \bm{U}_{jv} (t) &\approx \sum_{m=1}^{M_{U_j}}\rho_{U_j v m}\bm{\psi}_{U_jm}(t),\; j = 1,...,q;\, v =1, ..., V_{U_j},\\ \bm{E}_v(t) &\approx \sum_{m=1}^{M_E}\rho_{Ev m}\bm{\psi}_{Em}(t), \; v = 1, ..., N, \end{aligned} \end{equation} where the orthonormal multivariate eigenfunctions $\bm{\psi}_{gm} = (\psi_{gm}^{(1)}, ..., \psi_{gm}^{(D)})^{\top}\in L^2_D(\mathcal{I})$, $m = 1,..., M_g$, $g\in\{U_1, ..., U_q, E\}$ of the corresponding covariance operators with truncation order $M_g$ are used as basis functions and the random scores $\rho_{gvm} \sim N(0, \nu_{gm})$ are \gls{iid} with ordered eigenvalues $\nu_{gm}$ of the corresponding covariance operator. Note that the assumption of Gaussianity for the random processes can be relaxed. For non-Gaussian random processes, the \gls{kl} expansion still gives uncorrelated (but non-normal) scores and estimation based on a \gls{pls} criterion (see Section \ref{subsec:FAMM}) remains reasonable. Using \gls{kl} expansions gives a parsimonious representation of the multivariate random processes that is an optimal approximation with respect to the integrated squared error \citep[cf.][]{ramsay2005}, as well as interpretable basis functions capturing the most prominent modes of variation of the respective process. The distinct feature of this approach is that the multivariate \glspl{fpc} directly account for the dependency structure of each random process across the dimensions. If, by contrast, e.g.\ splines were used in the basis representation of the random effects, it would be necessary to explicitly model the cross-covariances of each random process in the model \citep[cf.][]{li2020}. Multivariate eigenfunctions, however, are designed to incorporate the dependency structure between dimensions and allow the assumption of independent (univariate) basis coefficients $\rho_{gvm}$ via the \gls{kl} theorem \citep[see e.g.~][]{happ2018}. This leads to a parsimonious multivariate basis for the random effects, where a typically small vector of scalar scores $\rho_{gvm}$ common to all dimensions represents nearly the entire information about these $D$-dimensional processes. \section{Estimation} \label{sec:Estimation} We use a two-step approach to estimate the \gls{mfamm} and the respective multivariate covariance operators. In a first step (section \ref{subsec:EigenfunctionEstimation}), the D-dimensional eigenfunctions $\bm{\psi}_{gm}(t)$ with their corresponding eigenvalues $\nu_{gm}$ are estimated from their univariate counterparts following \citet{cederbaum2018} and \citet{happ2018}. These estimates are then plugged into \eqref{eq:truncated_KL_expansion} and we represent the \gls{mfamm} as part of the general \gls{famm} framework (section \ref{subsec:FAMM}) by suitable re-arrangement. We can view the estimated $\bm{\psi}_{gm}(t)$ simply as an empirically derived basis that parsimoniously represents the patterns in the observed data. While their estimation adds uncertainty, we are not interested in inferential statements for the variance modes and our simulations (see Section \ref{sec:simulation}) suggest that the estimated eigenfunctions are reasonable approximations that work well as a basis. \subsection{Step 1: Estimation of the Eigenfunction Basis} \label{subsec:EigenfunctionEstimation} \subsubsection*{Step 1 (i): Univariate Mean Estimation} \label{subsubsec:UniMean} In a first step, we obtain preliminary estimates of the dimension specific means $\mu^{(d)}(\bm{x}_i, t) = \sum_{l=1}^{p}f_l^{(d)}(\bm{x}_{il}, t)$ using univariate \glspl{famm}. We model \begin{align} y_{it}^{(d)}&= \mu^{(d)}(\bm{x}_i, t) + \epsilon^{(d)}_{it};\; d=1,\dots,D \label{eq:uniMeanEstim} \end{align} independently for all $d$ with \gls{iid}~Gaussian random variables $\epsilon^{(d)}_{it}$. The estimation of $\mu^{(d)}(\bm{x}_i, t)$ proceeds analogously to the estimation of the \gls{mfamm} described in section \ref{subsec:FAMM}. It is based on the evaluation points of the $y_i^{*(d)}(t)$, whose locations on the interval $\mathcal{I}$ can vary across dimensions. Model \eqref{eq:uniMeanEstim} thus accommodates sparse and irregular multivariate functional data and implies a working independence assumption across scalar observations within and across functions. \subsubsection*{Step 1 (ii): Univariate Covariance Estimation} This preliminary mean function is used to centre the data $\tilde{y}_{it}^{(d)} = y_{it}^{(d)}- \hat{\mu}^{(d)}(\bm{x}_i, t)$ in order to obtain noisy evaluations of the detrended functions $\tilde{y}_i^{*(d)}(t) = y_i^{*(d)}(t) - {\mu}^{(d)}(\bm{x}_i, t)$ for covariance estimation. \citet{cederbaum2016} already find that for this purpose, the working independence assumption within functions across evaluation points in \eqref{eq:uniMeanEstim} gives reasonable results. The expectation of the crossproducts of the centred functions then coincides with the auto-covariance, i.e.\ $\mathbb{E}\left(\tilde{y}_{it}^{(d)}\tilde{y}_{i't'}^{(d)}\right) \approx \text{Cov}\left[y_{it}^{(d)}, y_{i't'}^{(d)}\right]$. For the independent random components specified in model \eqref{eq:multivariateFLMM}, this overall covariance decomposes additively into contributions from each random process as \begin{align} \label{eq:nested_random_effects_cov_estimation} \mathbb{E}\left(\tilde{y}_{it}^{(d)}\tilde{y}_{i't'}^{(d)}\right) \approx \sum_{j=1}^q K_{U_j}^{(d,d)}(t, t')\delta_{v_jv_j'} + \big(K_{E}^{(d,d)}(t, t') + \sigma^2_{d}\delta_{tt'}\big)\delta_{ii'}, \end{align} using indicators $\delta_{xx'}$ that equal one for $x=x'$ and zero otherwise. The indicator $\delta_{v_jv_j'}$ thus identifies if the curves in the crossproduct belong to the same group $v_j$ of the $j$th layer. Using $t$, $t'$, and the indicators $\delta_{v_jv_j'},\delta_{tt'}, \delta_{ii'}$ as covariates and the crossproducts of the centred data as responses, we can estimate the auto-covariances $K_{U_1}^{(d,d)}, ..., K_{U_q}^{(d,d)},$ and $K_{E}^{(d,d)}$ of the random processes using symmetric additive covariance smoothing \citep{cederbaum2018}. This extends the univariate approach proposed by \citet{cederbaum2016}. In particular, we also allow a nested random effects structure as required for the snooker training application in section \ref{subsec:snookerTraining} by specifying the indicator of the nested effect as the product of subject and session indicators. Note that estimating \eqref{eq:nested_random_effects_cov_estimation} also yields estimates of the dimension specific error variances $\sigma_d^{2}$ as a byproduct. \subsubsection*{Step 1 (iii): Univariate Eigenfunction Estimation} Based on the covariance kernel estimates, we apply separate univariate \glspl{fpca} for each random process by conducting an eigendecomposition of the respective linear integral operator. Practically, each estimated process- and dimension-specific auto-covariance is re-evaluated on a dense grid so that a univariate \gls{fpca} can be conducted. Alternatively, \citet{reiss2020tensor} provide an explicit spline representation of the estimated eigenfunctions. Eigenfunctions with non-positive eigenvalues are removed to ensure positive definiteness, and further regularization by truncation based on the proportion of variance explained is possible \citep[see e.g.][]{di2009multilevel, peng2009geometric, cederbaum2016}. However, we suggest to keep all univariate \glspl{fpc} with positive eigenvalues for the computation of the \gls{mfpca} in order to preserve all important modes of variation and cross-correlation in the data. \subsubsection*{Step 1 (iv): Multivariate Eigenfunction Estimation} The estimated univariate eigenfunctions and scores are then used to conduct an \gls{mfpca} for each of the $g$ multivariate random processes separately. The \gls{mfpca} exploits correlations between univariate \gls{fpc} scores across dimensions to reduce the number of basis functions needed to sufficiently represent the random processes. We base the \gls{mfpca} on the following definition of a (weighted) scalar product \begin{align} \label{eq:weighted_scalar_product} \langle\langle \bm{f}, \bm{g} \rangle\rangle := \sum_{d=1}^D w_d \int_{\mathcal{I}}f^{(d)}(t)g^{(d)}(t)dt, \quad \bm{f}, \bm{g} \in L^2_D(\mathcal{I}), \end{align} for the response space with positive weights $w_d, d = 1,...,D$ and the induced norm denoted by $\vert\vert\vert\cdot\vert\vert\vert$. The corresponding covariance operators $\Gamma_{g}: L^2_D(\mathcal{I}) \rightarrow L^2_D(\mathcal{I})$ of the multivariate random processes $\bm{U}_{jv}$ and $\bm{E}_v$ are then given by $(\Gamma_{g} \bm{f})(t) = \langle\langle \bm{f}, K_{g}(t, \cdot) \rangle\rangle$, $g\in\{U_1,..., U_q, E\}$. The standard choice of weights in our applications is $w_1 = ... = w_D = 1$ (unweighted scalar product) but other choices are possible. Consider for example a scenario where dimensions are observed with different amounts of measurement error. If variation in dimensions with a large proportion of measurement error is to be downweighted, we propose to use $w_d = \frac{1}{\hat{\sigma}^2_d}$ with the dimension specific measurement error variance estimates $\hat{\sigma}^2_d$ obtained from \eqref{eq:nested_random_effects_cov_estimation}. \citet{happ2018} show that estimates of the multivariate eigenvalues $\nu_{gm}$ of $\Gamma_g$ can be obtained from an eigenanalysis of a covariance matrix of the univariate random scores. The corresponding multivariate eigenfunctions $\bm{\psi}_{gm}$ can be obtained as linear combinations of the univariate eigenfunctions with the weights given by the resulting eigenvectors. The estimates $\hat{\bm{\psi}}_{gm}$ are then substituted for the basis functions of the truncated multivariate \gls{kl} expansions of the random effects $\bm{U}_{jv}$ and $\bm{E}_v$ in \eqref{eq:truncated_KL_expansion}. Note that for each random process $g$, the maximum number of \glspl{fpc} is given by the total number of univariate eigenfunctions included in the estimation process of the \gls{mfpca} of $g$. To achieve further regularization and analogously to \citet{cederbaum2016}, we propose to choose truncation orders $M_g$ for each \gls{kl} expansion of the multivariate random processes using a prespecified proportion of explained variation. \subsubsection*{Step 1 (v): Multivariate Truncation Order} We offer two different approaches for the choice of truncation orders $M_g$ based on different variance decompositions (derivation in Appendix \ref{app_sec:vardecomp}): \begin{gather} \label{eq:total_variation_decomp} \mathbb{E}\left(\vert\vert\vert \bm{y}_i - \bm{\mu}(\bm{x}_i) \vert\vert\vert^2 \right) = \sum_{d=1}^Dw_d\int_{\mathcal{I}}\mathrm{Var}\big(y_{i}^{(d)}(t)\big) dt =\sum_{g}\sum_{m = 1}^{\infty}\nu_{gm} + \sum_{d=1}^Dw_d\sigma_d^2 \vert\mathcal{I}\vert, \\ \label{eq:univar_variation_decomp} \text{and} \quad \int_{\mathcal{I}}\mathrm{Var}\big(y_{i}^{(d)}(t)\big) dt = \sum_{g}\sum_{m = 1}^{\infty}\nu_{gm}\vert\vert\psi_{gm}^{(d)}\vert\vert^2 + \sigma_d^2 \vert\mathcal{I}\vert \end{gather} with $\vert \mathcal{I}\vert$ the length of the interval $\mathcal{I}$ (here equal to one) and $\vert\vert\cdot\vert\vert$ the $L^2$ norm. Multivariate variance decomposition \eqref{eq:total_variation_decomp} uses the (weighted) sum of total variation in the data across dimensions. We select the \glspl{fpc} with highest associated eigenvalues $\nu_{gm}$ over all random processes $g$ until their sum reaches a prespecified proportion (e.g.\ 0.95) of the total variation, thus approximating the infinite sums in \eqref{eq:total_variation_decomp} with $M_g$ summands. For the approach based on the univariate variance \eqref{eq:univar_variation_decomp}, we require $M_g$ to be the smallest truncation order for which at least a prespecified proportion of variance is explained on every dimension $d$. This second choice of $M_g$ might be preferable in situations where the variation is considerably different (in amount or structure) across dimensions, whereas the first approach gives a more parsimonious representation of the random effects. Note that both approaches can lead to a simplification of the \gls{mfamm} if $M_g = 0$ is chosen for some $g$. The simulation results of section \ref{sec:simulation} suggest that increasing the number of \glspl{fpc} improves model accuracy which is why sensitivity analyses with regard to the truncation order are recommended. \subsection{Step 2: Estimation of the multiFAMM} \label{subsec:FAMM} In the following, we discuss estimating the \gls{mfamm} given the estimated multivariate \glspl{fpc}. We base the proposed model on the general \gls{famm} framework of \citet{scheipl2015}, which models functional responses using basis representations. To make the extension of the \gls{famm} framework to multivariate functional data more apparent, the multivariate response vectors and the respective model matrices are stacked over dimensions, so that every block has the structure of a univariate \gls{famm} over all observations $i$. This gives concatenated basis functions with discontinuities between the dimensions. The fixed effects are modelled analogously to the univariate case by interacting all covariate effects with a dimension indicator. The random effects are based on the parsimonious, concatenated multivariate \gls{fpc} basis. \subsubsection*{Matrix Representation} For notational simplicity we assume that the functions are evaluated on a fixed grid of time points $\boldsymbol{t} = (\boldsymbol{t}^{(1)}, ..., \boldsymbol{t}^{(D)})^{\top}$ with $\boldsymbol{t}^{(d)} = (\boldsymbol{t}_{1}^{(d)}, ..., \boldsymbol{t}_{N}^{(d)})$ and identical $\boldsymbol{t}_i^{(d)} \equiv (t_1,..., t_T)$ over all $N$ individuals and $D$ dimensions. However, our framework allows for sparse functional data using different grids per dimension and per observed function as in the two applications (Section \ref{sec:application}). Correspondingly, $\boldsymbol{y} = (\boldsymbol{y}^{(1)\top}, ..., \boldsymbol{y}^{(D)\top})^{\top}$ is the $DNT$-vector of stacked evaluation points with $\boldsymbol{y}^{(d)} = (\boldsymbol{y}_1^{(d)\top}, ..., \boldsymbol{y}_N^{(d)\top})^{\top}$ and $\boldsymbol{y}_i^{(d)} = (y_{i1}^{(d)},..., y_{iT}^{(d)})^{\top}$. Model \eqref{eq:multivariateFLMM} on this grid can be written as \begin{align} \label{eq:multiFAMM} \bm{y} = \bm{\Phi\theta} + \bm{\Psi\rho} + \bm{\epsilon} \end{align} with $\bm{\Phi}, \bm{\Psi}$ the model matrices for the fixed and random effects, respectively, $\bm{\theta},\bm{\rho}$ the vectors of coefficients and random effect scores to be estimated, and $\bm{\epsilon} = (\bm{\epsilon}^{(1)\top}, ..., \bm{\epsilon}^{(D)\top})^{\top}$, $\bm{\epsilon}^{(d)} = (\epsilon_{11}^{(d)}, ..., \epsilon_{1T}^{(d)}, ..., \epsilon_{NT}^{(d)})^{\top}$ the vector of residuals. We have $\bm{\epsilon} \sim N(\bm{0}, \bm{\Sigma})$ with $\bm{\Sigma} = \operatorname{diag}(\sigma_1^2,..., \sigma_D^2)\otimes \bm{I}_{NT}$, the Kronecker product denoted by $\otimes$, and the $(NT\times NT)$ identity matrix $\bm{I}_{NT}$. We estimate $\bm{\theta}$ and $\bm{\rho}$ by minimizing the \gls{pls} criterion \begin{align} \label{eq:pls} (\bm{y} - \bm{\Phi\theta} - \bm{\Psi\rho})\bm{\Sigma}^{-1}(\bm{y} - \bm{\Phi\theta} - \bm{\Psi\rho})^{\top} + \sum_{l=1}^{p}\bm{\theta}_{l}^{\top}\bm{P}_{l}(\bm{\lambda}_{xl}, \bm{\lambda}_{tl})\bm{\theta}_{l} + \sum_{g}\lambda_{g}\bm{\rho}_{g}^{\top}\bm{P}_{g}\bm{\rho}_{g} \end{align} using appropriate penalty matrices $\bm{P}_{l}(\bm\lambda_{xl}, \bm\lambda_{tl})$ and $\bm{P}_{g}$ for the fixed effects and random effects, respectively, and smoothing parameters $\bm{\lambda}_{xl} = \left(\lambda_{xl}^{(1)}, ..., \lambda_{xl}^{(D)}\right),\bm{\lambda}_{tl} = \left(\lambda_{tl}^{(1)}, ..., \lambda_{tl}^{(D)}\right)$, and $\lambda_g$. The model and penalty matrices as well as the parameter vectors of \eqref{eq:multiFAMM} and \eqref{eq:pls} are discussed in detail below. \subsubsection*{Modeling of Fixed Effects} The block diagonal matrix $\bm{\Phi} = \operatorname{diag}\left(\bm{\Phi}^{(1)}, ..., \bm{\Phi}^{(D)}\right)$ models the fixed effects separately on each dimension as in a \gls{famm} \citep{scheipl2015}. The $(DNT \times b)$ matrix $\bm{\Phi}$ consists of the design matrices $\bm{\Phi}^{(d)} = (\bm{\Phi}_1^{(d)}\,|\,...\,|\,\bm{\Phi}_p^{(d)})$ that are constructed for the partial predictors $f_{l}^{(d)}(\bm{x}, \bm{t}^{(d)}), l = 1, ..., p$, which correspond to the $NT$-vectors of evaluations of the effect functions $f_l^{(d)}$. The vectors of scalar covariates $\bm{x}_i$ are repeated $T$ times to form the matrix of covariate information $\bm{x} = (\bm{x}_1,..., \bm{x}_1,..., \bm{x}_N)^{\top}$. We use the basis representations \begin{align*} f_l^{(d)}(\bm{x}, \bm{t}^{(d)}) \approx \bm{\Phi}_l^{(d)}\bm{\theta}_l^{(d)} = (\bm{\Phi}_{xl}^{(d)} \odot \bm{\Phi}_{tl}^{(d)})\bm{\theta}_l^{(d)} , \end{align*} where $\bm{A}\odot\bm{B}$ denotes the row tensor product $(\bm{A}\otimes\bm{1}_b^{\top})\cdot(\bm{1}_a^{\top}\otimes\bm{B})$ of the $(h\times a)$ matrix $\bm{A}$ and the $(h\times b)$ matrix $\bm{B}$ with element-wise multiplication $\cdot$ and $\bm{1}_c$ the $c$-vector of ones. This modeling approach combines the $(NT \times b_{xl}^{(d)})$ basis matrix $\bm{\Phi}_{xl}^{(d)}$ with the $(NT \times b_{tl}^{(d)})$ basis matrix $\bm{\Phi}_{tl}^{(d)}$. These matrices contain the evaluations of suitable marginal bases in $\bm{x}$ and $\bm{t}^{(d)}$, respectively. For a linear effect, for example, the basis matrix $\bm{\Phi}_{xl}^{(d)}$ is specified as the familiar linear model design matrix $\bm{x}$ for the linear effect $f_l^{(d)}(\bm{x}, \bm{t}^{(d)}) = \bm{x}\bm{\beta}_l^{(d)}(\bm{t}^{(d)})$ with coefficient function $\bm{\beta}_l^{(d)}(\bm{t}^{(d)})$. For a nonlinear effect $f_l^{(d)}(\bm{x}, \bm{t}^{(d)})= g_l^{(d)}(\bm{x}, \bm{t}^{(d)})$, the basis matrix $\bm{\Phi}_{xl}^{(d)}$ contains an (e.g. B-spline) basis representation analogously to a scalar additive model. For the functional intercept, $\bm{\Phi}_{xl}^{(d)}$ is a vector of ones, and we generally use a spline basis for $\bm{\Phi}_{tl}^{(d)}$. For a complete list of possible effect specifications with examples, we refer to \citet{scheipl2015}. The tensor product basis is weighted by the $b_{xl}^{(d)}b_{tl}^{(d)}$ unknown basis coefficients in $\bm{\theta}_l^{(d)}$. Stacking the vectors $\bm{\theta}_l^{(d)}$ gives $\bm{\theta}^{(d)} = (\bm{\theta}_1^{(d)\top}, ..., \bm{\theta}_p^{(d)\top})^{\top}$ and finally the $b$-vector $\bm{\theta} = (\bm{\theta}^{(1)\top},..., \bm{\theta}^{(D)\top})^{\top}$ with $b = \sum_{d}\sum_{l}b_{xl}^{(d)}b_{tl}^{(d)}$. Choosing the number of basis functions is a well known challenge in the estimation of nonlinear or functional effects. We introduce regularization by a corresponding quadratic penalty term in \eqref{eq:pls}. Let $\bm{\theta}_l$ contain the coefficients corresponding to the partial predictor $l$ and order it by dimensions. The penalty $\bm{P}_{l}(\bm{\lambda}_{xl}, \bm{\lambda}_{tl})$ is then constructed from the penalty on the marginal basis for the covariate effect, $\bm{P}_{xl}^{(d)}$, and the penalty on the marginal basis over the functional index, $\bm{P}_{tl}^{(d)}$. Specifically, $\bm{P}_{l}(\bm{\lambda}_{xl}, \bm{\lambda}_{tl})$ is a block-diagonal matrix with blocks for each $d$ corresponding to the Kronecker sums of the marginal penalty matrices $\lambda_{xl}^{(d)}\bm{P}_{xl}^{(d)}\otimes \bm{I}_{b_{tl}^{(d)}} + \lambda_{tl}^{(d)}\bm{I}_{b_{xl}^{(d)}} \otimes \bm{P}_{tl}^{(d)}$ \citep{wood2017}. A standard choice for these marginal penalty matrices given a B-splines basis representation are second or third order difference penalties, thus approximately penalizing squared second or third derivatives of the respective functions \citep{eilers1996}. For unpenalized effects such as a linear effect of a scalar covariate, the corresponding $\bm{P}_{xl}^{(d)}$ is simply a matrix of zeroes. \subsubsection*{Modeling of Random Effects} We represent the $DNT$-vectors $\bm{U}_j(\bm{t}) = (\bm{U}_j(\bm{t}^{(1)})^{\top}, ..., \bm{U}_j(\bm{t}^{(D)})^{\top})^{\top}$, $\bm{E}(\bm{t}) = (\bm{E}(\bm{t}^{(1)})^{\top}, ..., \bm{E}(\bm{t}^{(D)})^{\top})^{\top}$ with $\bm{U}_j(\bm{t}^{(d)})$, $\bm{E}(\bm{t}^{(d)})$ containing the evaluations of the univariate random effects for the corresponding groups and time points using the basis approximations \begin{align*} \bm{U}_j(\bm{t}) \approx \bm{\Psi}_{U_j} \bm{\rho}_{U_j} = (\bm{\delta}_{U_j} \odot \tilde{\bm{\Psi}}_{U_j}) \bm{\rho}_{U_j}, \quad \bm{E}(\bm{t}) \approx \bm{\Psi}_E \bm{\rho}_{E} = (\bm{\delta}_E \odot \tilde{\bm{\Psi}}_E) \bm{\rho}_{E}. \end{align*} The $v$th column in the $(DNT \times V_g), g \in \{U_1,..., U_q, E\}$ indicator matrix $\bm{\delta}_g$ indicates whether a given row is from the $v$th group of the corresponding grouping layer. Thus, the rows of the indicator matrix $\bm{\delta}_g$ contain repetitions of the group indicators $\bm{z}_{ij}^{\top}$ and $\bm{e}_{i}^{\top}$ in model \eqref{eq:multivariateFLMM}. For the smooth residual, $\bm{\delta}_E$ simplifies to $\bm{1}_D\otimes(\bm{I}_N \otimes \bm{1}_T)$. The $(DNT \times M_g)$ matrix $\tilde{\bm{\Psi}}_g = (\tilde{\bm{\Psi}}_g^{(1)\top}| ... |\tilde{\bm{\Psi}}_g^{(D)\top})^{\top}$ comprises the evaluations of the $M_g$ multivariate eigenfunctions $\psi_{gm}^{(d)}(t)$ on dimensions $d = 1,...,D$ for the $NT$ time points contained in the $(NT\times M_g)$ matrix $\tilde{\bm{\Psi}}_g^{(d)}$. The $M_gV_g$ vector $\bm{\rho}_g = (\bm{\rho}_{g1}^{\top},...,\bm{\rho}_{gV_g}^{\top})^{\top}$ with $\bm{\rho}_{gv} = (\rho_{gv1},...,\rho_{gvM_g})^{\top}$ stacks all the unknown random scores for the functional random effect $g$. The $(DNT \times \sum_g M_gV_g)$ model matrix $\bm{\Psi} = (\bm{\Psi}_{U_1} | ... |\bm{\Psi}_{U_q} | \bm{\Psi}_E)$ then combines all random effect design matrices. Stacking the vectors of random scores in a $\sum_g M_gV_g$ vector $\bm{\rho}= (\bm{\rho}_{U_1}^{\top},..., \bm{\rho}_{U_q}^{\top}, \bm{\rho}_{E}^{\top})^{\top}$ lets us represent all functional random intercepts in the model via $\bm{\Psi}\bm{\rho}$. For a given functional random effect, the penalty takes the form $\bm{\rho}_{g}^{\top}\bm{P}_{g}\bm{\rho}_{g} = \bm{\rho}_g^{\top} (\bm{I}_{V_g}\otimes \tilde{\bm{P}}_g)\bm{\rho}_g$, where $\bm{I}_{V_g}$ corresponds to the assumed independence between the $V_g$ different groups. The diagonal matrix $\tilde{\bm{P}}_g =\operatorname{diag}(\nu_{g1},..., \nu_{gM_g})^{-1}$ contains the (estimated) eigenvalues $\nu_{gm}$ of the associated multivariate \glspl{fpc}. This quadratic penalty is mathematically equivalent to a normal distribution assumption on the scores $\bm{\rho}_{gv}$ with mean zero and covariance matrix $\tilde{\bm{P}}_g^{-1}$, as implied by the \gls{kl} theorem for Gaussian random processes. Note that the smoothing parameter $\lambda_g$ allows for additional scaling of the covariance of the corresponding random process. \subsubsection*{Estimation} We estimate the unknown smoothing parameters in $\bm{\lambda}_{xl}, \bm{\lambda}_{tl}$, and $\lambda_g$ using fast \gls{reml}-estimation \citep{wood2017}. The standard identifiability constraints of \glspl{famm} are used \citep{scheipl2015}. In particular, in addition to the constraints for the fixed effects, the multivariate random intercepts are subject to a sum-to-zero constraint over all evaluation points as given by e.g.\ \citet{refundpackage}. We propose a weighted regression approach to handle the heteroscedasticity assumption contained in $\bm{\Sigma}$. We weigh each observation proportionally to the inverse of the estimated univariate measurement error variances $\hat{\sigma}_d^2$ from the estimation of the univariate covariances \eqref{eq:nested_random_effects_cov_estimation}. Alternatively, updated measurement error variances can be obtained from fitting separate univariate \glspl{famm} on the dimensions using the univariate components of the multivariate \glspl{fpc} basis. In practice, we found that the less computationally intensive former option gives reasonable results. As our proposed model is part of the \gls{famm} framework, inference for the \gls{mfamm} is readily available based on inference for scalar additive mixed models \citep{wood2017}. Note, however, that all inferential statements do not incorporate uncertainty due to the estimated multivariate eigenfunction bases, nor in the chosen smoothing parameters. The estimation process readily provides i.a.\ standard errors for the construction of point-wise univariate \glspl{cb}. \subsection{Implementation} We provide an implementation of the estimation of the proposed \gls{mfamm} in the \texttt{multifamm} \texttt{R}-package \citep{multifammpackage}. It is possible to include up to two functional random intercepts in $\bm{U}(t)$, which can have a nested or crossed structure, in addition to the curve-specific random intercept $\bm{E}_i(t)$. While including e.g.\ functional covariates is conceptually straightforward \citep[see][]{scheipl2015}, our implementation is restricted to scalar covariates and interactions thereof. We provide different alternatives for specifying the multivariate scalar product, the multivariate cut-off criterion, and the covariance matrix of the white noise error term. Note that the estimated univariate error variances have been proposed as weights for two separate and independent modeling decisions: as weights in the scalar product of the \gls{mfpca} and as regression weights under heteroscedasticity across dimensions. \section{Applications} \label{sec:application} We illustrate the proposed \gls{mfamm} for two different data applications corresponding to intrinsically multivariate and multimodal fuctional data. The presentation focuses on the first application with a detailed description of the multimodal data application in Appendix \ref{APPsec:ca_data}. We provide the data and the code to produce all analyses in the github repository \textit{\href{https://github.com/alexvolkmann/multifammPaper}{multifammPaper}}. \subsection{Snooker Training Data} \label{subsec:snookerTraining} \subsubsection*{Data Set and Preprocessing} In a study by \citet{snooker2014}, 25 recreational snooker players split into two groups, one of which had instructions to follow a self-administered training schedule over the next six weeks consisting of exercises aimed at improving snooker specific muscular coordination. The second was a control group. Before and after the training period, both groups were recorded on high speed digital camera under similar conditions to investigate the effects of the training on their snooker shot of maximal force. In each of the two recording sessions, six successful shots per participant were videotaped. The recordings were then used to manually locate points of interest (a participant's shoulder, elbow, and hand) and track them on a two-dimensional grid over the course of the video. This yields a six dimensional functional observation per snooker shot $\bm{y}^{*} = (y^{*(\text{elbow.x})}, ..., y^{*(\text{shoulder.y})}): \mathcal{I} = [0, 1] \to \mathbb{R}^{6}$, i.e.\ a two-dimensional movement trajectory for each point of interest (see Figure \ref{fig:snook_obs}). \begin{figure} \begin{subfigure}{.37\textwidth} \includegraphics[scale=0.55]{images/snooker_pic.jpg} \end{subfigure} \begin{subfigure}{.5\textwidth} \includegraphics[scale=0.50]{images/snook_obs.png} \end{subfigure} \caption{\textit{Left:} Screenshot of software for tracking (blue lines) the points of interest (circles). \textit{Right:} Two-dimensional trajectories of the snooker training data set (grey curves, right). For both groups of skilled and unskilled participants, three randomly selected observations are highlighted. Every colour corresponds to one multivariate observation, i.e.\ one observation consists of three trajectories: elbow (top), shoulder (right), hand (bottom). The start of the exemplary trajectories are marked with a black asterisk with the hand trajectory centred at the origin.} \label{fig:snook_obs} \end{figure} In their starting position (hand centred at the origin), the snooker players are positioned centrally in front of the snooker table aiming at the cue ball. From their starting position, the players draw back the cue, then accelerate it forwards and hit the cue ball shortly after their hands enter the positive range of the horizontal $x$ axis. After the impulse onto the cue ball, the hand movement continues until it is stopped at a player's chest. \citet{snooker2014} identify two underlying techniques that a player can apply: dynamic and fixed elbow. With a dynamic elbow, the cue can be moved in an almost straight line (piston stroke) whereas additionally fixing the elbow results in a pendular motion (pendulum stroke). In both cases, the shoulder serves as a fixed point and should be positioned close to the snooker table. We adjust the data for differences in body height and relative speed \citep{steyer2020} and apply a coarsening method to reduce the number of redundant data points, thereby lowering computational demands of the analysis. Appendix \ref{app_sec:snooker_analysis} provides a detailed description of the data preprocessing. As some recordings and evaluations of bivariate trajectories are missing, the final data set contains 295 functional observations with a total of 56,910 evaluation points. These multivariate functional data are irregular and sparse, with a median of 30 evaluation points per functional observation (minimum 8, maximum 80) for each of the six dimensions. \subsubsection*{Model Specification} We estimate the following model \begin{align} \label{eq:snooker_model} \bm{y}_{ijht}= \bm{\mu}(\bm{x}_{ij}, t) + \bm{B}_i(t) + \bm{C}_{ij}(t) + \bm{E}_{ijh}(t) + \bm{\epsilon}_{ijht}, \end{align} with $i = 1,..., 25$ the index for the snooker player, $j = 1, 2$ the index for the session, $h = 1,..., H_{ij}$ the index for the typically six snooker shot repetitions in a session, and $t \in [0,1]$ relative time. Correspondingly, $\bm{B}_i(t)$ is a subject-specific random intercept, $\bm{C}_{ij}(t)$ is a nested subject-and-session-specific random intercept, and $\bm{E}_{ijh}(t)$ is the shot-specific random intercept (smooth residual). The nested random effect $\bm{C}_{ij}(t)$ is supposed to capture the variation within players between sessions (e.g.\ differences due to players having a good or bad day). Different positioning of participants with respect to the recording equipment or the snooker table as well as shot to shot variation are captured by the smooth residual $\bm{E}_{ijh}(t)$. The white noise measurement error $\bm{\epsilon}_{ijht}$ is assumed to follow a zero-mean multivariate normal distribution with covariance matrix $\sigma^2\bm{I}_6$, as all six dimensions are measured with the same set-up. The additive predictor is defined as \begin{align*} \bm{\mu}(\bm{x}_{ij},t) &= \bm{f}_0(t) + \texttt{skill}_{i}\cdot \bm{f}_1(t) +\texttt{group}_{i} \cdot \bm{f}_2(t) + \texttt{session}_{j}\cdot \bm{f}_3(t) \\ & \quad + \texttt{group}_{i}\cdot \texttt{session}_{j}\cdot\bm{f}_4(t). \end{align*} The dummy covariates $\texttt{skill}_i$ and $\texttt{group}_{i}$ indicate whether player $i$ is an advanced snooker player and belongs to the treatment group (i.e.\ receives the training programme), respectively. Note that the snooker players self-select into training and control group to improve compliance with the training programme, which is why we include a group effect in the model. The dummy covariate $\texttt{session}_{j}$ indicates whether the shot $j$ is recorded after the training period. The effect function $\bm{f}_4(t)$ can thus be interpreted as the treatment effect of the training programme. Cubic P-splines with first order difference penalty, penalizing deviations from constant functions over time, with 8 basis functions are used for all effect functions in the preliminary mean estimation as well as in the final \gls{mfamm}. For the estimation of the auto-covariances of the random processes, we use cubic P-splines with first order difference penalty on five marginal basis functions. We use an unweighted scalar product \eqref{eq:weighted_scalar_product} for the \gls{mfpca} to give equal weight to all spatial dimensions, as we can assume that the measurement error mechanism is similar across dimensions. Additionally, we find that hand, elbow, and shoulder contribute roughly the same amount of variation to the data, cf.\ Table \ref{APPENDIXtab:snooker_varcontr} in Appendix \ref{app_subsec:snooker_analysis}, where we also discuss potential weighting schemes for the \gls{mfpca}. The multivariate truncation order is chosen such that 95\% of the (unweighted) sum of variation \eqref{eq:total_variation_decomp} is explained. \subsubsection*{Results} The \gls{mfpca} gives sets of five (for $\bm{C}$ and $\bm{E}$) and six (for $\bm{B}$) multivariate \glspl{fpc} that explain 95\% of the total variation. The estimated eigenvalues allow to quantify their relative importance. Approximately 41\% of the total variation (conditional on covariates) can be attributed to the nested subject-and-session-specific random intercept $\bm{C}_{ij}(t)$, 33\% to the subject-specific random intercept $\bm{B}_i(t)$, 14\% to the shot-specific $\bm{E}_{ijh}(t)$, and 7\% to white noise. This suggests that day to day variation within a snooker player is larger than the variation between snooker players. Note that these proportions are based on estimation step 1 (see Section \ref{subsec:EigenfunctionEstimation}). \begin{figure} \centering \includegraphics[width=0.84\textwidth]{images/paper_snooker_eval.png} \caption{\textit{Left:} Dominant mode ($\bm{\psi}_{C1}$) of the subject-and-session-specific random effect, explaining $27.7\%$ of total variation and shown as mean trajectory (black solid) plus (red $+$) or minus (blue $-$) $2\sqrt{\nu_{C 1}}$ times the first \gls{fpc}. An asterisk marks the start of a trajectory. \textit{Right:} Estimated covariate effect functions for skill. The central plot shows the effect of the coefficient function (red) on the two-dimensional trajectories for the reference group (blue). The marginal plots show the estimated univariate effect functions (black) with pointwise 95\% \glspl{cb} (dotted) and the baseline (blue dashed).} \label{fig:eval_snooker} \end{figure} The left plot of Figure \ref{fig:eval_snooker} displays the first \gls{fpc} for $\bm{C}$, which explains about $28\%$ of total variation. A suitable multiple of the \glspl{fpc} is added ($+$) to and subtracted ($-$) from the overall mean function (black solid line, all covariate values set to $0.5$). We find that the dominant mode of the random subject-and-session specific effect influences the relative positioning of a player's elbow, shoulder, and hand, thus suggesting a strong dependence between the dimensions. \citet{snooker2014} argue from a theoretical viewpoint that the ideal starting position should place elbow and hand in a line perpendicular to the plane of the snooker table (corresponding to the x axis). The most prominent mode of variation captures deviations from this ideal starting position found in the overall mean. The next most important \gls{fpc} $\bm{\psi}_{B1}$ of the subject-specific random effect, which explains about $15\%$ of total variation, represents a subject's tendency towards the piston or pendulum stroke (see Appendix Figure \ref{APPENDIXfig:snooker_fpc_B}). This additional insight into the underlying structure of the variance components might be helpful for e.g.\ developing personalized training programmes. The central plot on the right of Figure \ref{fig:eval_snooker} compares the estimated mean movement trajectory for advanced snooker players (red) to that in the reference group (blue). It suggests that more experienced players tend towards the dynamic elbow technique, generating a hand trajectory resembling a straight line (piston stroke). Uncertainties in the trajectory could be represented by pointwise ellipses, but inference is more straightforward to obtain from the univariate effect functions. The marginal plots display the estimated univariate effects with pointwise 95\% confidence intervals. Even though we find only little statistical evidence for increased movement of the elbow (horizontal-left and vertical-top marginal panels), the hand and shoulder movements (horizontal centre and right, vertical centre and bottom) strongly suggest that the skill level indeed influences the mean movement trajectory of a snooker player. Further results indicate that the mean hand trajectories might slightly differ between treatment and control group at baseline as well as between sessions ($\bm{f}_2(t)$ and $\bm{f}_3(t)$, see Appendix Figure \ref{APPENDIXfig:snooker_cov_023}). The estimated treatment effect $\bm{f}_4(t)$ (Appendix Figure \ref{APPENDIXfig:snooker_cov_1_4}), however, suggests that the training programme did not change the participants' mean movement trajectories substantially. Appendix \ref{app_subsec:snooker_analysis} contains a detailed discussion of all model terms as well as some model diagnostics and sensitivity analyses. \subsection{Consonant Assimilation Data} \subsubsection*{Data Set and Model Specification} \citet{pouplier2016} study the assimilation of the German /s/ and /sh/ sounds such as the final consonant sounds in ``Kürbis'' (English example: ``haggis'') and ``Gemisch'' (English example: ``dish''), respectively. The research question is how these sounds assimilate in fluent speech when combined across words such as in ``Kürbis-Schale'' or ``Gemisch-Salbe'', denoted as /s\#sh/ and /sh\#s/ with \# the word boundary. The 9 native German speakers in the study repeated a set of 16 selected word combinations five times. Two different types of functional data, i.e.\ \gls{aco} and \gls{epg} data, were recorded for each repetition to capture the acoustic (produced sound) and articulatory (tongue movements) aspects of assimilation over (relative) time $t$ within the consonant combination. Each functional index varies roughly between $+1$ and $-1$ and measures how similar the articulatory or acoustic pattern is to its reference patterns for the first ($+1$) and second ($-1$) consonant at every observed time point \citep{cederbaum2016}. Without assimilation, the data are thus expected to shift from positive to negative values in a sinus-like form (see Figure \ref{fig:speech_obs}). The data set contains 707 bivariate functional observations with differently spaced grids of evaluation points per curve and dimension, with the number of evaluation points ranging from 22 to 59 with a median of 35. Note that the consonant assimilation data are unaligned as registration of the time domain would mask transition speeds between the consonants, which are an interesting part of assimilation. \begin{figure} \centering \includegraphics[width=0.8\textwidth]{images/speech_obs.png} \caption{Index curves of the consonant assimilation data set for both \gls{aco} and \gls{epg} data as a function of standardized time $t$ (grey curves). For every consonant order, three randomly selected observations have been highlighted. Every colour corresponds to one multivariate observation, i.e.\ one observation consists of two index curves.} \label{fig:speech_obs} \end{figure} For comparability, we follow the model specification of \citet{cederbaum2016}, who analyse only the \gls{aco} dimension and ignore the second mode \gls{epg}. Our specified multivariate model is similar to \eqref{eq:snooker_model} with $i = 1,..., 9$ the speaker index, $j = 1, ..., 16$ the word combination index, $h = 1,..., H_{ij}$ the repetition index and $t \in [0,1]$ relative time. Note that the nested effect $\bm{C}_{ij}(t)$ is replaced by the crossed random effect $\bm{C}_{j}(t)$ specific to the word combinations. The additive predictor $\bm{\mu}(\bm{x}_{j}, t)$ now contains eight partial effects: the functional intercept plus main and interaction effects of scalar covariates describing characteristics of the word combination such as the order of the consonants /s/ and /sh/. The white noise measurement error $\bm{\epsilon}_{ijht}$ is assumed to follow a zero-mean bivariate normal distribution with diagonal covariance matrix $\operatorname{diag}(\sigma^2_{\text{ACO}}, \sigma^2_{\text{EPG}})$. The basis and penalty specifications follow the univariate analysis in \citet{cederbaum2016}. Given different sampling mechanisms, we also compare the \gls{mfamm} based on weighted and unweighted scalar products for the \gls{mfpca}. \subsubsection*{Results} The multivariate analysis supports the findings of \citet{cederbaum2016} that assimilation is asymmetric (different mean patterns for /s\#sh/ and /sh\#s/). Overall, the estimated fixed effects are similar across dimensions as well as comparable to the univariate analysis. Hence, the multivariate analysis indicates that previous results for the acoustics are consistently found also for the articulation. Compared to univariate analyses, our approach reduces the number of \gls{fpc} basis functions and thus the number of parameters in the analysis. The \gls{mfamm} can improve the model fit and can provide smaller \glspl{cb} for the \gls{aco} dimension compared to the univariate model in \citet{cederbaum2016} due to the strong cross-correlation between the dimensions. We find similar modes of variation for the multivariate and the univariate analysis as well as across dimensions. In particular, the word combination-specific random effect $\bm{C}_{j}(t)$ is dropped from the model as much of the between-word variation is already explained by the included fixed effects. The definition of the scalar product has little effect on the estimated fixed effects but changes the interpretation of the \glspl{fpc}. Appendix \ref{APPsec:ca_data} contains a more in depth description of this application. \section{Simulations} \label{sec:simulation} \subsection{Simulation Set-Up} We conduct an extensive simulation study to investigate the performance of the \gls{mfamm} depending on different model specifications and data settings (over 20 scenarios total), and to compare it to univariate regression models as proposed by \citet{cederbaum2016}, estimated on each dimension independently. Given the broad scope of analysed model scenarios, we refer the interested reader to Appendix \ref{app_sec:simulation} for a detailed report and restrict the presentation here to the main results. We mimic our two presented data examples (Section \ref{sec:application}) and simulate new data based on the respective \gls{mfamm}-fit. Each scenario consists of model fits to 500 generated data sets, where we randomly draw the number and location of the evaluation points, the random scores, and the measurement errors according to different data settings. The accuracy of the estimated model components is measured by the \gls{mse} based on the unweighted multivariate norm but otherwise as defined by \citet{cederbaum2016}, see Appendix \ref{app_subsec:sim_description}. The \gls{mse} takes on (unbounded) positive values with smaller values indicating a better fit. \subsection{Simulation Results} Figure \ref{fig:sim_eval_multi} compares the \gls{mse} values over selected modeling scenarios based on the consonant assimilation data. We generate a benchmark scenario (dark blue), which imitates the original data without misspecification of any model component. In particular, the number of \glspl{fpc} is fixed to avoid truncation effects. Comparing this scenario to the other blue scenarios illustrates the importance of the number of \glspl{fpc} in the accuracy of the estimation. Choosing the truncation order via the proportion of univariate variance explained (Cut-Off Uni) as in \eqref{eq:univar_variation_decomp} gives models with roughly the same number of \glspl{fpc} (mean $\bm{B}:2.8, \bm{E}:5$) as is used for the data generation ($\bm{B}:3, \bm{E}:5$). The cut-off criterion based on the multivariate variance (Cut-Off Mul) given by \eqref{eq:total_variation_decomp} results in more parsimonious models (mean $\bm{B}:2.15, \bm{E}:4$) and thus considerably higher \gls{mse} values. The increased variation in the \gls{mse} values can also be attributed to variability in the truncation orders (cf. Appendix Figure \ref{fig:app_sim_nfpc_y}), leading to a mixture distribution. Comparing the benchmark scenario to more sparsely observed functional data (ceteris paribus) suggests a lower estimation accuracy for the Sparse Data scenario, especially for the curve-specific random effect $\bm{E}_{ijh}(t)$ and resultingly the fitted curves $\bm{y}_{ijh}(t)$, but pooling the information across functions helps the estimation of $\bm{\mu}(\bm{x}_{ij}, t)$ and $\bm{B}_{i}(t)$. In particular, the estimation of the mean $\bm{\mu}(\bm{x}_{ij}, t)$ is quite robust against the increased uncertainty of these three scenarios. Only when the random scores are not centred and decorrelated as in the benchmark scenario do we find an increase in \gls{mse} values for the mean (Uncentred Scores). This corresponds to a departure from the modeling assumptions likely to occur in practice when only few levels of a random effect are available (here for the subject-specific $\bm{B}_{i}(t)$). The model then has difficulties to correctly separate the intercept in $\bm{\mu}(\bm{x}_{ij}, t)$ and the random effects $\bm{B}_{i}(t)$. The empirical (non-zero) mean of the $\bm{B}_{i}(t)$ is then absorbed by the intercept in $\bm{\mu}(\bm{x}_{ij}, t)$, resulting in higher \gls{mse} values for both of these model terms. However, this shift does not affect the overall fit to the data $\bm{y}_{ijh}(t)$ nor the estimation of the other fixed effects (cf. Appendix Figure \ref{fig:app_sim_eff_umse}). Note that the \gls{mse} values of the Sparse Data and Uncentred Scores scenarios are based on slightly different normalizing constants (i.e.\ different true data) and cannot be directly compared except for the mean. \begin{figure} \includegraphics[width=\textwidth]{images/sim_multivariate_abr.png} \caption{\gls{mse} values of the fitted curves $\bm{y}_{ijh}(t)$, the mean $\bm{\mu}(\bm{x}_{ij}, t)$, and the random effects $\bm{B}_{i}(t)$ and $\bm{E}_{ijh}(t)$ for different modeling scenarios. Scenarios coloured with blue correspond to different model specifications in the same data setting.} \label{fig:sim_eval_multi} \end{figure} Our simulation study thus suggests that basing the truncation orders on the proportion of explained variation on each dimension \eqref{eq:univar_variation_decomp} gives parsimonious and well fitting models. If interest lies mainly in the estimation of fixed effects, the alternative cut-off criterion based on the total variation in the data \eqref{eq:total_variation_decomp} allows even more parsimonious models at the cost of a less accurate estimation of the random effects and overall model fit. Furthermore, the results presented in Appendix \ref{app_sec:simulation} show that the mean estimation is relatively stable over different model scenarios including misspecification of the measurement error variance structure or of the multivariate scalar product, as well as in scenarios with strong heteroscedasticity across dimensions. In our benchmark scenario, the \glspl{cb} cover the true effect $89-94\%$ of the time but coverage can further decrease with additional uncertainty e.g.\ about the number of \glspl{fpc}. Overall, the covariance structure such as the leading \glspl{fpc} can be recovered well, also for a nested random effect such as in the snooker training application. The comparison to the univariate modeling approach suggests that the \gls{mfamm} can improve the mean estimation but is especially beneficial for the prediction of the random effects while reducing the number of parameters to estimate. In some cases like strong heteroscedasticity, including weights in the multivariate scalar product might further improve the modeling. \section{Discussion} \label{sec:discussion} The proposed multivariate functional regression model is an additive mixed model, which allows to model flexible covariate effects for sparse or irregular multivariate functional data. It uses \gls{fpc} based functional random effects to model complex correlations within and between functions and dimensions. An important contribution of our approach is estimating the parsimonious multivariate \gls{fpc} basis from the data. This allows us to account not only for auto-covariances, but also for non-trivial cross-covariances over dimensions, which are difficult to adequately model using alternative approaches such as parametric covariance functions like the Matèrn family or penalized splines, which imply a parsimonious covariance only within but not necessarily between functions. As a \gls{famm}-type regression model, a wide range of covariate effect types is available, also providing pointwise \glspl{cb}. Our applications show that the \glspl{mfamm} can give valuable insight into the multivariate correlation structure of the functions in addition to the mean structure. An apparent benefit of multivariate modeling is that it allows to answer research questions simultaneously relating to different dimensions. In addition, using multivariate \glspl{fpc} reduces the number of parameters compared to fitting comparable univariate models while improving the random effects estimation by incorporating the cross-covariance in the multivariate analysis. The added computational costs are small: For our multimodal application, the multivariate approach prolongs the computation time by only five percent (104 vs.\ 109 minutes on a 64-bit Linux platform). We find that the average point-wise coverage of the point-wise \glspl{cb} can in some cases lie considerably below the nominal value. There are two main reasons for this: One, the \glspl{cb} presented here do not incorporate the uncertainty of the eigenfunction estimation nor of the smoothing parameter selection. Two, coverage issues can arise in (scalar) mixed models, if effect functions are estimated as constant when in truth they are not \citep[e.g.][]{wood2017, Grevencomment}. To resolve these issues, further research on the level of scalar mixed models might be needed. A large body of research covering \gls{cb} estimation for functional data \citep[e.g.][]{goldsmith2013corrected, choi2018, liebl2019fast} suggests that the construction of \glspl{cb} is an interesting and complex problem, also outside of the \gls{famm} framework. It would be interesting to extend the \gls{mfamm} to more general scenarios of multivariate functional data such as observations consisting of functions with different dimensional domains, e.g.\ functions over time and images as in \citet{happ2018}. This would require adapting the estimation of the univariate auto-covariances for spatial arguments $t, t'$. Exploiting properties of dense functional data, such as the block structure of design matrices for functions observed on a grid, could help to reduce computational cost in this case. Future research could further generalize the covariance structure of the \gls{mfamm} by allowing for additional covariate effects. In our snooker training application, for example, a treatment effect of the snooker training might show itself in the form of reduced intra-player variance \citep[cf.][]{backenroth2018}. Ideas from distributional regression could be incorporated to jointly model the mean trajectories and covariance structure conditional on covariates. \section*{Acknowledgements} We thank Timon Enghofer, Phil Hoole, and Marianne Pouplier for providing access to their data and for fruitful discussions. We also thank Lisa Steyer for contributing the data registration of the snooker training data and two anonymous reviewers for their helpful suggestions. Sonja Greven, Almond Stöcker, and Alexander Volkmann were funded by grant GR 3793/3-1 from the German research foundation (DFG). Fabian Scheipl was funded by the German Federal Ministry of Education and Research (BMBF) under Grant No. 01IS18036A.
{'timestamp': '2021-10-06T02:19:11', 'yymm': '2103', 'arxiv_id': '2103.06606', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06606'}
arxiv
\section{Introduction}\label{sec:intro} \emph{Residuation theory}~\cite{residuation} concerns the study of partially ordered algebraic structures, most often just monoids, equipped with an operator that behaves as a weak inverse to the monoidal one, without the structure being necessarily a group. Such structures have since long be investigated in mathematics and computer science. Concerning e.g. logics, residuated monoids form the basis for the semantics of substructural logics~\cite{onoETC}. As for e.g. discrete event systems such as weighted automata, the use of tropical semirings put forward the adoption of residuals for the approximated solution of inequalities~\cite{resbook}. One of the recent area of application of residuation theory has been constraint programming. Roughly, a \emph{Soft Constraint Satisfaction Problem} is given by a relation on a set of variables, plus a preference score to each assignment of such variables~\cite{jacm97,schiex}. They key requirement is the presence of an aggregator operator for combining preferences, making such a set a monoid, and a large body of work has been devoted to enrich such a structure, guaranteeing that resolution techniques can be generalised by a parametric formalism for designing metrics and algorithms. An example are \emph{local-consistency} algorithms~\cite{arconsistency}, devised for safely moving costs towards constraints involving a smaller number of variables, without changing the set of solutions and their preference. In order to ``move'' quantities, we need to ``subtract'' costs somewhere and ``add'' them elsewhere. The paper focuses on residuated monoids for constraint programming. Their relevance for local-consistency, as mentioned above, has been spotted early on~\cite{residuation1,resCS}, and various extensions has been proposed~\cite{ipl}, as well as applications to languages based on the Linda paradigm, such as \emph{Soft Concurrent Constraint Programming}, where a process may be \emph{telling} and \emph{asking} constraints to a centralised store~\cite{labelled}. More precisely, we tackle here two aspects. On the one side, we consider lexicographic orders, as used in contexts with multi-objective problems. That is, the preference values are obtained by the combination of separate concerns, and the order of the combination matters. On the other side, we introduce a soft version of \emph{Bucket} and \emph{Mini-bucket} elimination algorithms, well-known exact and approximated techniques for inference, which exploits the presence of a residuated monoid: in order to have an estimation of the approximation on the preference level of a solution, it is necessary to use a removal operator. Finally we present a \emph{Depth-First Branch-and-Bound} algorithm, which exploits upper and lower bounds to prune search. Our proposals generalise the original soft versions of these approximation techniques presented in~\cite{bucketsemiring}. Lexicographic orders are potentially useful in applications that involve multiple objectives and attributes, and as such have been extensively investigated in the literature on soft constraints. However, usually the connection has been established by encoding a lexicographic \emph{hard} constraint problem, where the preference structure is a Boolean algebra, into a soft constraint formalism. For example, in \cite{freuderlexi} the authors show how to encode a lexicographic order and how the resulting structure can support specialised algorithms such as \emph{Branch-and-bound}. \emph{Hierarchical Constraint Logic Programming}~\cite{hierarchicalclp} frameworks allow to handle both hard constraints and several preference levels of soft constraints, whose violations need to be minimised, and such levels are usually managed following a lexicographic order~\cite{valuation}. However, even if lifting the algebraic structure of a preference set to the associated set of (possibly infinite) tuples with a point-wise order is straightforward, doing the same for the lexicographic order is not, and this result cannot be directly achieved for the formalisms in \cite{jacm97,schiex}. The solution advanced in~\cite{GadducciHMW13,valuation} is to drop some preference values from the domain carrier of the set of tuples. The present work builds on this proposal by dealing with sets of preferences that form residuated monoids, systematise and extending the case of infinite tuples tackled in~\cite{sca} to tuples of any length. The paper has the following structure: in Section~\ref{sec:om} we present the background on partially ordered residuated monoids, which is the structure we adopt to model preferences. In Section~\ref{sec:collapsing} we consider the collapsing elements of a monoid, which will be used to define an ad-hoc algebraic structure representing (possibly infinite) lexicographically ordered tuples of elements of the chosen monoid, which is given in Section~\ref{sec:lexico}. The latter section also presents our main construction, introducing residuation for these lexicographically ordered monoids. Section~\ref{sec:bucket} shows how residuation helps to find a measure of goodness between an algorithm and its tractable approximation. Finally, in Section~\ref{sec:conclusion} we wrap up the paper with concluding remarks and ideas about future works. \section{Preliminaries}\label{sec:om} This section recalls some of the basic algebraic structures needed for defining the set of preference values. In particular, we propose elements of \emph{ordered monoids} to serve as preferences, which allows us to compare and compose preference values. \subsection{Ordered Monoids} \label{sec:lem} The first step is to define an algebraic structure for modelling preferences. We refer to~\cite{ipl} for the missing proofs as well as for an introduction and a comparison with other proposals. \begin{definition}[Orders] A partial order (PO) is a pair $\langle A, \leq \rangle$ such that $A$ is a set and $\leq \,\,\subseteq A \times A$ is a reflexive, transitive, and anti-symmetric relation. % % A join semi-lattice (simply semi-lattice, SL) is a POs such that any finite subset of $A$ has a least upper bound (LUB); a complete lattice (CL) is a PO such that any subset of A has a LUB. \end{definition} The LUB of a subset $X \subseteq A$ is denoted $\bigvee X$, and it is unique. Note that we require the existence of $\bigvee \emptyset$, which is the bottom of the order, denoted as $\bot$, and sometimes we will talk about a PO with bottom element (POB). The existence of LUBs for any subset of $A$ (thus including $\emptyset$) guarantees that CLs also have greatest lower bounds (GLBs) for any subset $X$ of $A$: it will be denoted by $\bigwedge X$. Whenever it exists, $\bigvee A$ corresponds to the top of the order, denoted as $\top$. \begin{definition}[Ordered monoids]\label{defn:clm} A (commutative) monoid is a triple $\langle A, \otimes,$ $\mathbf{1} \rangle$ such that $\otimes: A \times A \rightarrow A$ is a commutative and associative function and $\mathbf{1} \in A$ is its \emph{identity} element, i.e., $\forall a \in A. a \otimes \mathbf{1} = a$. A partially ordered monoid (POM) is a 4-tuple $\langle A, \leq, \otimes, \mathbf{1} \rangle$ such that $\langle A, \leq \rangle$ is a PO and $\langle A, \otimes, \mathbf{1} \rangle$ a monoid. % A semi-lattice monoid (SLM) and a complete lattice monoid (CLM) are POMs such that their underlying PO is a SL, a CL respectively. \end{definition} For ease of notation, we use the infix notation: $a \otimes b$ stands for $\otimes(a,b)$. \begin{example}[Power set]\label{ex:powerset} Given a (possibly infinite) set $V$ of variables, we consider the monoid $\langle 2^V, \cup, \emptyset \rangle$ of (possibly empty) subsets of $V$, with union as the monoidal operator. Since the operator is idempotent (i.e., $\forall a\in A.\, a \otimes a = a$), the natural order ($\forall a, b \in A.\, a \leq b$ iff $a \otimes b = b$) is a partial order, and it coincides with subset inclusion: in fact, $\langle 2^V, \subseteq, \cup, \emptyset \rangle$ is a CLM. \end{example} In general, the partial order $\leq$ and the multiplication $\otimes$ can be unrelated. This is not the case for distributive CLMs. \begin{definition}[Distributivity] \label{dist} A SLM $\langle A, \leq, \otimes, \mathbf{1} \rangle$ is finitely distributive if \[ \forall X \subseteq_f A.\, \forall a \in A.\, \quad a \otimes \bigvee X = \bigvee \{a \otimes x \mid x \in X\}. \] A CLM is distributive is the equality holds also for any subset. \end{definition} In the following, we will sometimes write $a \otimes X$ for the set $\{a \otimes x \mid x \in X\}$. \begin{remark} Note that $a \leq b$ is equivalent to $\bigvee \{a,b\} = b$ for all $a, b \in A$. Hence, finite distributivity implies that $\otimes$ is monotone with respect to $\leq$ (i.e., $\forall a, b, c \in A.\, a \leq b \Rightarrow a \otimes c \leq b \otimes c$) and that $\bot$ is the zero element of the monoid (i.e., $\forall a \in A.\, a\otimes \bot = \bot$). The power-set CLM in Example~\ref{ex:powerset} is distributive. \end{remark} \begin{example}[Extended integers]\label{ex:bipolar} The extended integers $\langle \mathbb{Z} \cup \{\pm \infty\}, \leq, +, 0 \rangle$, where $\leq$ is the natural order, such that for $k \in \mathbb{Z}$ $$-\infty \leq k \leq +\infty,$$ $+$ is the natural addition, such that for $k \in \mathbb{Z} \cup \{+\infty\}$ $$\pm\infty + k = \pm \infty, \qquad \qquad +\infty + (-\infty) = -\infty,$$ and $0$ the identity element constitutes a distributive CLM, and $+\infty$ and $-\infty$ are respectively the top and the bottom element of the CL. \end{example} \begin{remark} Finitely distributive SLMs precisely corresponds to \emph{tropical} semirings by defining the (idempotent) sum operator as $a \oplus b = \bigvee \{a, b\}$ for all $a,b \in A$. If, moreover, $\mathbf{1}$ is the top of the SLM we end up with \emph{absorptive} semirings~\cite{golan}, which are known as $c$-semirings in the soft constraint jargon~\cite{jacm97}. Together with monotonicity, imposing $\mathbf{1}$ to coincide with $\top$ means that preferences are negative (i.e., $a \leq \mathbf{1}$ for all $a \in A$). Distributive CLMs are known in the literature as \emph{quantales}~\cite{quantales}. \end{remark} \begin{remark} \label{remark} Given two distributive CLMs, it is easy to show that their Cartesian product, whose elements are pairs and where the partial order and the monoidal operator are defined point-wise, is a distributive CLM. % In particular, in the following we consider the Cartesian product of $\langle \mathbb{Z} \cup \{\pm \infty\}, \leq, +, 0 \rangle$ with itself: its set of elements is $(\mathbb{Z} \cup \{\pm \infty\})^2$, the identity element is $(0,0)$, and the top and bottom elements are $(+\infty, +\infty)$ and $(-\infty, -\infty)$, respectively. \end{remark} \subsection{Residuated monoids} We first introduce \emph{residuation}, which allows us to define a ``weak'' inverse operator with respect to the monoidal operator $\otimes$. In this way, besides aggregating values together, it is also possible to remove one from another. Residuation theory~\cite{golan} is concerned with the study of sub-solutions of the equation $b \otimes x = a$, where $x$ is a ``divisor'' of $a$ with respect to $b$. The set of sub-solutions of an equation contains also the possible solutions, whenever they exist, and in that case the maximal element is also a solution. \begin{definition}[residuation] A residuated POM is a 5-tuple $\langle A,$ $\leq, \otimes, { \ominus\hspace{-8pt}:}\;, \mathbf{1} \rangle$ such that $\langle A, \leq \rangle$ is a PO, $\langle A, \otimes, \mathbf{1} \rangle$ is a monoid, and ${ \ominus\hspace{-8pt}:}\;: A \times A \rightarrow A$ is a function such that \begin{itemize} \item $\forall a, b, c \in A.\ b \otimes c \leq a \iff c \leq a { \ominus\hspace{-8pt}:}\; b$. \end{itemize} \end{definition} In the following, we will sometimes write $a { \ominus\hspace{-8pt}:}\; X$ and $X { \ominus\hspace{-8pt}:}\; a$ for the set $\{a { \ominus\hspace{-8pt}:}\; x \mid x \in X\}$ and $\{x { \ominus\hspace{-8pt}:}\; a \mid x \in X\}$, respectively. \begin{remark} It is easy to show that residuation is monotone on the first argument and anti-monotone on the second. In fact, in a SML $\bigvee (X { \ominus\hspace{-8pt}:}\; a) \leq \bigvee X { \ominus\hspace{-8pt}:}\; a$, and the same in a CLM with respect to infinite sub-sets. However, the equality does not hold, e.g. in the Cartesian product of the CLM $\langle N \cup \{\infty\}, \geq, +, 0 \rangle$ with itself. Also, $a { \ominus\hspace{-8pt}:}\; \bigvee X \leq \bigwedge (a { \ominus\hspace{-8pt}:}\; X)$ whenever the latter exists, as it does in CLMs. \end{remark} \begin{remark} \label{remarkC} As for distributivity, given two residuated POMs, it is easy to show that their Cartesian product is a residuated POM. \end{remark} Residuation implies distributivity (see e.g.~\cite[Lem. 2.2]{ipl}). \begin{lemma} Let $\langle A, \leq, \otimes, \mathbf{1} \rangle$ be a residuated POM. Then it is monotone. If additionally it is a SLM (CLM), then it is finitely distributive (distributive). \end{lemma} Conversely, it is noteworthy that CLMs are always residuated, and the following folklore fact holds. \begin{lemma} \label{resCLM} Let $\langle A, \leq, \otimes, \mathbf{1} \rangle$ be a distributive CLM. It is residuated and $\forall a, b \in A.\ a { \ominus\hspace{-8pt}:}\; b = \bigvee \{c \mid b \otimes c \leq a\}$. \end{lemma} We close with a simple lemma relating residuation with the top and the bottom elements of a POM. \begin{lemma} \label{someProps} Let $\langle A, \leq, \otimes, { \ominus\hspace{-8pt}:}\;, \mathbf{1} \rangle$ be a residuated POM. If it has the bottom element $\bot$, then it also has the top element $\top$and $\forall a \in A.\ a { \ominus\hspace{-8pt}:}\; \bot = \top$. % Viceversa, if it has the top element $\top$ then $\forall b \in A.\ \top { \ominus\hspace{-8pt}:}\; b = \top$. \end{lemma} \begin{remark} Nothing can be stated for $\bot { \ominus\hspace{-8pt}:}\; a$, since there could be elements that are $\bot$-divisors: see again the Cartesian product of the CLM $\langle \mathbb N \cup \{\infty\}, \geq, +, 0 \rangle$ with itself, where $\langle \infty, 3\rangle \otimes \langle 4, \infty \rangle = \langle \infty,\infty \rangle$. Similarly, nothing can be stated for $a { \ominus\hspace{-8pt}:}\; \top$: see the Cartesian product of the CLM $\langle \mathbb N \cup \{\infty\}, \geq, +, 0 \rangle$ with its dual CLM $\langle \mathbb N \cup \{\infty\}, \leq, +, 0 \rangle$. \end{remark} \section{The ideal of collapsing elements} \label{sec:collapsing} As shown in~\cite{GadducciHMW13}, the first step for obtaining SLMs based on a lexicographic order is to restrict the carrier of the monoid. \begin{definition} Let $\langle A, \otimes, \mathbf{1} \rangle$ be a monoid. Its sub-set $I(A)$ of \emph{cancellative} elements is defined as $\{ c \mid \forall a, b \in A.\ a \otimes c = b \otimes c \implies a = b \}$. \end{definition} We recall a well-known fact. \begin{lemma} \label{ideal} Let $\langle A, \otimes, \mathbf{1} \rangle$ be a monoid. % Then $I(A)$ is a sub-monoid of $A$ and $C(A) = A\setminus I(A)$ is a prime ideal of $A$. \end{lemma} Explicitly, $C(A) = \{ c \mid \exists a, b \in A.\ a \neq b \wedge a \otimes c = b \otimes c\}$. Being an ideal means that $\forall a \in A, c \in C( A).\ a \otimes c \in C(A)$, and being prime further states that $\forall a, b \in A.\ a\otimes b \in C( A) \implies a \in C(A) \vee b \in C(A)$. All the proofs are straightforward, and we denote $C(A)$ as the set of \emph{collapsing} elements of $A$. Note that an analogous closure property does not hold for LUBs. \begin{example}\label{flat} Consider the monoid of natural numbers $\langle \mathbb N, +, 0 \rangle$ and the (non distributive) CLM with elements $\mathbb N \cup \{\bot,\top\}$ obtained by lifting the flat order (i.e., $a \not \leq b$ for any $a, b \in \mathbb N$ as well as $a + \bot = \bot = \top + \bot$ and $a + \top = \top$ for any $a \in \mathbb N$). Then, $I(\mathbb N \cup \{\bot,\top\}) = \mathbb N$ is not closed under finite LUBs. Now, let us consider the distributive CLM with elements $\mathbb N \cup \{\infty\}$ obtained by lifting the natural order induced by addition. We have that $I(\mathbb N \cup \{\infty\}) = \mathbb N$ is a (finitely distributive) SLM, yet it is not closed with respect to infinite LUBs. \end{example} We now present a simple fact that is needed later on. \begin{lemma} Let $A_1, A_2$ be POMs and $A_1 \times A_2$ their Cartesian product. Then we have $C(A_1 \times A_2) = C(A_1) \times A_2 \cup A_2 \times C(A_2)$. \end{lemma} \begin{example} Let us consider the tropical SLM $\langle \mathbb N \cup \{\infty\}, \geq, +, 0 \rangle$ and the Cartesian product with itself. Clearly, $C(\mathbb N\times \mathbb N)$ is not closed under finite LUBs: it suffices to consider $X= \{\langle \infty, 3 \rangle, \langle 4, \infty \rangle\} \subseteq C(\mathbb N\times \mathbb N)$, since $\bigvee X = \langle 3,4 \rangle \not \in C(\mathbb N\times \mathbb N)$. % Neither is $C(\mathbb N\times \mathbb N)$ closed under residuation, as suggested by Lem.~\ref{someProps}, since the top element is not necessarily collapsing. Indeed, in $C(\mathbb N\times \mathbb N)$ we have $\langle \infty, 4 \rangle { \ominus\hspace{-8pt}:}\; \langle \infty, 3 \rangle = \langle 0,1\rangle$. \end{example} \begin{remark} Note that in an absorptive CLM $A$ we have that $a { \ominus\hspace{-8pt}:}\; b = 1$ whenever $b \leq a$. Hence $C(A)$ is usually not closed under residuation, since $1$ is cancellative. \end{remark} \subsection{A different view on collapsing elements} When the first presentation of lexicographic SLMs was provided~\cite{GadducciHMW13}, a different set of collapsing elements was considered. \begin{definition}[\cite{GadducciHMW13}] Let $\langle A, \leq, \otimes, \mathbf{1} \rangle$ be a POM. Its sub-set $C'(A)$ is defined as $\{ c \mid \exists a, b \in A.\ a < b \wedge a \otimes c = b \otimes c\}$. \end{definition} Clearly, $C'(A) \subseteq C(A)$. However, we can replicate Lem.~\ref{ideal}. \begin{lemma} Let $\langle A, \otimes, \mathbf{1} \rangle$ be a monoid. % Then $C'(A)$ is an ideal of $A$. If $\otimes$ is monotone, then $I'(A) = A \setminus C'(A) $ is a sub-monoid of $A$ and $C'(A)$ a prime ideal of $A$. \end{lemma} Explicitly, $I'(A) = \{ c \mid \forall a, b \in A.\ a \otimes c = b \otimes c \implies a \not < b \}$. The definitions we encounter in the next section could then be rephrased using $I'(A)$ and $C'(A)$ with minimal adjustments, thus confirming the proposal in~\cite{GadducciHMW13}.\footnote{And in fact, the lemma holds also for a property that is weaker than monotonicity: it suffices that $\forall a, b, c.\ a \leq b \implies (a \otimes c \leq b \otimes c) \vee (b \otimes c \leq a \otimes c)$. } However, what is in fact noteworthy is that the two approaches are coincident whenever distributivity holds, as shown by the lemma below. \begin{lemma} Let $\langle A, \leq, \otimes, \mathbf{1} \rangle$ be a finitely distributive SLM. % Then $C'(A) = C(A)$. \end{lemma} \begin{proof} We already noted that $C'(A) \subseteq C(A)$ always holds. Now, let $a, b, c$ such that $a \neq b \wedge a \otimes c = b \otimes c$: it suffices to consider $a \vee b$, noting that it must be either $a < a \vee b$ or $b < a \vee b$ and that by distributivity $(a \vee b) \otimes c = a \otimes c = b \otimes c$. \end{proof} \begin{remark} Consider the (non distributive) CLM $\langle \mathbb [0 \ldots n] \cup \{\bot,\top\}, +, 0 \rangle$ obtained by lifting the initial segment $[0 \ldots n]$ of the natural numbers with the flat order (as done for the CLM of all natural numbers in Example~\ref{flat}). Here addition is capped, so that e.g. $n + m = n$ for all $m$. Hence, $C([0 \ldots n] \cup \{\bot,\top\}) = [1 \ldots n] \cup \{\bot,\top\}$ that is, all elements except $0$. Instead, $C'([0 \ldots n] \cup \{\bot,\top\})) = \{\bot,\top\}$. \end{remark} \section{On lexicographic orders}\label{sec:lexico} We now move to lexicographic orders, taking into account the results in Sect.~\ref{sec:collapsing}. \begin{proposition}\label{def:lexilist} Let $\langle A, \leq, \otimes, \mathbf{1} \rangle$ be a POM with bottom element $\bot$. % Then we can define a family $\langle Lex_k(A), \leq_k, \otimes^k, \mathbf{1}^k \rangle$ of POMs with bottom element $\bot^k$ such that $\otimes^k$ is defined point-wise, $Lex_1(A) = A$ and $\leq_1 = \leq$, and \begin{itemize} \item $Lex_{k+1}(A) = I(A) Lex_k(A) \cup C(A) \{\bot\}^k$, \item $a_1 \ldots a_k \leq_k b_1 \ldots b_k$ if $a_1 < b_1$ or $a_1 = b_1$ and $a_2 \ldots a_k \leq_{k-1} b_2 \ldots b_k$. \end{itemize} \end{proposition} \begin{proof} Monoidality of $\otimes^k$ as well as reflexivity and symmetry of $\leq_k$ are straightforward. As for transitivity, let $a_1 \ldots a_k \leq_k b_1 \ldots b_k$ and $b_1 \ldots b_k \leq_k c_1 \ldots c_k$. If $a_1 \leq b_1 < c_1$ or $a_1 < b_1 \leq c_1$, it follows immediately; if $a_1 = b_1 = c_1$, then it holds by induction. \end{proof} Note that $Lex_k(A)$ is contained in the $k$-times Cartesian product $A^k$, and the definitions of $\otimes^k$, $\mathbf{1}^k$, and $\bot^k$ coincide. Also, the bottom element is needed for padding the tuples, in order to make simpler the definition of the order. We can provide an alternative definition for such POMs. \begin{lemma} Let $\langle A, \leq, \otimes, \mathbf{1} \rangle$ be a POM with bottom element $\bot$. Then $Lex_{k+1}(A) = \bigcup_{i \leq k}I(A)^i A \{\bot\}^{k-i}$ for all $k$. \end{lemma} \begin{proof} The proof goes by induction on $k$. For $k = 0$ it is obvious. Let assume it to be true by induction for $k = n$, that is, $Lex_{n+1}(A) = \bigcup_{i \leq n}I(A)^i A \{\bot\}^{n-i}$ . Now, $Lex_{n+2}(A) = I(A) Lex_{n+1}(A) \cup C(A) \{\bot\}^{n+1} = \bigcup_{i \leq n}I(A)^{i+1} A \{\bot\}^{n-i} \cup C(A) \{\bot\}^{n+1} = \bigcup_{i \leq n+1}I(A)^{i} A \{\bot\}^{n+1-i}$ and we are done, where the latter equality holds since $I(A)\{\bot\}^{n+1} \in \bigcup_{i \leq n}I(A)^{i+1} A \{\bot\}^{n-i}$ and $A = I(A) \cup C(A)$. \end{proof} Now, given a tuple $a$ of elements in $A^k$, for $i \leq k$ we denote with $a_i$ its $i$-th component and with $a_{\mid i}$ its prefix $a_1 \ldots a_i$, with the obvious generalisation for a set $X \subseteq A^k$, noting that $a_1 = a_{\mid 1}$. \begin{theorem}\label{theo:lexiSLM} Let $\langle A, \leq, \otimes, \mathbf{1} \rangle$ be a finitely distributive SLM (distributive CLM). Then so is $\langle Lex_k(A), \leq_k, \otimes^k, \mathbf{1}^k \rangle$ for all $k$. \end{theorem} \begin{proof} As a first step, we define the LUB $\bigvee X$ of a set $X \subseteq Lex_k(A)$, given inductively as \begin{itemize} \item $(\bigvee X)_1 = \bigvee X_1 = \bigvee \{ y \mid y \in X_{\mid 1}\}$ \item $(\bigvee X)_{i+1} = \bigvee \{ y \mid (\bigvee X)_1 \ldots (\bigvee X)_i y \in X_{\mid i+1}\}$ \end{itemize} Now, $\bigvee X$ is clearly a suitable candidate, since $x \leq_k \bigvee X$ for all $x \in X$. Minimality is proved inductively by exploiting the analogous definition of $\leq_k$. Concerning distributivity, we need to show that $(\bigvee a \otimes^k X)_n = a_n \otimes (\bigvee X)_n$ holds for all $n \leq k$. We proceed by induction on $n$. If $n = 1$, this boils down to the distributivity of the underlying monoid, since $$(\bigvee a \otimes^k X)_1 = \bigvee (a \otimes^k X)_1 = \bigvee \{ y \mid y \in (a \otimes^k X)_{\mid 1}\} =$$ $$\bigvee \{ y \mid \exists z \in X_{\mid 1}.\ y = a_1 \otimes z\} = \bigvee \{ a_1 \otimes z \mid z \in X_{\mid 1}\}$$ and $$ a_1 \otimes (\bigvee X)_1 = a_1 \otimes \bigvee \{ y \mid y \in X_{\mid 1}\} = \bigvee \{ a_1 \otimes y \mid y \in X_{\mid 1}\}$$ Now, let us assume that it holds for $n$. Now we have $$(\bigvee a \otimes^k X)_{n+1} = \bigvee \{ y \mid (\bigvee a \otimes^k X)_1 \ldots (\bigvee a \otimes^k X)_n y \in (a \otimes^k X)_{\mid n+1}\} =$$ $$ \bigvee \{ y \mid \exists z \in X_{n+1}.\ y = a_{n+1} \otimes z \wedge a_1 \otimes (\bigvee X)_1 \ldots a_n \otimes (\bigvee X)_n y \in (a \otimes^k X)_{\mid n+1}\} =$$ $$ \bigvee \{ a_{n+1} \otimes z \mid (\bigvee X)_1 \ldots (\bigvee X)_n z \in X_{\mid n+1}\}$$ The latter equality obviously holds if $a_1 \ldots a_n$ are cancellative, yet it holds also otherwise since in that case $a_{n+1} = \bot$, hence both sides coincide with $\bot$. Finally $$a_{n+1} \otimes (\bigvee X)_{n+1} = a_{n+1} \otimes \bigvee \{ y \mid (\bigvee X)_1 \ldots (\bigvee X)_n y \in X_{\mid n+1}\} =$$ $$ \bigvee \{ a_{n+1} \otimes y \mid (\bigvee X)_1 \ldots (\bigvee X)_n y \in X_{\mid n+1}\}$$ \end{proof} \subsection{On lexicographic residuation} The fact that $Lex_k(A)$ is a CLM if so is $A$ tells us that $Lex_k(A)$ is also residuated. \begin{example} Let us consider the usual tropical CLM of natural numbers with inverse order, and the CLM $Lex_{2}(\mathbb N)$. Clearly $C(\mathbb N) = +\infty$. We then have for example that \[ (3, 6) { \ominus\hspace{-8pt}:}\;_2 (4, 2) = \bigvee \{(x, y) \mid (4 + x, 2 + y) \leq_2 (3, 6)\} = (0,0) \] Indeed, $(4 + x, 2 + y) \leq_2 (3, 6)$ holds for any possible choice of $(x, y)$, since $4 + x < 3$ for all $x$, hence $(0,0)$ as the result. % Note that for the CLM obtained via the Cartesian product $\mathbb N \times \mathbb N$, the result would have been $(0, 4)$. \end{example} Indeed, this can be proved in general for POMs. First, we need some additional definitions and technical lemmas. \begin{definition} Let $\langle A, \leq, \otimes, { \ominus\hspace{-8pt}:}\;, \mathbf{1} \rangle$ be a residuated POM with bottom and $a, b \in Lex_k(A)$. Then \begin{itemize} \item $\gamma(a, b) = min\{ i \mid (a_i { \ominus\hspace{-8pt}:}\; b_i) \in C(A)\}$ \item $\delta(a, b) = min\{ i \mid (a_i { \ominus\hspace{-8pt}:}\; b_i) \otimes b_i < a_i\}$ \end{itemize} with the convention that the result is $k+1$ whenever the set if empty. \end{definition} \begin{lemma}\label{limit} Let $\langle A, \leq, \otimes, { \ominus\hspace{-8pt}:}\;, \mathbf{1} \rangle$ be a residuated POM with bottom and $a, b \in Lex_k(A)$. Then either $\delta(a,b) = k+1$ or $\delta(a,b) \leq \gamma(a,b)$. \end{lemma} \begin{proof} If $\gamma(a,b) < \delta(a,b) \leq k$ then $a_{\gamma(a,b)} = (a_{\gamma(a,b)} { \ominus\hspace{-8pt}:}\; b_{\gamma(a,b)}) \otimes b_{\gamma(a,b)}$. Since $C(A)$ is an ideal of $A$, it holds that $a_{\gamma(a,b)} \in C(A)$, which in turn implies that $a_{\delta(a,b)} = \bot$, hence a contradiction. \end{proof} We can then present the definition of residuation for lexicographic POMs only for the cases identified by the proposition above. \begin{proposition} \label{div0} Let $\langle A, \leq, \otimes, { \ominus\hspace{-8pt}:}\;, \mathbf{1} \rangle$ be a residuated POM with bottom and $a, b \in Lex_k(A)$. If $\delta(a,b) = \gamma(a,b) = k+1$ then their residuation $a { \ominus\hspace{-8pt}:}\;_k b$ in $Lex_k(A)$ exists and it is given by \[ (a_1 { \ominus\hspace{-8pt}:}\; b_1) \ldots (a_k { \ominus\hspace{-8pt}:}\; b_k) \] \end{proposition} \begin{proof} First of all, note that $a { \ominus\hspace{-8pt}:}\;_k b \in I(A)^k \subseteq Lex_k(A)$. So, given $c \in Lex_k(A)$, we need to prove that $b\otimes^k c \leq_k a$ iff $c \leq_k a { \ominus\hspace{-8pt}:}\;_k b$. \begin{description} \item[$\mathbf{[b\otimes^k c \leq_k a].}$] Let $l = min \{ i \mid b_i \otimes c_i < a_i\}$, with the convention that the result is $k+1$ whenever the set if empty. Also, let $m = min\{l, k\} < \delta(a,b)$. We have that $b_j \otimes c_j \leq a_j$ for all $j \leq m$, hence $c_j \leq a_j { \ominus\hspace{-8pt}:}\; b_j $ for all $j \leq m$. % If $c_n < a_n { \ominus\hspace{-8pt}:}\; b_n$ for some $n \leq m$ we are done. % Otherwise, if $m = k < l$ then $c_n = a_n { \ominus\hspace{-8pt}:}\; b_n$ for all $n \leq k$ and we are done. % Finally, if $m = l \leq k $ then $b_l \otimes c_l = b_l \otimes (a_l { \ominus\hspace{-8pt}:}\; b_l) = a_l$ since $l < \delta(a,b)$, hence a contradiction. \item[$\mathbf{[c \leq_k a { \ominus\hspace{-8pt}:}\;_k b].}$] Let $l = min \{ i \mid c_i < (a { \ominus\hspace{-8pt}:}\;_k b)_i\}$, with the convention that the result is $k+1$ whenever the set if empty. Also, let $m = min \{l, k\} < \delta(a,b)$. We have that $c_j \leq (a { \ominus\hspace{-8pt}:}\;_k b)_j = a_j { \ominus\hspace{-8pt}:}\; b_j$ for all $j \leq m$, hence $b_j \otimes c_j \leq a_j$ for all $j \leq m$. % If $b_n \otimes c_n < a_n$ for some $n \leq m$ we are done. % Otherwise, if $m = k < l$ then $b_n \otimes c_n = a_n$ for all $n \leq k$ and we are done. % Finally, if $m = l \leq k$ then $b_l \otimes c_l = a_l = b_l \otimes (a_l { \ominus\hspace{-8pt}:}\; b_l)$ since $l < \delta(a,b)$, hence either a contradiction if $b_l \in I(A)$ or $b_p \otimes c_p = \bot = a_p$ for all $p > l$ if $b_l \in C(A)$ and consequently $a_l \in C(A)$. \end{description} \end{proof} Note that $a { \ominus\hspace{-8pt}:}\;_k b$ here coincides with the residuation $a { \ominus\hspace{-8pt}:}\;^k b$ on the Cartesian product. Furthermore, we have that $(a { \ominus\hspace{-8pt}:}\;_k b) \otimes^k b = a$. \begin{proposition} \label{div1} Let $\langle A, \leq, \otimes, { \ominus\hspace{-8pt}:}\;, \mathbf{1} \rangle$ be a residuated POM with bottom and $a, b \in Lex_k(A)$. If $\delta(a,b) < \gamma(a,b)$ then their residuation $a { \ominus\hspace{-8pt}:}\;_k b$ in $Lex_k(A)$ exists and it is given by \[ (a_1 { \ominus\hspace{-8pt}:}\; b_1) \ldots (a_{\delta(a, b)} { \ominus\hspace{-8pt}:}\; b_{\delta(a, b)}) (\bigvee Lex_{k - \delta(a, b)}(A)) \] \end{proposition} \begin{proof} First of all, note that $(a { \ominus\hspace{-8pt}:}\;_k b)_{\mid \delta(a,b)} \in I(A)^{\delta(a,b)} \subseteq Lex_{\delta(a,b)}(A)$. So, given $c \in Lex_k(A)$, we need to prove that $b\otimes^k c \leq_k a$ iff $c \leq_k a { \ominus\hspace{-8pt}:}\;_k b$. \begin{description} \item[$\mathbf{[b\otimes^k c \leq_k a].}$] Let $l = min \{ i \mid b_i \otimes c_i < a_i\}$, with the convention that the result is $k+1$ whenever the set if empty. Also, let $m = min \{l, \delta(a,b)\}$. We have that $b_j \otimes c_j \leq a_j$ for all $j \leq m$, hence $c_j \leq a_j { \ominus\hspace{-8pt}:}\; b_j $ for all $j \leq m$. % If $c_n < a_n { \ominus\hspace{-8pt}:}\; b_n$ for some $n \leq m$ we are done. % Otherwise, if $m = \delta(a,b) \leq l$ then $c_j \leq a_j { \ominus\hspace{-8pt}:}\; b_j $ for all $j \leq \delta(a,b)$ and we are done. % Finally, if $m = l < \delta(a,b)$ then $b_l \otimes c_l = b_l \otimes (a_l { \ominus\hspace{-8pt}:}\; b_l) = a_l$, hence a contradiction. \item[$\mathbf{[c \leq_k a { \ominus\hspace{-8pt}:}\;_k b].}$] Let $l = min \{ i \mid c_i < (a { \ominus\hspace{-8pt}:}\;_k b)_i\}$, with the convention that the result is $k+1$ whenever the set if empty. Also, let $m = min \{l, \delta(a,b)\}$. We have that $c_j \leq (a { \ominus\hspace{-8pt}:}\;_k b)_j = a_j { \ominus\hspace{-8pt}:}\; b_j$ for all $j \leq m$, hence $b_j \otimes c_j \leq a_j$ and $b_j \otimes c_j \leq b_j \otimes (a_j { \ominus\hspace{-8pt}:}\; b_j)$ for all $j \leq m$, the latter by monotonicity of $\otimes$. % If $b_n \otimes c_n < a_n$ for some $n \leq m$ we are done. % Otherwise, if $m = \delta(a,b) \leq l$ then $b_{\delta(a,b)} \otimes (a_{\delta(a,b)} { \ominus\hspace{-8pt}:}\; b_{\delta(a,b)}) < a_{\delta(a,b)} = b_{\delta(a,b)} \otimes c_{\delta(a,b)} \leq b_{\delta(a,b)} \otimes (a_{\delta(a,b)} { \ominus\hspace{-8pt}:}\; b_{\delta(a,b)})$, hence a contradiction. % Finally, if $m = l < \delta(a,b)$ then $b_l \otimes c_l = a_l = b_l \otimes (a_l { \ominus\hspace{-8pt}:}\; b_l)$, hence either a contradiction if $b_l \in I(A)$ or $b_p \otimes c_p = \bot = a_p$ for all $p > l$ if $b_l \in C(A)$ and consequently $a_l \in C(A)$. \end{description} \end{proof} Additionally, please note that $\bigvee Lex_n(A)$ can be easily characterised: it coincides with $\top^n$ if $\top \in I(A)$, and with $\top \bot^{n -1}$ otherwise. \begin{proposition} \label{div2} Let $\langle A, \leq, \otimes, { \ominus\hspace{-8pt}:}\;, \mathbf{1} \rangle$ be a residuated POM with bottom element $\bot$ and $a, b \in Lex_k(A)$. If $\delta(a,b) = \gamma(a,b) \leq k$ or $\delta(a,b) > \gamma(a,b)$ then their residuation $a { \ominus\hspace{-8pt}:}\;_k b$ in $Lex_k(A)$ exists and it is given by \[ (a_1 { \ominus\hspace{-8pt}:}\; b_1) \ldots (a_{\gamma(a, b)} { \ominus\hspace{-8pt}:}\; b_{\gamma(a, b)}) \bot^{k - \gamma(a, b)} \] \end{proposition} \begin{proof} First of all, note that $(a { \ominus\hspace{-8pt}:}\;_k b)_{\mid \gamma(a,b)} \in I(A)^{\gamma(a,b)-1} C(A) \subseteq Lex_{\gamma(a,b)}(A)$. Also, $\delta(a,b) > \gamma(a,b)$ implies that $\delta(a,b) = k+1$ and $a_{\gamma(a,b)} \in C(A)$. Given $c \in Lex_k(A)$, we need to prove that $b\otimes^k c \leq_k a$ iff $c \leq_k a { \ominus\hspace{-8pt}:}\;_k b$. \begin{description} \item[$\mathbf{[b\otimes^k c \leq_k a].}$] Let $l = min \{ i \mid b_i \otimes c_i < a_i\}$, with the convention that the result is $k+1$ whenever the set if empty. Also, let $m = min \{l, \gamma(a,b)\} \leq \delta(a,b)$. We have that $b_j \otimes c_j \leq a_j$ for all $j \leq m$, hence $c_j \leq a_j { \ominus\hspace{-8pt}:}\; b_j $ for all $j \leq m$. % If $c_n < a_n { \ominus\hspace{-8pt}:}\; b_n$ for some $n \leq m$ we are done. % Otherwise, if $m = \gamma(a,b) \leq l$ then $c_{\gamma(a,b)} \in C(A)$ and we are done since $c_p = \bot = (a { \ominus\hspace{-8pt}:}\;_k b)_p$ for all $p > {\gamma(a,b)}$. % Finally, if $m = l < \gamma(a,b)$ then $b_l \otimes c_l = b_l \otimes (a_l { \ominus\hspace{-8pt}:}\; b_l) = a_l$ since $l < \delta(a,b)$, hence a contradiction. \item[$\mathbf{[c \leq_k a { \ominus\hspace{-8pt}:}\;_k b].}$] Let $l = min \{ i \mid c_i < (a { \ominus\hspace{-8pt}:}\;_k b)_i\}$, with the convention that the result is $k+1$ whenever the set if empty. Also, let $m = min \{l, \gamma(a,b)\} \leq \delta(a,b)$. We have that $c_j \leq (a { \ominus\hspace{-8pt}:}\;_k b)_j = a_j { \ominus\hspace{-8pt}:}\; b_j$ for all $j \leq m$, hence $b_j \otimes c_j \leq a_j$ and $b_j \otimes c_j \leq b_j \otimes (a_j { \ominus\hspace{-8pt}:}\; b_j)$ for all $j \leq m$, the latter by monotonicity of $\otimes$. % If $b_n \otimes c_n < a_n$ for some $n \leq m$ we are done. % Otherwise, if $m = \gamma(a,b) < l$ then $c_{\gamma(a,b)} \in C(A)$ and we are done since $b_p \otimes c_p = \bot \leq a_p$ for all $p > {\gamma(a,b)}$. % Finally, if $m = l \leq \gamma(a,b)$ then $b_l \otimes (a_l { \ominus\hspace{-8pt}:}\; b_l) \leq a_l = b_l \otimes c_l \leq b_l \otimes (a_l { \ominus\hspace{-8pt}:}\; b_l)$ since $l \leq \delta(a,b)$, hence either a contradiction if $b_l \in I(A)$ or $b_p \otimes c_p = \bot = a_p$ for all $p > l$ if $b_l \in C(A)$ and consequently $a_l \in C(A)$. \end{description} \end{proof} From the propositions above it is straightforward to derive Th.~\ref{prop:lexiRes}, which states that, given a residuated POM, it is possible to define a lexicographic order on its tuples, which is a residuated POM as well. \begin{theorem}\label{prop:lexiRes} Let $\langle A, \leq, \otimes, { \ominus\hspace{-8pt}:}\;, \mathbf{1} \rangle$ be a residuated POM with bottom element $\bot$. Then so is $\langle Lex_k(A), \leq_k, \otimes^k, { \ominus\hspace{-8pt}:}\;_k, \mathbf{1}^k \rangle$ for all $k$, with ${ \ominus\hspace{-8pt}:}\;_k$ defined as \[ a { \ominus\hspace{-8pt}:}\;_k b = \begin{cases} \begin{array}{lcl} (a_1 { \ominus\hspace{-8pt}:}\; b_1) \ldots (a_k { \ominus\hspace{-8pt}:}\; b_k) & & \mbox{if } k+1 = \gamma(a,b) = \delta(a,b) \\ (a_1 { \ominus\hspace{-8pt}:}\; b_1) \ldots (a_{\gamma(a, b)} { \ominus\hspace{-8pt}:}\; b_{\gamma(a, b)}) \bot^{k - \gamma(a, b)} & & \mbox{if } k+1 \neq \gamma(a,b) \leq \delta(a,b) \\ (a_1 { \ominus\hspace{-8pt}:}\; b_1) \ldots (a_{\delta(a, b)} { \ominus\hspace{-8pt}:}\; b_{\delta(a, b)}) (\bigvee Lex_{k-\delta(a,b)}(A)) & & \mbox{otherwise} \end{array} \end{cases} \] \end{theorem} \subsection{Infinite tuples}\label{sec:infinite} We can now move to POMs whose elements are tuples of infinite length. \begin{proposition} Let $\langle A, \leq, \otimes, \mathbf{1} \rangle$ be a POM with bottom element $\bot$. % Then we can define a POM $\langle Lex_\omega(A), \leq_\omega, \otimes^\omega, \mathbf{1}^\omega \rangle$ with bottom element $\bot^\omega$ such that $\otimes^\omega$ is defined point-wise and \begin{itemize} \item $Lex_\omega(A) = I(A)^\omega \cup I(A)^\ast A \{\bot\}^\omega$ \item $a \leq_\omega b$ if $a_{\leq k} \leq_k b_{\leq k}$ for all $k$ \end{itemize} \end{proposition} A straightforward adaptation of Prop.~\ref{def:lexilist}. Thus, we can define a POM of infinite tuples simply by lifting the family of POMs of finite tuples. \begin{remark} Note that the seemingly obvious POM structure cannot be lifted to $\bigcup_k Lex_k(A) = I(A)^\ast A \{\bot\}^\ast$: it would be missing the identity of the monoid. \end{remark} \begin{proposition}\label{prop:lexiSLM} Let $\langle A, \leq, \otimes, \mathbf{1} \rangle$ be a finitely distributive SLM (distributive CLM). Then so is $\langle Lex_\omega(A), \leq_\omega, \otimes^\omega, \mathbf{1}^\omega \rangle$. \end{proposition} Also a straightforward adaptation, this time of Th.~\ref{theo:lexiSLM}. \begin{proposition}\label{prop:lexiResOmega} Let $\langle A, \leq, \otimes, { \ominus\hspace{-8pt}:}\;, \mathbf{1} \rangle$ be a residuated POM with bottom. Then so is $\langle Lex_\omega(A), \leq_\omega, \otimes^\omega, { \ominus\hspace{-8pt}:}\;_\omega, \mathbf{1}^\omega \rangle$, with ${ \ominus\hspace{-8pt}:}\;_w$ defined as \[ a { \ominus\hspace{-8pt}:}\;_\omega b = \begin{cases} \begin{array}{lcl} (a_1 { \ominus\hspace{-8pt}:}\; b_1) \ldots (a_k { \ominus\hspace{-8pt}:}\; b_k) \ldots & & \mbox{if } \infty = \gamma(a,b) = \delta(a,b) \\ (a_1 { \ominus\hspace{-8pt}:}\; b_1) \ldots (a_{\gamma(a, b)} { \ominus\hspace{-8pt}:}\; b_{\gamma(a, b)}) \bot^\omega & & \mbox{if } \infty \neq \gamma(a,b) \leq \delta(a,b) \\ (a_1 { \ominus\hspace{-8pt}:}\; b_1) \ldots (a_{\delta(a, b)} { \ominus\hspace{-8pt}:}\; b_{\delta(a, b)}) (\bigvee Lex_{\omega}(A)) & & \mbox{otherwise} \end{array} \end{cases} \] \end{proposition} It follows from Th.~\ref{prop:lexiRes}, via the obvious extension of Lem.~\ref{limit}. Note that $\bigvee Lex_\omega(A)$ is $\top^\omega$ if $\top \in I(A)$, and $\top \bot^\omega$ otherwise. \section{Mini-bucket elimination for residuated POMs}\label{sec:bucket} This section shows an application of residuation to a general approximation algorithms for soft CSPs, \emph{Mini-Bucket Elimination} (MBE)~\cite{minibucket}, a relaxation of a well-known complete inference algorithm, \emph{Bucket Elimination} (BE)~\cite{bucket}. BE first partitions the constraints into \emph{buckets}, where the bucket of a variable stores those constraints whose \emph{support}\footnote{The \emph{support} of a constraint is the set of variables on which assignment it depends.} contains that variable and none that is higher in the ordering: variables are previously sorted according to some criteria (e.g., just lexicographically on their names: $v_1, v_2, \dots$). The next step is to process the buckets from top to bottom. When the bucket of variable $v$ is processed, an \emph{elimination procedure} is performed over the constraints in its bucket, yielding a new constraint defined over all the variables mentioned in the bucket, excluding $v$. This constraint summarises the ``effect'' of $v$ on the remainder of the problem. The new constraint ends up in a lower bucket. BE finds the preference of the optimal solution and not an approximation of it; however, BE is exponential in the induced width, which measures the aciclicity of a problem. On the other hand, MBE takes advantage of a control parameter $z$: it partitions the buckets into smaller subsets called \emph{mini-buckets}, such that their arity is bounded by $z$. Therefore, the cost of computing this approximation is now exponential in $z$, which allows trading off time and space for accuracy. MBE is often used for providing bounds in branch-and-bound algorithms (see Sect.~\ref{sec:softbb}). Algorithm~\ref{alg:soft:bucket} extends MBE to work on residuated monoids, hence including also the framework of preferences presented in Sect.~\ref{sec:collapsing} and Sect.~\ref{sec:lexico}. The algorithm takes as input a problem $P$ defined as $P = \langle V,D,C\rangle_{\mathit{POM}}$, where $V$ is the set of variables $\{v_1, \dots, v_n\}$, $D$ is a set of domains $\{D_1, \dots, D_n\}$ (where $v_1 \in D_1, \dots, v_n \in D_n$), $C$ is a set of constraints where $\bigcup_{c \in C} \mathit{supp}(c) = V$,\footnote{For instance, a binary constraint $c$ with $\mathit{supp}(c) = \{v_1, v_2\}$ is a function $c : (V \longrightarrow D) \longrightarrow A$ that depends only on the assignment of variables $\{v_1, v_2\} \subseteq V$.} and finally, the problem is given on a residuated SLM. We define a \emph{projection} operator $\Downarrow$ for a constraint $c$ and variable $v$ as $(c\Downarrow_v) = \bigvee_{d \in D_v} c [v:=d].$ Projection decreases the support: $supp(c\Downarrow_v) \subseteq supp({c}) \setminus \{v\}$. In Algorithm~\ref{alg:soft:bucket} we use this operator to eliminate variables from constraints. At line $4$ Algorithm~\ref{alg:soft:bucket} finds bucket $\mathfrak{B}_i$, which contains all the constraints having $v_i$ in their support. Then at line $5$ we find a partition of $\mathfrak{B}_i$ into $p$ mini-buckets $\mathfrak{Q}$ limited by $z$. All the mini-buckets are projected over $v_i$, thus eliminating it from the support and obtaining a new constraint $g_{i,j}$ as result (line $7$). Finally, the bucket $\mathfrak{B}_i$ is discarded from the problem while adding $p$ new constraints $g$ (line $8$). The elimination of the last variable produces an empty-support constraints, whose composition provides the desired upper bound (that is, a solution of $P$ cannot have a better preference than this bound). Bucket elimination is defined in Algorithm~\ref{alg:bucket}. The second part (from line $7$ to $14$) has been modified with respect to the one in e.g~\cite{bucket} in order to manage partially ordered preferences (as POMs can do). Note that the $\cdot$ operator extends an assignment tuple $t$ with a new element. The set $I$ stores all the domain values that produce new undominated tuples, which are saved in $T$. This is repeated for all the assignments in the set of partial solutions, which is finally updated in $\mathit{BSols}$ with not dominated solutions only (line $13$); $g_1$ is the empty-support constraint which represents the (best) preference of such solutions. By having defined residuation on lexicographic orders, it is now possible to use it in order to have an estimation about how far a partitioning is from buckets: we can use ${ \ominus\hspace{-8pt}:}\;$ to compute good bucket partitions, similarly to the method adopted in \cite{bucketsemiring}. Let us consider a partition $\mathfrak{Q} = \{\mathfrak{Q}_1, \mathfrak{Q}_2, \dots, \mathfrak{Q}_p \}$ of a bucket $\mathfrak{B}_i$, which contains all the constraints with variable $v_i$ in the support. We say that $ \mathfrak{Q}$ is a $z$ partition if the support size of its mini-buckets is smaller than $z$, i.e., if $\forall i. |\mathit{supp}(\mathfrak{Q}_i)| \leq z$. The approximation $\mu^\mathfrak{Q}$ of the bucket is computed as \footnotesize $$\mu^\mathfrak{Q} = \bigotimes\limits^{p}_{j=1} \bigg(\left(\bigotimes\limits \mathfrak{Q}_j\right)\Downarrow_{v_i}\bigg)$$ \normalsize \begin{algorithm}[t] \caption{Mini-Bucket for Residuated POMs.} \label{alg:soft:bucket} \scriptsize \hspace*{\algorithmicindent} \textbf{Input:} $P = \langle V,D,C \rangle_{\mathit{POM}}$ and control parameter $z$ \\ \hspace*{\algorithmicindent} \textbf{Output:} An upper bound of $(\bigotimes_{c \in C}) \Downarrow_V$ \begin{algorithmic}[1] \Function{MBE}{} \State $\{v_1, v_2, \dots, v_n\} := \mathit{compute\_order}(P)$ \For{$i = n \textrm{ to } 1$} \State $\mathfrak{B}_i := \{c \in C \mid v_i \in supp(c) \}$ \State $\{\mathfrak{Q}_1, \mathfrak{Q}_2, \dots, \mathfrak{Q}_p\} := \mathit{partition(\mathfrak{B}_i, z)}$ \For{$j = 1 \textrm{ to } p$} \State $g_{i,j} := (\bigotimes_{c\in \mathfrak{Q}_j} c) \Downarrow_{v_i}$ \EndFor \State $C := (C \cup \{g_{i,1}, \dots, g_{i,j}\}) - \mathfrak{B}_i$ \EndFor \State \Return{$(\bigotimes_{c \in C} c)$} \EndFunction \end{algorithmic} \normalsize \end{algorithm} \begin{algorithm}[t] \caption{Bucket for Residuated POMs.} \label{alg:bucket} \scriptsize \hspace*{\algorithmicindent} \textbf{Input:} $P = \langle V,D,C \rangle_{\mathit{POM}}$ \\ \hspace*{\algorithmicindent} \textbf{Output:} The set of best solutions of $P$ \begin{algorithmic}[1] \Function{BE}{} \State $\{v_1, v_2, \dots, v_n\} := \mathit{compute\_order}(P)$ \For{$i = n \textrm{ to } 1$} \State $\mathfrak{B}_i := \{c \in C \mid v_i \in supp(c) \}$ \State $g_{i} := (\bigotimes_{c\in \mathfrak{B}_j} c) \Downarrow_{v_i}$ \State $C := (C \cup \{g_{i}\}) - \mathfrak{B}_i$ \EndFor \State $\mathit{BSols} := \{\langle \rangle\}$ \Comment{The empty tuple} \For{$i = 1 \textrm{ to } |V|$} \State $T = \emptyset$ \ForAll {$t \in \mathit{BSols}$} \State $I := \{ d \mid \nexists d'. (\bigotimes\limits \mathfrak{B}_i) (t \cdot (x_i = d)) < (\bigotimes\limits \mathfrak{B}_i) (t \cdot (x_i = d'))\}$ \State $T := T \cup \{t \cdot (x_i = d) \mid \exists d \in I\}$ \EndFor \State $\mathit{BSols} := T \setminus \{ t \in T \mid \exists t' \in T. (\bigotimes\limits \mathfrak{B}_i) (t) < (\bigotimes\limits \mathfrak{B}_i) (t') \}$ \EndFor \State \Return{$(g_1, \mathit{BSols})$} \EndFunction \end{algorithmic} \normalsize \end{algorithm} It is noteworthy that residuation may help in quantifying the distance between a bucket and its partitioning \footnotesize $$\bigg(\left(\bigotimes\limits \mathfrak{B} \right)\Downarrow_{v_i}\bigg) { \ominus\hspace{-7.45pt}:}\; \left(\bigotimes\limits^{p}_{j=1} \bigg(\left(\bigotimes \mathfrak{Q}_j\right)\Downarrow_{v_i}\bigg)\right)$$ \normalsize We can compute a refined approximation for a mini-bucket $\mathit{app}_{\mathfrak{Q}_j}$ with respect to the partitioned bucket as \footnotesize $$\Bigg(\bigg(\left(\bigotimes\limits \mathfrak{B} \right) { \ominus\hspace{-7.45pt}:}\; \left( \bigotimes\limits (\mathfrak{B} \setminus \mathfrak{Q}_j) \right)\bigg)\Downarrow_{v_i}\Bigg) { \ominus\hspace{-7.45pt}:}\; \bigg(\left(\bigotimes\limits \mathfrak{Q}_j\right)\Downarrow_{v_i}\bigg)$$ \normalsize If we compose this approximation for each mini-bucket we get an approximation between a bucket and its partitioning \footnotesize $$\mathit{approx}_{\mu^\mathfrak{Q}} = \bigotimes\limits_{j} \mathit{approx}_{\mathfrak{Q}_j}$$ \normalsize \subsection{Soft Branch-and-Bound}\label{sec:softbb} Algorithms as MBE can be used to obtain a lower bound that underestimates the best solution of a given problem $P = \langle V,D,C \rangle_{\mathit{POM}}$. This bound can be then passed as input to a search algorithm in order to increase its pruning efficiency~\cite{jheuristics}. In the following of this section, we describe an example of search that can be used to find all the solutions of a (possibly lexicographic) soft CSP. Note that this algorithm is designed to deal with partially ordered solutions. On the contrary, in \cite{schiex} the solution of \emph{Lex-VCSP} (and in general \emph{Valued CSP}s, i.e., \emph{VCSP}s) is associated with a set of totally ordered preferences. The family of \emph{Soft Branch-and-Bound} algorithms explores the state space of a soft CSP as a tree. A \emph{Depth-First Branch-and-Bound} (\emph{DFBB}) (see Algorithm~\ref{alg:soft:bnb}) performs a depth-first traversal of the search tree. Given a partial assignment $t$ of $V$, an upper bound $\mathit{ub}(t)$ is an overestimation of the acceptance degree of any possible complete assignment involving $t$. A lower bound $\mathit{lb}(t)$ is instead a minimum acceptance degree that we are willing to accept during the search. With each node in the search tree is associated a set of variables $X \subseteq V$ that have been already assigned (and the set of unassigned ones is given by $U = V \setminus X$), along with the associated (partial) assignment $t$ to those variables ($\mathit{supp}(t) = X$). A leaf node is associated with a complete assignment ($\mathit{supp}(t) = V$). Each time a new internal node is created, a variable $v_i \in U$ to assign next is chosen, as well as an element $d \in D_{v_i}$ of its domain. Note that the procedure in Algorithm~\ref{alg:soft:bnb} prunes the search space at line $8$, since it only explores those assignments $v_i = d$ such that there exists an upper bound $u \in \mathit{UB}$ that is better than a lower bound $l \in \mathit{LB}$. The efficiency of Soft DFBB depends largely on its pruning capacity, which relies on the quality of its bounds: the higher $\mathit{lb}$ and the lower $\mathit{ub}$ (still ensuring they are actual bounds of optimal solutions), the better Soft DFBB performs. Note that, in order to deal with partial orderings of preferences, Algorithm~\ref{alg:soft:bnb} has to manage sets of undominated upper \emph{UB} and lower \emph{LB} bounds of (partial) solutions, differently from classical Branch-and-Bound. In Algorithm~\ref{alg:soft:bnb}, \emph{LB} returns a set of lower bounds for a given partial assignment. When all the variables are assigned (line $2$), the procedure stops with a solution. \begin{Algorithm}[t]{11cm} \caption{Soft Depth-First Branch-and-Bound.} \label{alg:soft:bnb} \scriptsize \begin{algorithmic}[1] \Function{SoftDFBB}{$t, \mathit{LB}$} \If {$(\mathit{supp}(t) = V)$} \State \Return{$\bigotimes C(t)$} \Else \State \textbf{let} $v_i \in U$ \Comment $U$ is the set of unassigned variables \ForAll{$d \in D_{v_i}$} \State $H:= \mathit{UB}(t \cdot (v_i = d))$ \If {$(\exists u \in H, \exists l \in LB. \: l \leq_{\mathit{POM}} u)$} \State \ $\mathit{LB} := \mathit{LB} \cup \mathtt{SoftDFBB}(t \cdot (v_i = d), \mathit{LB})$ \State $\mathit{LB} := \mathit{LB} \setminus \{e \in \mathit{LB} \mid \exists e' \in \mathit{LB}. e <_{\mathit{POM}} e'\}$ \EndIf \EndFor \State \Return{$LB$} \EndIf \EndFunction \end{algorithmic} \end{Algorithm} \section{Conclusions and Future Works}\label{sec:conclusion} In this paper we considered a formal framework for soft CSP based on a residuated monoid of partially ordered preferences. This allows for using the classical solving algorithms that need some preference removal, as for instance arc consistency where values need to be moved from binary to unary constraints, or for proving a cost estimation to be used during the search for solutions, as for instance branch-and-bound algorithms. The contribution of this paper is twofold. On the one side, we proved the adequacy of the formalism for modelling lexicographic orders. On the other side, we showed how it can enable heuristics for efficiently solving soft CSPs, such as the Nucket and Mini-bucket elimination. Our focus on soft CSP includes its computational counterparts based on constraints, such as soft CCP~\cite{labelled}, and in fact, considering infinite tuples enables to model temporal reasoning as shown for soft constraint automata in \cite{sca}. However, the framework is reminiscent, and is in fact an extension, of previous formalisms such as monotonic logic programming~\cite{residuatedlogic}, whose semantics is given in terms of residuated lattices of complete lattices of truth-values. And it fits in the current interests on the development of sequent systems for substructural logics, as witnessed by current research projects~\cite{ciabattoni}: well-known examples are Lukasiewicz's many-valued logics, relevance logics and linear logics. All the connections sketched above deserve further investigations. For the time being, we leave to future work some related extensions. Mini-bucket is often used for providing an upper bound in branch-and-bound algorithms: for this reason we will investigate this technique, as well as other solving methods used in the solution of lexicographic problems~\cite{freuderlexi}. We will also study ad-hoc heuristics for selecting the order in Algorithm~\ref{alg:soft:bucket}, directly depending on lexicographic orders. \bibliographystyle{splncs03
{'timestamp': '2021-03-12T02:26:58', 'yymm': '2103', 'arxiv_id': '2103.06741', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06741'}
arxiv
\section{Conclusion} This paper presents \textbf{ASAP}, a large-scale Chinese restaurant review dataset towards aspect category sentiment analysis (ACSA) and rating prediction (RP). \textsc{ASAP} consists of $46,730$ restaurant user reviews with star ratings from a leading e-commerce platform in China. Each review is manually annotated according to its sentiment polarities on $18$ fine-grained aspect categories. Besides evaluations of ACSA and RP models on \textsc{ASAP} separately, we also propose a joint model to address ACSA and RP synthetically, which outperforms other state-of-the-art baselines considerably. we hope the release of \textsc{ASAP} could push forward related researches and applications. \clearpage \section{Introduction} With the rapid development of e-commerce, massive user reviews available on e-commerce platforms are becoming valuable resources for both customers and merchants. Aspect-based sentiment analysis(ABSA) on user reviews is a fundamental and challenging task which attracts interests from both academia and industries~\citep{hu2004mining,ganu2009beyond,jo2011aspect,kiritchenko2014nrc}. According to whether the aspect terms are explicitly mentioned in texts, ABSA can be further classified into aspect term sentiment analysis (ATSA) and aspect category sentiment analysis (ACSA), we focus on the latter which is more widely used in industries. Specifically, given a review "Although the fish is delicious, the waiter is horrible!", the ACSA task aims to infer the sentiment polarity over aspect category \textit{food} is positive while the opinion over the aspect category \textit{service} is negative. The user interfaces of e-commerce platforms are more intelligent than ever before with the help of ACSA techniques. For example, \autoref{fig:dianping} presents the detail page of a coffee shop on a popular e-commerce platform in China. The upper aspect-based sentiment text-boxes display the aspect categories (e.g., \textit{food}, \textit{sanitation}) mentioned frequently in user reviews and the aggregated sentiment polarities on these aspect categories (the orange ones represent positive and the blue ones represent negative). Customers can focus on corresponding reviews effectively by clicking the aspect-based sentiment text-boxes they care about (e.g., the orange filled text-box ``\begin{CJK*}{UTF8}{gkai}卫生条件好\end{CJK*}'' (\textit{good sanitation})). Our user survey based on $7,824$ valid questionnaires demonstrates that $80.08\%$ customers agree that the aspect-based sentiment text-boxes are helpful to their decision-making on restaurant choices. Besides, the merchants can keep track of their cuisines and service qualities with the help of the aspect-based sentiment text-boxes. Most Chinese e-commerce platforms such as Taobao\footnote{\url{https://www.taobao.com/}}, Dianping\footnote{\url{https://www.dianping.com/}}, and Koubei\footnote{\url{https://www.koubei.com/}} deploy the similar user interfaces to improve user experience. Users also publish their overall $5$-star scale ratings together with reviews. \autoref{fig:dianping} displays a sample of $5$-star rating to the coffee shop. In comparison to fine-grained aspect sentiment, the overall review rating is usually a coarse-grained synthesis of the opinions on multiple aspects. Rating prediction(RP)~\citep{jin2016jointly,li-etal-2018-document,wu2019arp} which aims to predict the “seeing stars” of reviews also has wide applications. For example, to promise the aspect-based sentiment text-boxes accurate, unreliable reviews should be removed before ACSA algorithms are performed. Given a piece of user review, we can predict a rating for it based on the overall sentiment polarity underlying the text. We assume the predicted rating of the review should be consistent with its ground-truth rating as long as the review is reliable. If the predicted rating and the user rating of a review disagree with each other explicitly, the reliability of the review is doubtful. \autoref{fig:review-rating} demonstrates an example review of low-reliability. In summary, RP can help merchants to detect unreliable reviews. Therefore, both ACSA and RP are of great importance for business intelligence in e-commerce, and they are highly correlated and complementary. ACSA focuses on predicting its underlying sentiment polarities on different aspect categories, while RP focuses on predicting the user's overall feelings from the review content. We reckon these two tasks are highly correlated and better performance could be achieved by considering them jointly. As far as we know, current public datasets are constructed for ACSA and RP separately, which limits further joint explorations of ACSA and RP. To address the problem and advance the related researches, this paper presents a large-scale Chinese restaurant review dataset for \textbf{A}spect category \textbf{S}entiment \textbf{A}nalysis and rating \textbf{P}rediction, denotes as \textbf{ASAP} for short. All the reviews in ASAP are collected from the aforementioned e-commerce platform. There are $46,730$ restaurant reviews attached with $5$-star scale ratings. Each review is manually annotated according to its sentiment polarities towards $18$ fine-grained aspect categories. To the best of our knowledge, ASAP is the largest Chinese large-scale review dataset towards both ACSA and RP tasks. We implement several state-of-the-art (SOTA) baselines for ACSA and RP and evaluate their performance on ASAP. To make a fair comparison, we also perform ACSA experiments on a widely used SemEval-2014 restaurant review dataset~\citep{SemEval2014}. Since BERT~\citep{Devlin2018BERTPO} has achieved great success in several natural language understanding tasks including sentiment analysis~\citep{xu2019bert,sun2019utilizing,mams}, we propose a joint model that employs the fine-to-coarse semantic capability of BERT. Our joint model outperforms the competing baselines on both tasks. \begin{figure}[htb] \centering \includegraphics[height=0.25\textwidth]{figs/AspectSelect_new_en_no_pic.pdf} \caption{The user interface of a coffee shop on a popular e-commerce App. The top aspect-based sentiment text-boxes display aspect categories and sentiment polarities. The orange text-boxes are positive, while the blue ones are negative. The reviews mentioning the clicked aspect category (e.g., \textit{good sanitation}) with ratings are shown below. The text spans mentioning the aspect categories are also highlighted.} \label{fig:dianping} \end{figure} \begin{figure}[htb] \centering \includegraphics[width=0.45\textwidth]{figs/rating-disagreement_review.pdf} \caption{A content-rating disagreement case. The review holds a $2$-star rating while all the mentioned aspects are super positive.} \label{fig:review-rating} \end{figure} Our main contributions can be summarized as follows. (1) We present a large-scale Chinese review dataset towards aspect category sentiment analysis and rating prediction, named as \textsc{ASAP}, including as many as $46,730$ real-world restaurant reviews annotated from $18$ pre-defined aspect categories. Our dataset has been released at \url{https://github.com/Meituan-Dianping/asap}. (2) We explore the performance of widely used models for ACSA and RP on \textsc{ASAP}. (3) We propose a joint learning model for ACSA and RP tasks. Our model achieves the best results both on \textsc{ASAP} and SemEval \textsc{Restaurant} datasets. \section{Related Work and Datasets} \textbf{Aspect Category Sentiment Analysis.} ACSA~\citep{Zhou2015Representation,Movahedi2019Aspect,Ruder2016A,can} aims to predict sentiment polarities on all aspect categories mentioned in the text. The series of SemEval datasets consisting of user reviews from e-commerce websites have been widely used and pushed forward related research~\citep{ATAE,IAN,xu2019bert,sun2019utilizing,mams}. The SemEval-2014 task-4 dataset (SE-ABSA14)~\citep{SemEval2014} is composed of laptop and restaurant reviews. The restaurant subset includes $5$ aspect categories (i.e., \textit{Food}, \textit{Service}, \textit{Price}, \textit{Ambience} and \textit{Anecdotes/Miscellaneous}) and $4$ polarity labels (i.e., \textit{Positive}, \textit{Negative}, \textit{Conflict} and \textit{Neutral}). The laptop subset is not suitable for ACSA. The SemEval-2015 task-12 dataset (SE-ABSA15)~\citep{SemEval2015} builds upon SE-ABSA14 and defines its aspect category as a combination of an entity type and an attribute type(e.g., \textit{Food\#Style\_Options}). The SemEval-2016 task-5 dataset (SE-ABSA16)~\citep{SemEval2016} extends SE-ABSA15 to new domains and new languages other than English. MAMS~\citep{mams} tailors SE-ABSA14 to make it more challenging, in which each sentence contains at least two aspects with different sentiment polarities. Compared with the prosperity of English resources, high-quality Chinese datasets are not rich enough. ``ChnSentiCorp''~\citep{tan2008empirical}, ``IT168TEST''~\citep{zagibalov2008unsupervised}, ``Weibo''\footnote{\url{http://tcci.ccf.org.cn/conference/2014/pages/page04\_dg.html}}, ``CTB''~\citep{li2014recursive} are $4$ popular Chinese datasets for general sentiment analysis. However, aspect category information is not annotated in these datasets. ~\citet{zhao2014creating} presents two Chinese ABSA datasets for consumer electronics (mobile phones and cameras). Nevertheless, the two datasets only contain $400$ documents ($\sim4000$ sentences), in which each sentence only mentions one aspect category at most. BDCI\footnote{\url{https://www.datafountain.cn/competitions/310}} automobile opinion mining and sentiment analysis dataset~\citep{dai2019multi} contains $8, 290$ user reviews in automobile industry with $10$ pre-defined categories. ~\citet{peng2017review} summarizes available Chinese ABSA datasets. While most of them are constructed through rule-based or machine learning-based approaches, which inevitably introduce additional noise into the datasets. Our ASAP excels above Chinese datasets both on quantity and quality. \noindent \textbf{Rating Prediction.} Rating prediction (RP) aims to predict the “seeing stars” of reviews, which represent the overall ratings of reviews. In comparison to fine-grained aspect sentiment, the overall review rating is usually a coarse-grained synthesis of the opinions on multiple aspects. ~\citet{ganu2009beyond, li2011incorporating,chen2018neural} form this task as a text classification or regression problem. Considering the importance of opinions on multiple aspects in reviews, recent years have seen numerous work~\citep{jin2016jointly, cheng2018aspect,li-etal-2018-document,wu2019arp} utilizing the information of the aspects to improve the rating prediction performance. This trending also inspires the motivation of ASAP. Most RP datasets are crawled from real-world review websites and created for RP specifically. Amazon Product Review English dataset~\citep{mcauley2013hidden} containing product reviews and metadata from Amazon has been widely used for RP~\citep{cheng2018aspect,mcauley2013hidden}. Another popular English dataset comes from Yelp Dataset Challenge 2017\footnote{\url{http://www.yelp.com/dataset\_challenge/}}, which includes reviews of local businesses in $12$ metropolitan areas across $4$ countries. Openrice\footnote{\url{https://www.openrice.com}} is a Chinese RP dataset composed of $168,142$ reviews. Both the English and Chinese datasets don't annotate fine-grained aspect category sentiment polarities. \section{Dataset Collection and Analysis} \label{sec:dataset} \subsection{Data Construction \& Curation} We collect reviews from one of the most popular O2O e-commerce platforms in China, which allows users to publish coarse-grained star ratings and writing fine-grained reviews to restaurants (or places of interest) they have visited. In the reviews, users comment on multiple aspects either explicitly or implicitly, including \textit{ambience},\textit{price}, \textit{food}, \textit{service}, and so on. First, we retrieve a large volume of user reviews from popular restaurants holding more than $50$ user reviews randomly. Then, $4$ pre-processing steps are performed to promise the ethics, quality, and reliability of the reviews. (1) User information (e.g., user-ids, usernames, avatars, and post-times) are removed due to privacy considerations. (2) Short reviews with less than $50$ Chinese characters, as well as lengthy reviews with more than $1000$ Chinese characters are filtered out. (3) If the ratio of non-Chinese characters within a review is over $70$\%, the review is discarded. (4) To detect the low-quality reviews (e.g., advertising texts), we build a BERT-based classifier with an accuracy of $97\%$ in a leave-out test-set. The reviews detected as low-quality by the classifier are discarded too. \subsection{Aspect Categories} Since the reviews already hold users' star ratings, this section mainly introduces our annotation details for ACSA. In SE-ABSA14 restaurant dataset (denoted as \textsc{Restaurant} for simplicity), there are $5$ coarse-grained aspect categories, including \textit{food}, \textit{service}, \textit{price}, \textit{ambience} and \textit{miscellaneous}. After an in-depth analysis of the collected reviews, we find the aspect categories mentioned by users are rather diverse and fine-grained. Take the text ``...The restaurant holds a high-end decoration but is quite noisy since a wedding ceremony was being held in the main hall... (\begin{CJK*}{UTF8}{gkai}...环境看起来很高大上的样子,但是因为主厅在举办婚礼非常混乱,感觉特别吵...\end{CJK*})'' in \autoref{tb:dataset} for example, the reviewer actually expresses opposite sentiment polarities on two fine-grained aspect categories related to \textit{ambience}. The restaurant's decoration is very high-end (\textit{Positive}), while it's very noisy due to an ongoing ceremony (\textit{Negative}). Therefore, we summarize the frequently mentioned aspects and refine the $5$ coarse-grained categories into $18$ fine-grained categories. We replace \textit{miscellaneous} with \textit{location} since we find users usually review the restaurants' location (e.g., whether the restaurant is easy to reach by public transportation.). We denote the aspect category as the form of ``\textit{Coarse-grained Category\#Fine-grained Categoty}'', such as ``\textit{Food\#Taste}'' and ``\textit{Ambience\#Decoration}''. The full list of aspect categories and definitions are listed in \autoref{tb:full-list}. \begin{table*}[htb] \small \center \caption{The full list of $18$ aspect categories and definitions.} \begin{tabular}{p{0.25\textwidth}p{0.20\textwidth}p{0.25\textwidth}p{0.20\textwidth}} \hline Aspect category & Definition & Aspect category & Definition \\ \hline \parbox{0.25\textwidth}{\textit{Food\#Taste}\\ (\begin{CJK*}{UTF8}{gkai}口味\end{CJK*})} & Food taste & \parbox{0.25\textwidth}{\textit{Location\#Easy\_to\_find}\\(\begin{CJK*}{UTF8}{gkai}是否容易寻找\end{CJK*})} & Whether the restaurant is easy to find \\ \parbox{0.25\textwidth}{\textit{Food\#Appearance}\\(\begin{CJK*}{UTF8}{gkai}外观\end{CJK*})} & Food appearance & \parbox{0.25\textwidth}{\textit{Service\#Queue}\\(\begin{CJK*}{UTF8}{gkai}排队时间\end{CJK*})} & Whether the queue time is acceptable \\ \parbox{0.25\textwidth}{\textit{Food\#Portion}\\ (\begin{CJK*}{UTF8}{gkai}分量\end{CJK*})} & Food portion & \parbox{0.25\textwidth}{\textit{Service\#Hospitality}\\ (\begin{CJK*}{UTF8}{gkai}服务人员态度\end{CJK*})} & Waiters/waitresses' attitude/hospitality \\ \parbox{0.25\textwidth}{\textit{Food\#Recommend}\\(\begin{CJK*}{UTF8}{gkai}推荐程度\end{CJK*})} & Whether the food is worth being recommended & \parbox{0.25\textwidth}{\textit{Service\#Parking}\\(\begin{CJK*}{UTF8}{gkai}停车方便\end{CJK*})} & Parking convenience \\ \parbox{0.25\textwidth}{\textit{Price\#Level}\\(\begin{CJK*}{UTF8}{gkai}价格水平\end{CJK*})} & Price level & \parbox{0.25\textwidth}{\textit{Service\#Timely}\\(\begin{CJK*}{UTF8}{gkai}点菜/上菜速度\end{CJK*})} & Order/Serving time \\ \parbox{0.25\textwidth}{\textit{Price\#Cost\_effective}\\(\begin{CJK*}{UTF8}{gkai}性价比\end{CJK*})} & Whether the restaurant is cost-effective & \parbox{0.25\textwidth}{\textit{Ambience\#Decoration}\\(\begin{CJK*}{UTF8}{gkai}装修\end{CJK*})} & Decoration level \\ \parbox{0.25\textwidth}{\textit{Price\#Discount}\\(\begin{CJK*}{UTF8}{gkai}折扣力度\end{CJK*})} & Discount strength & \parbox{0.25\textwidth}{\textit{Ambience\#Noise}\\(\begin{CJK*}{UTF8}{gkai}嘈杂情况\end{CJK*})} & Whether the restaurant is noisy \\ \parbox{0.25\textwidth}{\textit{Location\#Downtown}\\(\begin{CJK*}{UTF8}{gkai}位于商圈附近\end{CJK*})} & Whether the restaurant is located near downtown & \parbox{0.25\textwidth}{\textit{Ambience\#Space}\\ (\begin{CJK*}{UTF8}{gkai}就餐空间\end{CJK*})} & Dining Space and Seat Size \\ \parbox{0.25\textwidth}{\textit{Location\#Transportation}\\(\begin{CJK*}{UTF8}{gkai}交通方便\end{CJK*})} & Convenient public transportation to the restaurant & \parbox{0.25\textwidth}{\textit{Ambience\#Sanitary}\\(\begin{CJK*}{UTF8}{gkai}卫生情况\end{CJK*})} & Sanitary condition \\ \hline \end{tabular} \label{tb:full-list} \end{table*} \subsection{Annotation Guidelines \& Process} Bearing in mind the pre-defined $18$ aspects, assessors are asked to annotate sentiment polarities towards the mentioned aspect categories of each review. Given a review, when an aspect category is mentioned within the review either explicitly and implicitly, the sentiment polarity over the aspect category is labeled as $1$ (\textit{Positive}), $0$ (\textit{Neutral}) or $-1$ (\textit{Negative}) as shown in \autoref{tb:dataset}. We hire $20$ vendor assessors, $2$ project managers, and $1$ expert reviewer to perform annotations. Each assessor needs to attend a training to ensure their intact understanding of the annotation guidelines. Three rounds of annotation are conducted sequentially. First, we randomly split the whole dataset into $10$ groups, and every group is assigned to $2$ assessors to annotate independently. Second, each group is split into $2$ subsets according to the annotation results, denoted as \textbf{Sub-Agree} and \textbf{Sub-Disagree}. \textbf{Sub-Agree} comprises the data examples with agreement annotation, and \textbf{Sub-Disagree} comprises the data examples with disagreement annotation. \textbf{Sub-Agree} will be reviewed by assessors from other groups. The controversial examples during the review are considered as difficult cases. \textbf{Sub-Disagree} will be reviewed by the $2$ project managers independently and then discuss to reach an agreement annotation. The examples that could not be addressed after discussions are also considered as difficult cases. Third, for each group, the difficult examples from two subsets are delivered to the expert reviewer to make a final decision. More details of difficult cases and annotation guidelines during annotation are demonstrated in \autoref{tb:difficult-cases}. \begin{table*}[htb] \small \centering \caption{Difficult cases and annotation guidelines.} \begin{tabular}{P{0.15\textwidth}P{0.2\textwidth}P{0.2\textwidth}P{0.2\textwidth}P{0.15\textwidth}} \hline Category & Example & Example (Translation) & Guideline & Annotation \\ \hline Change of sentiment over time & \begin{CJK*}{UTF8}{gkai}我之前挺喜欢这家餐厅的饭菜,不过今天的饭菜可不怎么样.\end{CJK*} & I used to like the food of this restaurant, but the taste is not as expected today. & When there existed a sentiment drifting over time in the review, the most recent sentiment polarity is adopted. & (\textit{Food\#Taste}, $-1$) \\ Implicit sentiment polarity & \begin{CJK*}{UTF8}{gkai}比五星级酒店的餐厅差远了,而且在五星级酒店中餐厅里两个人吃一顿也就$500$左右就够了\end{CJK*} & The restaurant was far worse than the dinning hall of any five-star hotel, considering that the meal for two people only cost $500$ CNY in a five-star hotel. & Some reviewers express their polarities in an implicit manner instead of expressing their feelings directly. The implicit sentiment polarity is adopted to complete the annotation. & (\textit{Price\#Level}, $-1$) \\ Conflict opinions & \begin{CJK*}{UTF8}{gkai}这道菜有点咸,但是味道很赞。\end{CJK*} & This dish was a bit salty, but it tasted great. & When there existed multiple sentiment polarities toward the same aspect-category, the dominant sentiment is chosen. & (\textit{Food\#Taste}, $1$) \\ Mild sentiment & \begin{CJK*}{UTF8}{gkai} 饭菜还可以,不过也算不上特别好吃。\end{CJK*} & The food was okay, but nothing great. & The “neutral” label applies to mildly positive or mildly negative sentiment & (\textit{Food\#Taste}, $0$) \\ Irrelevant restaurant & \begin{CJK*}{UTF8}{gkai} 上次去的一家店很难吃,今天来了这家新的,感觉很好吃。\end{CJK*} & The food of the shop which I went to last time was very bad. Today I came to this new one. I felt very good. & The review mentions restaurant that the user has visited in the past. We only focus on the restaurant being reviewed & (\textit{Food\#Taste}, $1$) \\ \hline \end{tabular} \label{tb:difficult-cases} \end{table*} Finally, \textsc{ASAP} corpus consists of $46,730$ pieces of real-world user reviews, and we split it into a training set ($36,850$), a validation set ($4,940$) and a test set ($4,940$) randomly. \autoref{tb:dataset} presents an example review of \textsc{ASAP} and corresponding annotations on the $18$ aspect categories. \begin{table*}[htb] \renewcommand\arraystretch{3.8} \small \centering \caption{A review example in \textsc{ASAP}, with overall star rating and aspect category sentiment polarity annotations.}\label{tb:dataset} \begin{tabular}{M{0.42\textwidth}cM{0.15\textwidth}cM{0.15\textwidth}c} \hline Review & Rating & Aspect Category & Label & Aspect Category & Label \\ \hline \multirow{9}{*}{\parbox{0.42\textwidth}{With convenient traffic, the restaurant holds a high-end decoration, but quite noisy because a wedding ceremony was being held in the main hall. Impressed by its delicate decoration and grand appearance though, we had to wait for a while at the weekend time. However, considering its high price level, the taste is unexpected. We ordered the Kung Pao Prawn, the taste was acceptable and the serving size is enough, but the shrimp is not fresh. In terms of service, you could not expect too much due to the massive customers there. By the way, the free-served fruit cup was nice. Generally speaking, it was a typical wedding banquet restaurant rather than a comfortable place to date with friends. \\ \\ \begin{CJK*}{UTF8}{gkai} 交通还挺方便的,环境看起来很高大上的样子,但是因为主厅在举办婚礼非常混乱,特别吵感觉,但是装修的还不错,感觉很精致的装修,门面很气派,周末去的时候还需要等位。味道的话我觉得还可以但是跟价格比起来就很一般了,性价比挺低的,为了去吃宫保虾球的,但是我觉得也就那样吧虾不是特别新鲜,不过虾球很大,味道还行。服务的话由于人很多所以也顾不过来上菜的速度不快,但是有送水果杯还挺好吃的。总之就是典型的婚宴餐厅不是适合普通朋友吃饭的地方了。\end{CJK*} }} & \multirow{9}{*}{$3$-Star} & \parbox{0.15\textwidth}{\textit{Location\#Transportation}\\(\begin{CJK*}{UTF8}{gkai}交通方便\end{CJK*})} & $1$ & \parbox{0.15\textwidth}{\textit{Price\#Discount}\\ (\begin{CJK*}{UTF8}{gkai}折扣力度\end{CJK*}) } & - \\ & & \parbox{0.15\textwidth}{\textit{Location\#Downtown} \\ (\begin{CJK*}{UTF8}{gkai}位于商圈附近\end{CJK*}) } & - & \parbox{0.15\textwidth}{\textit{Ambience\#Decoration}\\ (\begin{CJK*}{UTF8}{gkai}装修\end{CJK*})} & $1$ \\ & & \parbox{0.15\textwidth}{\textit{Location\#Easy\_to\_find}\\ (\begin{CJK*}{UTF8}{gkai}是否容易寻找\end{CJK*} )} & - & \parbox{0.15\textwidth}{\textit{Ambience\#Noise}\\ (\begin{CJK*}{UTF8}{gkai}嘈杂情况\end{CJK*})} & $-1$ \\ & & \parbox{0.15\textwidth}{\textit{Service\#Queue}\\ (\begin{CJK*}{UTF8}{gkai}排队时间\end{CJK*})} & - & \parbox{0.15\textwidth}{\textit{Ambience\#Space}\\ (\begin{CJK*}{UTF8}{gkai}就餐空间\end{CJK*})} & $1$ \\ & & \parbox{0.15\textwidth}{\textit{Service\#Hospitality}\\ (\begin{CJK*}{UTF8}{gkai}服务人员态度\end{CJK*})} & - & \parbox{0.15\textwidth}{\textit{Ambience\#Sanitary}\\ (\begin{CJK*}{UTF8}{gkai}卫生情况\end{CJK*})} & - \\ & & \parbox{0.15\textwidth}{\textit{Service\#Parking}\\ (\begin{CJK*}{UTF8}{gkai}停车方便\end{CJK*})} & - & \parbox{0.15\textwidth}{\textit{Food\#Portion}\\ (\begin{CJK*}{UTF8}{gkai}分量\end{CJK*})} & $1$ \\ & & \parbox{0.15\textwidth}{\textit{Service\#Timely}\\ (\begin{CJK*}{UTF8}{gkai}点菜/上菜速度\end{CJK*})} & $-1$ & \parbox{0.15\textwidth}{\textit{Food\#Taste}\\ (\begin{CJK*}{UTF8}{gkai}口味\end{CJK*})} & $1$ \\ & & \parbox{0.15\textwidth}{\textit{Price\#Level}\\(\begin{CJK*}{UTF8}{gkai}价格水平\end{CJK*})} & $0$ & \parbox{0.15\textwidth}{\textit{Food\#Appearance}\\(\begin{CJK*}{UTF8}{gkai}外观\end{CJK*})} & - \\ & & \parbox{0.15\textwidth}{\textit{Price\#Cost\_effective}\\ (\begin{CJK*}{UTF8}{gkai}性价比\end{CJK*})} & $-1$ & \parbox{0.15\textwidth}{\textit{Food\#Recommend}\\ (\begin{CJK*}{UTF8}{gkai}推荐程度\end{CJK*})} & - \\ \hline \end{tabular} \label{tb:dataset} \end{table*} \subsection{Dataset Analysis} \autoref{fig:cate_dist} presents the distribution of $18$ aspect categories in \textsc{ASAP}. Because \textsc{ASAP} concentrates on the domain of restaurant, $94.7$\% reviews mention \textit{Food\#Taste} as expected. Users also pay great attention to aspect categories such as \textit{Service\#Hospitality}, \textit{Price\#Level} and \textit{Ambience\#Decoration}. The distribution proves the advantages of \textsc{ASAP}, as users' fine-grained preferences could reflect the pros and cons of restaurants more precisely. The statistics of \textsc{ASAP} are presented in \autoref{tb:distribution}. We also include a tailored SE-ABSA14 \textsc{Restaurant} dataset for reference. Please note that we remove the reviews holding aspect categories with sentiment polarity of ``conflict'' from the original \textsc{Restaurant} dataset. \begin{table*}[htb] \small \center \caption{The statistics and label/rating distribution of \textsc{ASAP} and \textsc{Restaurant}. The review length are counted by Chinese characters and English words respectively. The sentences are segmented with periods in \textsc{ASAP}{}, while \textsc{Restaurant} is a sentence-level dataset.} \scalebox{0.75}{ \begin{tabular}{M{0.1\textwidth}ccM{0.1\textwidth}M{0.1\textwidth}M{0.05\textwidth}M{0.05\textwidth}ccccccc} \hline Dataset & Split & Reviews & \parbox{0.1\textwidth}{\centering Average \\sentences\\per review} & \parbox{0.1\textwidth}{\centering Average\\aspects\\ per review} & \parbox{0.05\textwidth}{\centering Average\\length} & Positive & Negative & Neutral & $1$-star & $2$-star & $3$-star & $4$-star & $5$-star \\ \hline \multirow{3}{*}{\textsc{ASAP}} & Train & $36,850$ & $8.6$ & $5.8$ & $319.7$ & $133,721$ & $27,425$ & $52,225$ & $1,219$ & $1,258$ & $5,241$ & $13,362$ & $15,770$ \\ & Dev & $4,940$ & $8.7$ & $5.9$ & $319.9$ & $18,176$ & $3,733$ & $7,192$ & $151$ & $166$ & $784$ & $1,734$ & $2,105$ \\ & Test & $4,940$ & $8.3$ & $5.7$ & $317.1$ & $17,523$ & $3,813$ & $7,026$ & $165$ & $173$ & $717$ & $1,867$ & $2,018$ \\ \hline \multirow{2}{*}{\textsc{Restaurant}} & Train & $2,855$ & $1$ & $1.2$ & $15.2$ & $2150$ & $822$& $498$ & - & - & - & - & - \\ & Test & $749$ & $1$ & $1.3$ & $15.6$ &$645$ & $215$ & $94$ & - & - & - & - & - \\ \hline \end{tabular}} \label{tb:distribution} \end{table*} \begin{figure*}[!t] \centering \vspace{-0.3cm} \includegraphics[width=0.95\linewidth]{figs/cate_distribution_all_sentiment.pdf} \vspace{-0.2cm} \caption{The distribution of $18$ fine-grained aspect categories in \textsc{ASAP}.} \label{fig:cate_dist} \end{figure*} Compared with \textsc{Restaurant}, \textsc{ASAP} excels in the quantities of training instances, which supports the exploration of recent data-intensive deep neural models. \textsc{ASAP} is a review-level dataset, while \textsc{Restaurant} is a sentence-level dataset. The average length of reviews in \textsc{ASAP} is much longer, thus the reviews tend to contain richer aspect information. In \textsc{ASAP}, the reviews contain $5.8$ aspect categories in average, which is $4.7$ times of \textsc{Restaurant}. Both review-level ACSA and RP are more challenging than their sentence-level counterparts. Take the review in \autoref{tb:dataset} for example, the review contains several sentiment polarities towards multiple aspect categories. In addition to aspect category sentiment annotations, \textsc{ASAP} also includes overall user ratings for reviews. With the help of \textsc{ASAP}, ACSA and RP can be further optimized either separately or jointly. \section{Methodology} \label{sec:method} \subsection{Problem Formulation} We use $D$ to denote the collection of user review corpus in the training data. Given a review $R$ which consists of a series of words: $\{w_1,w_2,...,w_Z\}$, ACSA aims to predict the sentiment polarity $y_i \in \{Positive, Neutral, Negative\}$ of review $R$ with respect to the mentioned aspect category $a_i$, $i \in \{1,2,..., N\}$. $Z$ denotes the length of review $R$. $N$ is the number of pre-defined aspect categories (i.e., $18$ in this paper). Suppose there are $K$ mentioned aspect categories in $R$. We define a mask vector $[p_1,p_2,...,p_N]$ to indicate the occurrence of aspect categories. When the aspect category $a_i$ is mentioned in $R$, $p_i = 1$, otherwise $p_i = 0$. So we have $\sum_{i=1}^N p_i = K$. In terms of RP, it aims to predict the $5$-star rating score of $g$, which represents the overall rating of the given review $R$. \subsection{Joint Model} Given a user review, ACSA focuses on predicting its underlying sentiment polarities on different aspect categories, while RP focuses on predicting the user's overall feelings from the review content. We reckon these two tasks are highly correlated and better performance could be achieved by considering them jointly. The advent of BERT has established the success of the ``pre-training and then fine-tuning'' paradigm for NLP tasks. BERT-based models have achieved impressive results in ACSA~\citep{xu2019bert,sun2019utilizing,mams}. Review rating prediction can be deemed as a single-sentence classification (regression) task, which could also be addressed with BERT. Therefore, we propose a joint learning model to address ACSA and RP in a multi-task learning manner. Our joint model employs the fine-to-coarse semantic representation capability of the BERT encoder. \autoref{fig:framework} illustrates the framework of our joint model. \noindent\textbf{ACSA} As shown in \autoref{fig:framework}, the token embeddings of the input review are generated through a shared BERT encoder. Briefly, let $H \in \mathbb{R}^{d*Z}$ be the matrix consisting of token embedding vectors $\{h_1,...,h_Z\}$ that BERT produces, where $d$ is the size of hidden layers and $Z$ is the length of the given review. Since different aspect category information is dispersed across the content of $R$, we add an attention-pooling layer~\citep{ATAE} to aggregate the related token embeddings dynamically for every aspect category. The attention-pooling layer helps the model focus on the tokens most related to the target aspect categories. \begin{equation} M_i^a = \tanh(W_i^a*H) \end{equation} \begin{equation} \alpha_i = softmax(\omega_i^T*M_i^a) \end{equation} \begin{equation} r_i = \tanh(W_i^{p}*H*\alpha_i^T) \end{equation} Where $W_i^a \in \mathbb{R}^{d*d}$, $M_i^a \in \mathbb{R}^{d*Z}$, $\omega_i \in \mathbb{R}^d$, $\alpha_i \in \mathbb{R}^Z, W_i^{p} \in \mathbb{R}^{d*d}$, and $r_i \in \mathbb{R}^d$. $\alpha_i$ is a vector consisting of attention weights of all tokens which can selectively attend the regions of the aspect category related tokens, and $r_i$ is the attentive representation of review with respect to the $i_{th}$ aspect category $a_i$, $i \in \{1,2,..., N\}$. Then we have \begin{equation} \hat{y}_i = softmax(W_i^{q}*r_i+b_i^{q}) \end{equation} Where $W_i^{q} \in \mathbb{R}^{C*d}$ and $b_i^{q} \in \mathbb{R}^{C}$ are trainable parameters of the softmax layer. $C$ is the number of labels (i.e, $3$ in our task). Hence, the ACSA loss for a given review $R$ is defined as follows, \begin{equation} loss_{ACSA} = \frac{1}{K}\sum_{i=1}^N p_i \sum_{C}y_i*\log{\hat{y}_i} \end{equation} If the aspect category $a_i$ is not mentioned in $S$, $y_i$ is set as a random value. The $p_i$ serves as a gate function, which filters out the random $y_i$ and ensures only the mentioned aspect categories can participate in the calculation of the loss function. \begin{figure}[!t] \centering \includegraphics[width=0.85\linewidth]{figs/2020CIKM_model_architecture.pdf} \caption{The framework of the proposed joint learning model. The right part of the dotted vertical line is used to predict multiple aspect category sentiment polarities, while the left part is used to predict the review rating.} \label{fig:framework} \end{figure} \noindent\textbf{Rating Prediction} Since the objective of RP is to predict the review rating based on the review content, we adopt the [CLS] embedding $h_{[cls]} \in \mathbb{R}^d$ BERT produces as the representation of the input review, where $d$ is the size of hidden layers in the BERT encoder. \begin{equation} \hat{g} =\beta^T* \tanh(W^r*h_{[cls]} + b^r) \end{equation} Hence the RP loss for a given review $R$ is defined as follows, \begin{equation} loss_{RP} = |g - \hat{g}| \end{equation} Where $W^{r} \in \mathbb{R}^{d*d}$,$b^{r} \in \mathbb{R}^{d}$, $\beta \in \mathbb{R}^d$ are trainable parameters. The final loss of our joint model becomes as follows. \begin{equation} loss = loss_{ACSA} + loss_{RP} \end{equation} \section{Experiments} \label{sec:experiment} We perform an extensive set of experiments to evaluate the performance of our joint model on \textsc{ASAP}{} and \textsc{Restaurant}~\citep{SemEval2014}. Ablation studies are also conducted to probe the interactive influence between ACSA and RP. \subsection{ACSA} \begin{table*}[htp] \small \centering \caption{The experimental results of ACSA models on \textsc{ASAP} and \textsc{Restaurant}. Best scores are boldfaced. }\label{tb:exp-result} \begin{tabular}{llcccc} \hline \multirow{2}{*}{Category}& \multirow{2}{*}{Model} & \multicolumn{2}{c}{\textsc{ASAP}} & \multicolumn{2}{c}{\textsc{Restaurant}} \\ \cline{3-6} & & Macro-F1 & Acc. & Macro-F1 & Acc. \\ \hline \multirow{4}{*}{Non-BERT-based models} & TextCNN~\citep{kim2014convolutional} & $60.41\%$ & $71.10\%$ & $70.56\%$ & $82.29\%$ \\ & BiLSTM+Attn~\citep{zhou2016attention} & $70.53\%$ & $77.78\%$ & $70.85\%$ & $81.97\%$ \\ & ATAE\_LSTM~\citep{ATAE} & $76.60\%$ & $81.94\%$ & $70.15\%$ & $82.12\%$ \\ & CapsNet~\citep{capsnet} & $75.54\%$ & $81.66\%$ & $71.84\%$ & $82.63\%$ \\ \hline \multirow{3}{*}{BERT-based models} & Vanilla-BERT~\citep{Devlin2018BERTPO} & $79.18\%$ & $84.09\%$ & $79.22\%$ & $87.63\%$ \\ & QA-BERT~\citep{sun2019utilizing} & $79.44\%$ & $83.92\%$ & $80.89\%$ & $88.89\%$ \\ & CapsNet-BERT~\citep{mams} & $78.92\%$ & $83.74\%$ & $80.94\%$ & $89.00\%$ \\ & Joint Model (w/o RP) & $80.75\%$ & $85.15\%$ & $\mathbf{82.01\%}$ & $\mathbf{89.62\%}$ \\ & Joint Model & $\mathbf{80.78\%}$ & $\mathbf{85.19\%}$ & - & - \\ \hline \end{tabular} \end{table*} \noindent \textbf{Baseline Models} We implement several ACSA baselines for comparison. According to the different structures of their encoders, these models are classified into Non-BERT based models or BERT-based models. Non-BERT based models include TextCNN~\citep{kim2014convolutional}, BiLSTM+Attn~\citep{zhou2016attention}, ATAE-LSTM~\citep{ATAE} and CapsNet~\citep{capsnet}. BERT-based models include vanilla BERT~\citep{Devlin2018BERTPO}, QA-BERT~\citep{sun2019utilizing} and CapsNet-BERT~\citep{mams}. \noindent \textbf{Implementation Details of Experimental Models } In terms of non-BERT-based models, we initialize their inputs with pre-trained embeddings. For Chinese \textsc{ASAP}, we utilize Jieba\footnote{\url{https://github.com/fxsjy/jieba}} to segment Chinese texts and adopt Tencent Chinese word embeddings~\cite{song2018directional} composed of $8,000,000$ words. For English \textsc{Restaurant}, we adopt $300$-dimensional word embeddings pre-trained by Glove~\cite{pennington2014glove}. In terms of BERT-based models, we adopt the $12$-layer Google BERT Base\footnote{\url{https://github.com/google-research/bert}} to encode the inputs. The batch sizes are set as $32$ and $16$ for non-BERT-based models and BERT-based models respectively. Adam optimizer~\cite{kingma2014adam} is employed with $\beta_1 = 0.9$ and $\beta_2 = 0.999$. The maximum sequence length is set as $512$. The number of epochs is set as $3$. The learning rates are set as $0.001$ and $0.00005$ for non-BERT-based models and BERT-based models respectively. All the models are trained on a single NVIDIA Tesla $32$G V$100$ Volta GPU. \noindent \textbf{Evaluation Metrics} Following the settings of \textsc{Restaurant}, we adopt Macro-F1 and Accuracy (Acc) as evaluation metrics. \noindent \textbf{Experimental Results \& Analysis} We report the performance of aforementioned models on \textsc{ASAP} and \textsc{Restaurant} in \autoref{tb:exp-result}. Generally, BERT-based models outperform Non-BERT based models on both datasets. The two variants of our joint model perform better than vanilla-BERT, QA-BERT, and CapsNet-BERT, which proves the advantages of our joint learning model. Given a user review, vanilla-BERT, QA-BERT, and CapsNet-BERT treat the pre-defined aspect categories independently, while our joint model combines them together with a multi-task learning framework. On one hand, the encoder-sharing setting enables knowledge transferring among different aspect categories. On the other hand, our joint model is more efficient than other competitors, especially when the number of aspect categories is large. The ablation of RP (i.e., joint model(w/o RP)) still outperforms all other baselines. The introduction of RP to ACSA brings marginal improvement. This is reasonable considering that the essential objective of RP is to estimate the overall sentiment polarity instead of fine-grained sentiment polarities. We visualize the attention weights produced by our joint model on the example of \autoref{tb:dataset} in \autoref{fig:attenion_score}. Since different aspect category information is dispersed across the review of $R$, we add an attention-pooling layer~\cite{ATAE} to aggregate the related token embeddings dynamically for every aspect category. The attention-pooling layer helps the model focus on the tokens most related to the target aspect categories. \autoref{fig:attenion_score} visualizes attention weights of $3$ given aspect categories. The intensity of the color represents the magnitude of attention weight, which means the relatedness of tokens to the given aspect category. It's obvious that our joint model focus on the tokens most related to the aspect categories across the review of $R$. \begin{figure}[htb] \small \centering \includegraphics[height=0.4\textwidth]{figs/attention_score.png} \caption{Attention visualization example. We only show attention weights of $3$ aspect categories for beauty. The red text span "..With convenient traffic..(\begin{CJK*}{UTF8}{gkai}..交通还挺方便的..\end{CJK*})" is related to \textit{Location\#Transportation}. The blue text span "..the restaurant holds a high-end decoration..Impressed by its delicate decoration and grand appearance though..(\begin{CJK*}{UTF8}{gkai}..环境看起来高大上的样子..装修还不错,很精致的装修..\end{CJK*})" is related to \textit{Ambience\#Decoration}. The green text span "..but quite noisy..(\begin{CJK*}{UTF8}{gkai}..特别吵感觉..\end{CJK*})" is related to \textit{Ambience\#Noise}. The intensity of the color represents the magnitude of attention weight.} \label{fig:attenion_score} \end{figure} \subsection{Rating Prediction} We compare several RP models on \textsc{ASAP}, including TextCNN~\citep{kim2014convolutional}, BiLSTM+Attn~\citep{zhou2016attention} and ARP~\citep{arp}. The data pre-processing and implementation details are identical with ACSA experiments. \noindent \textbf{Evaluation Metrics.} We adopt Mean Absolute Error (MAE) and Accuracy (by mapping the predicted rating score to the nearest category) as evaluation metrics. \noindent \textbf{Experimental Results \& Analysis} The experimental results of comparative RP models are illustrated in \autoref{tb:rating-result}. \begin{table}[H] \small \centering \caption{Experimental results of RP models on \textsc{ASAP}{}. Best scores are boldfaced.}\label{tb:rating-result} \begin{tabular}{p{0.27\textwidth}cc} \hline Model & MAE & Acc. \\ \hline TextCNN~\citep{kim2014convolutional} & $.5814$ & $52.99\%$ \\ BiLSTM+Attn~\citep{zhou2016attention} & $.5737$ & $54.38\%$ \\ ARP~\cite{arp} & $.5620$ & $54.76\%$ \\ Joint Model (w/o ACSA) & $.4421$ & $60.08\%$ \\ Joint Model & $\mathbf{.4266}$ & $\mathbf{61.26\%}$ \\ \hline \end{tabular} \end{table} Our joint model which combines ACSA and RP outperforms other models considerably. On one hand, the performance improvement is expected since our joint model is built upon BERT. On the other hand, the ablation of ACSA (i.e., joint model(w/o ACSA)) brings performance degradation of RP on both metrics. We can conclude that the fine-grained aspect category sentiment prediction of the review indeed helps the model predict its overall rating more accurately. This section conducts preliminary experiments to evaluate classical ACSA and RP models on our proposed \textsc{ASAP} dataset. We believe there still exists much room for improvements to both tasks, and we will leave them for future work. \section{Appendix} \label{sec:appendix} \setcounter{table}{0} Due to the page limit, we supplement more details of \textsc{ASAP} in this section. \textbf{Difficult Cases' Annotation.} Most difficult cases during our annotation fall into $5$ categories. The cases and corresponding annotation guidelines are summarized in \autoref{tb:difficult-cases}. \begin{table*}[htb] \small \centering \caption{Difficult cases and annotation guidelines.} \begin{tabular}{P{0.15\textwidth}P{0.2\textwidth}P{0.25\textwidth}P{0.25\textwidth}P{0.15\textwidth}} \hline Category & Example & Example (Translation) & Guideline & Annotation \\ \hline Change of sentiment over time & \begin{CJK*}{UTF8}{gkai}我之前挺喜欢这家餐厅的饭菜,不过今天的饭菜可不怎么样.\end{CJK*} & I used to like the food of this restaurant, but the taste is not as expected today. & When there existed a sentiment drifting over time in the review, the most recent sentiment polarity is adopted. & (\textit{Food\#Taste}, $-1$) \\ Implicit sentiment polarity & \begin{CJK*}{UTF8}{gkai}比五星级酒店的餐厅差远了,而且在五星级酒店中餐厅里两个人吃一顿也就$500$左右就够了\end{CJK*} & The restaurant was far worse than the dinning hall of any five-star hotel, considering that the meal for two people only cost $500$ CNY in a five-star hotel. & Some reviewers express their polarities in an implicit manner instead of expressing their feelings directly. The implicit sentiment polarity is adopted to complete the annotation. & (\textit{Price\#Level}, $-1$) \\ Conflict opinions & \begin{CJK*}{UTF8}{gkai}这道菜有点咸,但是味道很赞。\end{CJK*} & This dish was a bit salty, but it tasted great. & When there existed multiple sentiment polarities toward the same aspect-category, the dominant sentiment is chosen. & (\textit{Food\#Taste}, $1$) \\ Mild sentiment & \begin{CJK*}{UTF8}{gkai} 饭菜还可以,不过也算不上特别好吃。\end{CJK*} & The food was okay, but nothing great. & The “neutral” label applies to mildly positive or mildly negative sentiment & (\textit{Food\#Taste}, $0$) \\ Irrelevant restaurant & \begin{CJK*}{UTF8}{gkai} 上次去的一家店很难吃,今天来了这家新的,感觉很好吃。\end{CJK*} & The food of the shop which I went to last time was very bad. Today I came to this new one. I felt very good. & The review mentions restaurant that the user has visited in the past. We only focus on the restaurant being reviewed & (\textit{Food\#Taste}, $1$) \\ \hline \end{tabular} \label{tb:difficult-cases} \end{table*}
{'timestamp': '2021-05-04T02:44:13', 'yymm': '2103', 'arxiv_id': '2103.06605', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06605'}
arxiv
\section{Introduction} \label{sec:intro} \hl{Social distances are a part of non-verbal human communications and, naturally, there are personal and cultural differences in how people feel about their personal space and interpret the interpersonal distance in different situations. The research field under social studies concerning these phenomena related to space is known as \emph{proxemics} \mbox{\cite{hall1968proxemics}}. Despite the long history of studies in the field \mbox{\cite{hiddendimensions, cook1970proxemics, harrigan2005proxemics}}, it remains difficult to carry out quantitative analysis on the actual social distances in the natural situations outside of monitored test conditions, e.g., when people are spending their free time with their families. One way to approach this problem is \mbox{\emph{visual social distancing}} (VSD), where the interpersonal distances are automatically measured from the images or videos. A comprehensive overview of the VSD problem, including the main challenges and connections to social studies, is provided in \mbox{\cite{vsd}}.} \hl{Social distancing has recently received a lot of attention due to t}he outbreak of SARS-CoV-2 virus \cite{covid19} \hl{that} was declared as a global pandemic by the World Health Organization (WHO) in March 2020. The pandemic, also known as the COVID-19 pandemic is still ongoing as of \hl{May 2021} and there has been a total of \hl{about 164} million confirmed cases and \hl{3.4} million deaths worldwide within the period of December 2019-\hl{May} 2021 \cite{coviddata}. Social distancing plays an important \hl{role} in slowing down the spread of the virus. \hl{WHO} recommends to stay at least one meter apart from other people in order to reduce the risk of infection \cite{who}. Automatically monitoring the social distances is important for safety reasons, but it is also interesting as a phenomenon that has globally changed basic human behavior \cite{zhang2021memory, dicorrado2020physicalactivity, eden2020media}. After the pandemic eases, there are many interesting research questions \hl{in proxemics and other fields} to look into: how the social distancing affected every-day life, what kind of significant differences were there between different countries, can the differences be linked to the spreading speed, will there be any long-term changes that will stay after the pandemic. \hl{While there are methods and sensors available for automatic monitoring and surveillance of social distances \mbox{\cite{nguyen_saputra_van}}, the analysis of deeper and longer term social and cultural impacts of the social distancing regulations requires looking into different source data, such as people's personal photo collections and pictures published in newspapers and magazines. For monitoring purposes, it is possible to use fixed camera setup and location, take videos or simultaneous images from multiple viewpoints, and use additional sensors such as depth or thermal cameras. All these can make the social distance estimates more accurate but are not available for typical personal and media photos that are not taken with a fixed setup, but have varying parameters such as focal length, sensor size, lighting conditions, and pitch angle. An example of an image that could be found in a personal or media photo collection, but not in a monitoring or surveillance setup is shown in Fig.~\mbox{\ref{fig:mediaexample}}. At the same time, in such social and proxemics studies the focus shifts from monitoring whether people are obeying the regulations to more subtle differences in the social distances and how they are represented in the media.} \hl{During the pandemic, most effort has been understandably on the monitoring side, and} currently there is no suitable benchmark for developing and testing algorithms for \hl{accurate social distance analysis from single images having varying camera parameters.} This can be due to the laboriousness of gathering varying images with measured pair-wise distances between humans. At the same time, there is no clear protocol for measuring the algorithm performance \hl{in this task}. To address these lacks, we provide a social distance evaluation test benchmark including a protocol for mapping the detected pair-wise distances into the corresponding ground truth distances, a suggested overall performance metric, and 96 test images taken with varying setups: indoors-outdoors, sitting-standing, varying camera angles using 2 different cameras and 7 different focal lengths. \hl{The photos were taken by a professional photojournalist to follow the typical media photography style.} We publish \hl{also} easy-to-use codes for evaluating novel methods and make it easy to integrate additional test photos. \begin{figure}[t] \centering \includegraphics[width=1\columnwidth]{mediaexample.jpg} \caption{\hl{An example of an image that represents a style, which is common in personal and media photography, but not in monitoring.}} \label{fig:mediaexample} \end{figure} We also propose a social distance estimation algorithm \hl{that can be applied on any uncalibrated single image taken by a regular camera as long as focal length and sensor size are known.} It combines object detection and human pose estimation with projective geometry \hl{using} image parameters (focal length, sensor size) and pixel locations. While the results are promising, we also point out some of the main remaining challenges for future development. The rest of the paper is organized as follows. Section~\ref{sec:related} introduces related work on social distancing and automatic distance evaluation. Section~\ref{sec:testdataset} describes the provided test benchmark and the proposed evaluation protocol. Our method for automatic social distance estimation is described in Section~\ref{sec:method}. Section~\ref{sec:experimental} provides our experimental setup and results and, finally, Section~\ref{sec:conclusion} concludes the paper. \section{Related Work} \label{sec:related} Effectiveness of social distancing on slowing down the spread of the COVID-19 virus have been widely studied \cite{voko,sun_zhai_2020,prem_liu_russell_kucharski_eggo_davies_group_jit_klepac_2020,courtemanche_garuccio_le_pinkston_yelowitz_2020,abouk_heydari_2021,balasa_2020} and these studies have shown that social distancing measures are successful in reducing the growth rate of the virus. Therefore, monitoring and regulating the social distancing behaviour between people plays a crucial part in dampening the effects of the virus. In addition to directly effecting the virus spread, social distancing has globally changed human behavior and interactions leading to different side-impacts, e.g., on mental health \cite{ford2020psychological, jacob2020crosssectional}, physical activity \cite{dicorrado2020physicalactivity, jacob2020crosssectional}, mood and memory \cite{zhang2021memory}, and media consumption \cite{eden2020media}. Such impacts and their cross-cultural \cite{alhasan2020crosscontinental, alhasan2020comparative, doogan2020twitter} and cross-sectional \cite{jacob2020crosssectional, lee2021southkorea} differences continue to draw attention from researchers in many fields. \begin{figure*}[t] \centering \includegraphics[width=1\textwidth]{birdseye0_1.png} \caption{Birdseye view of the outdoor photo shoot. \hl{The ground truth locations of the people and cameras are given in blue and red dots, respectively.}} \label{fig:birdeye1} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=1\textwidth]{birdseye2_1.png} \caption{Birdseye view of the indoor photo shoot. \hl{The ground truth locations of the people and cameras are given in blue and red dots, respectively}} \label{fig:birdeye2} \end{figure*} Social distance monitoring for safety reasons can be eased by automatic social distance estimation from images and videos. Recent advancements in machine learning, computer vision, thermal and ultrasound technologies have made this task possible. A comprehensive survey in \cite{nguyen_saputra_van} explores the wide array of current technologies that can be used to monitor and encourage social distancing. A mobile robot that incorporates a 2D lidar to autonomously navigate in crowded environments without colliding with people was described in \cite{covidrobot}. The robot uses a RGB-D camera to detect people and it estimates the distance between the detected people by using the visual and depth information. A commercial pedestrian tracking system was used in \cite{pedestriantracker} to detect passengers in crowded environments and estimate the distances between them by using a graph based approach. The method was employed in a Dutch train station and the results show that the average number of pedestrians and social distance violations in the station have decreased after the pandemic. A study in \cite{ahmed_ahmad_rodrigues_jeon_din_2021} proposed using a deep learning based model with YOLOv3 \cite{yolov3} as its backbone to monitor social distancing violations from overhead view cameras. In \cite{yolodeepsorttracker}, the authors used YOLOv3 \cite{yolov3} and DeepSort \cite{deepsort1,deepsort2} to detect bounding boxes of people in RGB images and by utilizing these boundary boxes, they detected the cases of social distance violations. Another study \cite{drone} used an autonomous drone and a YOLOv3 model \cite{yolov3} trained with a custom dataset. The model processes images from the live feed of the drone's RGB camera. The drone detects whether or not a person is wearing a face mask and monitors social distance violations between the people who are not wearing masks. A work in \cite{proxemics} proposed to use skeleton keypoints generated from human body pose estimation algorithms \cite{openpose1,openpose2,openpose3,openpose4} to estimate the distance between people from uncalibrated images. The authors used manual tuning to estimate the homography matrix \cite{proj_geo} of an image plane and then used leg, arm, and torso lengths of the people alongside with the homography matrix to draw a safe space circle underneath every detected person. Then, any collision between the estimated safe space circles was reported as a social distance violation. \hl{Similarly, the work in \mbox{\cite{interhomines}} also takes advantage of manual homography matrix calibration to estimate social distances for fixed cameras. Separating the work from \mbox{\cite{proxemics}}, bounding boxes obtained from the object detection model \mbox{\cite{centernet}} and the height of these boxes were used as reference points to estimate the locations of the people. Moreover, a small CNN is used to detect the feet locations even when they are not visible. The output of this CNN is used to correct the height of the bounding boxes in cases of occlusions. Another similar study in \mbox{\cite{yang2020visionbased}} also used bounding boxes obtained from object detectors \mbox{\cite{yolov4, fasterrcnn}} to estimate locations of the people from surveillance camera footage by using the homography matrix that is calculated from the known extrinsics. The work in \mbox{\cite{monoloco}} used a feed forward neural network that was trained on the intrinsic parameters of the camera and the keypoints obtained from a pose estimation model. The model outputs the predicted 3D locations as well as the orientations of the detected people. While detecting safe distance violations, not only the proximity but also the orientation of the people with respect to one another is considered.} \par \hl{Most of the introduced works approach automatic social distance estimation as a monitoring or surveillance task, where the goal is to prevent social distance regulation violations. To this end, they apply additional sensors, use predefined camera settings, and/or manually define a homography matrix for a certain environment. While such approaches can improve the social distance estimation accuracy, they are not feasible when the purpose is to analyze the impacts of social distances in personal or media photo collections.} Moreover, the above-mentioned studies approach the automatic social distance estimation problem as a binary classification problem where they aim to classify the pair-wise distances between people either as safe or unsafe, depending on a given threshold. Classifying distances in a binary manner has a high tolerance for distance estimation errors. For example, if the threshold for safe distance is set to 2 meters, the actual distance between a pair of people is 1.9 meters, and a method estimates that distance as 0.1 meter, the percentual distance estimation error would be 94.7\%, but a binary classification approach would still correctly label the situation as a social distance violation. \hl{Furthermore}, the binary approach does not provide any additional information on the severity of the violations in different situations which may be relevant information for subsequent analysis. A common pattern observed in most of the machine learning based social distance estimation methods (with the exception of at least \cite{proxemics, monoloco} that use keypoints of the human body) is that they rely on the bounding boxes drawn by object detectors to detect social distance violations. Although the current object detectors are accurate in detecting objects, the bounding boxes are generally loosely drawn around these objects. Thus, it is not reliable to use only the bounding box information for estimating exact distances between people as it is not possible to infer accurate 3D location estimates from the bounding boxes alone. Therefore, we aim to estimate exact 3D locations of all the people in uncalibrated RGB images with respect to the camera by using the information extracted from the human body skeleton detected by body estimation algorithms. Moreover, we also incorporate an object detection model for people detection. However, the purpose of the people detection in our approach is to only detect the false positives in skeleton keypoints, when they are drawn on non-human objects. \par The method in \cite{proxemics} is the most similar to our method as is also uses body poses. In \cite{proxemics}, manual input is used to estimate the homography matrix of the image plane to the ground plane. The method is evaluated on surveillance camera footage and the task is approached as a binary classification problem. It is feasible to manually set the homography matrix of surveillance cameras as these cameras are generally non-moving and stable. Contrary to this, we want our method to be fully automatic as we aim to estimate distances in images taken in different locations with different cameras. \hl{Instead of requiring manual input to estimate the homography as} the study in \cite{proxemics}, we assume \hl{that we can find keypoint pairs that are parallel to camera's sensor plane} and we use the image parameters, i.e., focal length and sensor size in our distance estimation. \hl{For the developing and testing social distance estimation methods, it is important to have image datasets that have a suitable setup and ground-truth for the task. The previous works have used datasets such as Epfl-Mpv-VSD \mbox{\cite{epflmpv}}, Epfl-Wildtrack-VSD \mbox{\cite{epflwildtrack}} and OxTown-VSD \mbox{\cite{oxtown}}. These dataset include videos taken by surveillance cameras with fixed extrinsic and intrinsics and they do not include manually measured ground truth locations and distances. Instead, the locations of the people are estimated by making use of the annotation boxes that were drawn on the people. The pixel locations of these annotation boxes are used as a reference point to estimate the subjects\mbox{’} locations by taking the extrinsic parameters into account. This means that these locations are not exactly ground truth, but estimations based on the known extrinsics and the pixel locations of the manually annotated person bounding boxes. Furthermore, since exact body parts are not annotated and the annotations are only in bounding box format, it is not feasible nor possible to accurately match the detected people with the given ground truth people when there are multiple overlapping boxes. Moreover, only the people that are passing on a certain region of interest are annotated. Due to the aforementioned reasons, the existing datasets are not suitable for evaluating methods that aim at estimating distances in general photo collections and are not manually tuned for a specific camera and environments. Furthermore, the approximate person annotations and location estimates do not allow accurately measuring the distance estimation performance, but are only suitable for detecting coarse violations in social distancing recommendations. While this may be sufficient for surveillance purposes in fixed environments, more accurate ground-truth and annotations are needed for evaluating methods aiming at detecting subtle changes in long-term social distancing behavior in varying environments. In the following section, we introduce our novel dataset that addresses the mentioned drawbacks of the existing datasets. } \section{KORTE SOCIAL DISTANCE ESTIMATION BENCHMARK} \label{sec:testdataset} We provide a test benchmark for facilitating research in automatic social distance evaluation. We propose a performance evaluation protocol and provide 96 test images with ground-truth pair-wise distances. While the number of images is too low for training fully learning-based systems, it provides a varied test setup. All the evaluation codes along with the test photos are publicly available at \href{https://doi.org/10.23729/b2ea87e6-b845-46b8-abf3-cdbe299ce8b0}{https://doi.org/10.23729/b2ea87e6-b845-46b8-abf3-cdbe299ce8b0}. It is also easy to complement the benchmark with additional images by following the proposed annotation format and using the provided evaluation protocol. \subsection{Test Photo Collection} We collected test photos in two separate photo shoots. The first photo shoot was organized outdoors at Tampere University campus in December 2020. Every person was standing. The second photo shoot was organized indoors at Tampere University campus in January 2021 with people sitting around tables. In both photo shoots we had five volunteer test subjects. We followed the COVID-19 restrictions at the time: everyone was wearing a mask and we were less than 10 people gathering. As an additional safety measure, we placed to closest distances from each other only people who meet regularly anyway because they share working space or live together. Every test subject signed an agreement allowing to use their images for research purposes. Any bypassers in the images were censored out to respect their privacy and because their exact positions were unknown. \hl{The photos were taken by a professional photojournalist}. During the photo shoots, test subjects stayed on the same known positions, while the photographer changed his position and used multiple cameras and lenses at each spot. Fig.~\ref{fig:birdeye1} shows the birdseye view of the first outdoor photo shoot. P0, P1, P2, P3, P4, P5 are the locations of the 5 test subjects and C0, C1, C2 are the camera locations. For the first photo shoot, P0, P1, P2, P3, P4, P5, C0 and C1 were all on the same ground plane, while C2 was at a balcony with a height of 230 cm relative to the ground plane that all of the other locations were at. Fig.~\ref{fig:birdeye2} shows the birdseye view of the second photo shoot. P0, P1, P2, P3, P4, P6 are the locations of the 6 people and C0, C1, C2, C3 are the camera locations. The unit of the x and y axis labels is centimeters. For the second photo shoot, all of the locations were on the same ground plane. \hl{The ground truth locations of the cameras and the test subjects were measured and maintained exploiting tiles on the ground/floor that were equal in size. Only the camera location C2 in the outdoor photo shoot was not on the same tiling and, therefore, it was measured separately using a measuring tape. } \hl{We do not report the exact pitch angles, and they were not fixed in the photo shoots. Due to the camera positions, pitch angles are close to zero in most of the images except for the 16 photos taken from camera position C2 in the outdoor photo shoot, where the camera was at an elevated position. We believe that our dataset represents a typical media or personal photo collection with respect to the pitch angles, but it should be noted that methods performing well on our dataset (especially if they rely on the zero pitch angle assumption) may not perform equally well on extreme pitch angles such as overhead images.} The used camera models were Canon EOS 5D Mark II and Canon EOS 6D Mark II. The used focal length sizes were 16, 24, 35, 50, 105, 200, and 300 mm. The cameras were stabilized on a tripod and the tripod's height was 135 cm for all images. Fig.~\ref{fig:samplephotos} shows example photos from both photo shoots, one photo from each camera position. \begin{figure*}[h] \centering \includegraphics[width=0.32\linewidth]{photoshoot_c0_tags.jpg} \includegraphics[width=0.32\linewidth]{photoshoot_c1_tags.jpg} \includegraphics[width=0.32\linewidth]{photoshoot_c2_tags.jpg} \\ \vspace{5pt} \includegraphics[width=0.24\linewidth]{photoshoot2C0.jpg} \includegraphics[width=0.24\linewidth]{photoshoot2C1.jpg} \includegraphics[width=0.24\linewidth]{photoshoot2C2.jpg} \includegraphics[width=0.24\linewidth]{photoshoot2C3.jpg} \caption{Example photos from the test dataset. The upper row has photos from the outdoor photo shoot taken from all camera positions C0 (left) to C2 (right) and the lower row has photos from the indoor photo shoot taken from all camera positions C0 (left) to C3 (right).} \label{fig:samplephotos} \end{figure*} \subsection{Test Data Description} \label{ssec:datadescription} The overall dataset contains 96 images including 63 outdoor images and 33 indoor images. All of the images are in JPG format. 81 of the images have the resolution 4180x2768 and 15 of the images have the resolution 4080x2720. Two different camera models were used and the sensor size for both of these cameras is 36 mm in width and 24 mm in height. The distribution of the pictures in terms of focal lengths, camera models, and shooting setting are given in Table 1. \begin{table}[t] \centering \begin{tabular}{|c|c|cc|} \hline \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Focal \\ Length (mm)\end{tabular}} & \multirow{2}{*}{Camera Model} & \multicolumn{2}{c|}{Shooting Setting} \\ \cline{3-4} & & Indoor & Outdoor \\ \hline 16 & Canon EOS 6D Mark II & 4 & 7 \\ 24 & Canon EOS 6D Mark II & 4 & 8 \\ 35 & Canon EOS 6D Mark II & 4 & 11 \\ 50 & Canon EOS 6D Mark II & 7 & 11 \\ 105 & Canon EOS 6D Mark II & 14 & 11 \\ 200 & Canon EOS 5D Mark II & - & 7 \\ 300 & Canon EOS 5D Mark II &- & 8 \\ \hline All & &33 & 63 \\ \hline \end{tabular} \caption{Numbers of photos in the test dataset for different focal lengths (mm), camera models, and shooting settings (indoor/outdoor).} \end{table} Along with the images, we also provide different annotation data provided in three separate .csv files illustrated in Fig.~\ref{fig:datasetexplanation}. The first file (Fig.~\ref{sfig:bodyparts}) contains the pixel locations of four different body parts. These annotated body parts are center of the eyes, center of the shoulders, center of the torso, and center of the head. If a body part is not visible in the image, then it is not annotated. The people in the images are labeled as P0, P1, P2, P3, P4, P5, and P6 in the annotation file. These person tags are consistent through all of the images. This means that a person tag always refers to the same person in all of the images that we provide. The second file (Fig.~\ref{sfig:3dlocations}) contains the 3D locations of people and different camera positions in both photoshoots. Photoshoot ID 0 refers to the outdoor photo shoot and photoshoot ID 1 refers to the indoor photo shoot. The third file (Fig.~\ref{sfig:3dlocations}) links the image filenames with the corresponding photoshoot and camera location. The cameras' exterior orientation parameters are not included in the metadata of the images. \begin{figure*} \centering \begin{subfigure}[b]{0.6\textwidth} \centering \includegraphics[width=\textwidth]{annonations_parts_3.jpg} \caption{Body part pixel locations} \label{sfig:bodyparts} \end{subfigure} \\ \begin{subfigure}[b]{0.43\textwidth} \centering \includegraphics[width=\textwidth]{annotations_3dlocations_3.jpg} \caption{Ground truth relative 3D location} \label{sfig:3dlocations} \end{subfigure} \begin{subfigure}[b]{0.38\textwidth} \centering \includegraphics[width=\textwidth]{annonations_photoshoots_3.jpg} \caption{Photoshoot identifiers and camera locations} \label{sfig:photshoot} \end{subfigure} \caption{Annotation file formats} \label{fig:datasetexplanation} \end{figure*} New images can be added to the dataset simply by following the described structure of the annotation data shown in Fig.~\ref{fig:datasetexplanation}. This does not require any changes in the provided evaluation codes. New photo shoots, i.e., new settings of people, must be identified with a unique integer identifier. For any photo shoot, the real world locations of the people should stay the same in all the photos. There may be pictures taken from different camera locations. Person and camera tags should start with a P and C letter, respectively, followed by a unique identifier integer. Person and camera location tags must be consistent within a given photo shoot, however repeated tags in different photo shoots are allowed. This means that two different people or camera tags could be the same as long as they belong to a different photo shoot. At least 1 of 4 body parts (center of the eyes, shoulders, torso, head) of the people in the images must be annotated in terms of pixel locations. They should be named "Eyes", "Shoulder", "Torso", and "Head" in the body part column of the body part pixel location file in Fig.~\ref{sfig:bodyparts}. To be consistent with the annotations in the provided test images, the annotation can be done as follows. Using the keypoint numbering in Fig.~\ref{fig:openposekeypoints}, the center of the eyes refers to the middle point of the keypoint pair 15-16, the center of the shoulders refers to the middle point of the keypoint pair 2-5, the center of the torso refers to the middle point of the keypoint pair 1-8, and the head should be annotated as middle point of the head regardless of the head's angle with respect to the camera. If a head is sideways and only one of the eyes is visible, the visible eye can be annotated as the center of the eyes. If none of the eyes are visible, the center of the eyes should not be annotated. The center of the eyes should also not be annotated if at least one of the eyes is out of the picture due to the head being on the edge of the picture. The other body parts can be annotated as long as they are either completely visible in the picture or are partially occluded by another person or object. In the cases where they are partially occluded, the pixel location should be estimated as if the occluding person or object was not present in the picture. The center of the shoulders, torso, and head should not be annotated only in the cases where these body parts are either partially or completely out of the picture due to the person being on the edge of the picture. If a person is sideways and only one of the shoulders, i.e., keypoints 2 and 5, is visible, this point can be annotated as the center of the shoulders. \par \subsection{Evaluation Protocol} \label{ssec:protocol} Any distance estimation method to be tested using the benchmark should give as output at least 1 of the 4 annotated pixel body locations along with either the estimated 3D location of the persons or the estimated distances between the people. The body part can be different for each person, or a method may choose to give only a single body part, such as the head, for all the persons. The test benchmark uses the pixel locations to automatically match each detected person with one of the ground truth locations and then computes average percentual pair-wise estimation errors between the estimated and ground truth distances. We provide all the necessary functionalities for testing as long as the required output for each image is given. Internally, the matching is carried out by comparing the automatically detected body pixel locations with the points annotated in the files. The automatically detected body parts are compared to all of the respective annotated body parts. As an example, a detected torso point is compared to all of the annotated torso points for that image. For all of the detected body parts of a person, the closest respective annotated point in terms of pixel-wise distance is found. In case there are more than one detected persons matched with the same ground truth person, the matching is done in a greedy manner by selecting only the closest match and the rest of the detected persons for that ground truth person are regarded as false positives. After matching the detections with the persons labeled in the photos, we calculate the distances between each person pair by using their estimated 3D locations. Then, the estimated pair-wise distances are compared to the corresponding ground truth pair-wise distances to obtain a percentual distance estimation error for each pair. The performance is evaluated by taking the average of all of the pair-wise percentual distance estimation errors for each image and then averaging over images. In addition to the pair-wise percentual distance estimation error, we evaluate also the person detection rate, i.e., the ratio of correctly detected person averaged over all the images, and the false discovery rate averaged over all the images. It should be noted here that we do not use any threshold for matching the detections with the actual people. As long as \hl{the number of detections is lower or equal to the actual number of images, all the detections are matched. Thus, d}etections can be considered false positives only if there are more detections than actual people for an image. Therefore, a method producing many false positive detections is expected to get a high detection rate, but naturally the distance estimations would likely be poor and the false discovery rate would be higher. On the other hand, a method missing most the people could have a low pair-wise percentual distance estimation error for the detected people, but still not be suitable social distancing analyses. Therefore, it is important to consider all these metrics together, when evaluating a social distance estimation algorithm. The pair-wise percentual distance estimation error $D_{e}$ for \hl{the $e^{th}$} single image is given by the following formula where \hl{$n$} is the number of detected people in the image, \hl{$E_{i}$} is the estimated 3D location of the \hl{$i^{th}$} person and \hl{$G_{i}$} is the ground truth 3D location of the \hl{$i^{th}$} person: \begin{equation} D_{e} = \frac{\sum_{k = 1}^{n-1} \sum_{i = k+1}^{n} \frac{\left \|E_{k} - E_{i}\right \| - \left \|G_{k} - G_{i}\right \|}{\left \|G_{k} - G_{i}\right \|} * 100}{\binom{n}{2}}. \end{equation} Here, the distances may be also directly given instead of the 3D locations. \begin{figure*}[t] \centering \includegraphics[width=0.494\linewidth]{Capture3.png} \includegraphics[width=0.494\linewidth]{Capture2.png} \caption{False positive examples for OpenPose (left) and YOLOv4 (right).} \label{fig:falsepositives} \end{figure*} In order to obtain an overall distance estimation error metric for a set of images, $D_{e}$ of all of the images in the image set are averaged. The distance estimation error for a set of images $D_{E}$ is given by the following formula where $N$ is the number of images in the set:\par \begin{equation} D_{E} = \frac{\sum_{e = 1}^{N} D_{e}}{N}. \end{equation} The test benchmark gives $D_{E}$, the person detection rate, and the false discovery rate as an output for a given set of images as long as the input and annotated data are provided in the proper format. Currently, the test benchmark uses our provided test photos, but if new images are added to the dataset as explained in Section~\ref{ssec:datadescription}, these will be automatically considered in the evaluation. \section{Proposed Method for Social Distance Estimation} \label{sec:method} Our proposed method to estimate social distances takes advantage of object detection and human pose estimation methods. Firstly, the input image is given to YOLOv4 \cite{yolov4} object detection model to obtain bounding boxes for people. After bounding boxes are obtained, overlapping boxes are grouped together. Then, these grouped boxes are cropped from the full image and they are individually given to OpenPose \cite{openpose1,openpose2,openpose3,openpose4} human pose estimation model. After the skeleton keypoints are extracted from OpenPose, the pixel locations of these keypoints are used in our distance estimation algorithm to obtain 3D location estimates for each person in the image. \par When YOLOv4 and OpenPose models are used together, they eliminate the other model's false positives. \hl{The l}eft image in Fig.~\ref{fig:falsepositives} shows a case where a backpack is falsely recognized as a human by OpenPose. However, YOLOv4 does not recognize it as a human. Therefore, the backpack would not be cropped and given to the OpenPose model. \hl{The r}ight image in Fig.~\ref{fig:falsepositives} shows a case where a bicycle is falsely recognized as a human by the YOLOv4 model. The bicycle is then cropped from the full image and given to the OpenPose model. However, the OpenPose model does not detect any human skeleton in the cropped bicycle image. Therefore, neither of these false positive cases is further processed by the distance estimation algorithm. \par After the cropped images from YOLOv4 are processed by the OpenPose model, the skeleton keypoints for detected human bodies are extracted. We use the 25 keypoint output version of OpenPose \hl{illustrated} in Fig.~\ref{fig:openposekeypoints}. \hl{Out of the extracted keypoints, we select pairs whose mutual distance is independent of the person's pose, whose average distance is available in the literature, whose angle towards the lens is as constant as possible, and which are visible in most of the photos. With these criteria, we select three key point pairs for our algorithm: 15-16 for pupillary distance, 2-5 for shoulder width, and 1-8 for torso length. In typical media or personal photos, the torso has the most constant angle towards the lens, but the eyes and shoulders are visible also in the close-up and portrait photos, where the torso is not seen. We assume average adult body proportions for the three keypoint pairs: 389 mm for shoulder width \mbox{\cite{shoulderwidth}}, 63 mm for pupillary distance \mbox{\cite{pupildistance}} and 444 mm for torso length \mbox{\cite{torsolength}}.} The extracted keypoint \hl{pairs} are then processed by our distance estimation algorithm that estimates 3D positions with respect to the camera for each person. \begin{figure}[!t] \centering \includegraphics[scale=0.5]{keypoints.png} \caption{25 skeleton keypoint output of OpenPose.} \label{fig:openposekeypoints} \end{figure} \begin{figure*}[h] \centering \includegraphics[width=0.85\linewidth]{triangle.jpg} \caption{Pinhole camera model.} \label{fig:pinhole} \end{figure*} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{orientationAngle.jpg} \caption{Birdseye view of orientation angle toward the lens.} \label{fig:noseangle} \end{figure} We use the pinhole camera model \cite{pinhole} shown in Fig.~\ref{fig:pinhole} for our calculations. We also make an assumption that every \hl{keypoint pair} is parallel to the camera's sensor plane. We make th\hl{ese} assumption\hl{s} because the \hl{subjects' poses and} camera's exterior orientation parameters \cite{camparameters} are not known. Estimating the exterior orientation parameters \cite{camparameters} of the camera from single images is an ill-posed problem \cite{illposed}, \hl{but} in most cases the angle between a person's torso and the camera's sensor plane is negligible for our calculations. We denote 3D locations of the keypoints on the image coordinate system as \begin{equation} (x_{a}, y_{a}, f), \label{eq:icoordinate} \end{equation} \hl{where $f$ is the focal length,} and 3D location estimates of the keypoints on the world coordinate system as \begin{equation} E_{n} = (X_{a}, Y_{a}, -d), \label{eq:wcoordinate} \end{equation} \hl{where $d$ is the distance to the camera.} The distance between a pair of keypoints on the image coordinate system is \begin{equation} D_{i} = \sqrt{(x_{0}-x_{1})^{2} + (y_{0}-y_{1})^{2} + (f-f)^{2}} \label{eq:idistance} \end{equation} and the distance between the keypoints on the world coordinate system is \begin{equation} D_{w} = \sqrt{(X_{0}-X_{1})^{2} + (Y_{0}-Y_{1})^{2} + (d-d)^{2}}. \label{eq:wdistance} \end{equation} Since the camera sensor's plane size is known, $x_{a}$ and $y_{a}$ in Eq.~\eqref{eq:icoordinate} \hl{can be} derived from the the x and y pixel locations of the keypoints in the image. The last coordinate, $f$, in Eq.~\eqref{eq:icoordinate} is obtained from the camera parameters. Thus, all the keypoints' 3D positions on the image coordinate system in Eq.~\eqref{eq:icoordinate} are known and $D_i$ can be solved. By using triangle similarity, the following equations give 3D positions of the keypoints on the world coordinate system. Eq.~\eqref{eq:destimate}, where $D_w$ is one of the average body proportions, is used to derive $d$ in Eq.~\eqref{eq:wcoordinate}. After $d$ is derived, $X_{a}$ and $Y_{a}$ are obtained from Eqs.~\eqref{eq:Xa} and \eqref{eq:Ya}. \begin{equation} \frac{D_{i}}{f} = \frac{D_{w}}{d} \label{eq:destimate} \end{equation} \begin{equation} X_{a} = -\frac{d}{f} x_{a} \label{eq:Xa} \end{equation} \begin{equation} Y_{a} = -\frac{d}{f} y_{a} \label{eq:Ya} \end{equation} \begin{figure*}[t] \centering \includegraphics[width=0.32\linewidth]{16mm.JPG} \includegraphics[width=0.32\linewidth]{105mm.JPG} \includegraphics[width=0.32\linewidth]{300mm.JPG} \caption{Examples of pictures from the dataset belonging to the first photo shoot, all of them taken from camera location C1. The used focal lengths for the pictures are 16mm, 105mm and 300mm from left to right.} \label{fig:focallengths} \end{figure*} \begin{figure}[p] \centering \includegraphics[scale=0.13]{flowchart_3.jpg} \caption{Flowchart of the method.} \label{fig:flowchart} \end{figure} After the 3D coordinates of the keypoints on the world coordinate system in Eq.~\eqref{eq:wcoordinate} are estimated, the middle points of each detected keypoint pair are used to represent a 3D location for the person. Thus, we have at most 3 different estimated 3D locations for a person, one for each keypoint pair (shoulder, pupil, torso). \hl{While we assume that the keypoint pairs are parallel to the camera's sensor plane, this assumption may not be valid, and the accuracy of the estimated locations is affected by the severity of the violations.} Fig.~\ref{fig:noseangle} shows the birdseye view of a person's orientation angle $\theta$ toward the lens. \hl{If the angle is non-zero,} the shoulder and pupil keypoint pairs are \hl{ no longer parallel to the sensor plane and the estimates based on these keypoint pairs are} prone to error. However, \hl{in a typical situation of upright torsos} the estimates made from the torso length are unaffected by $\theta$, \hl{because} $\theta$ does not affect $D_{i}$ computed using Eq.~\eqref{eq:idistance} for the torso. \hl{On the other hand, also a torso may not be parallel to the sensor plane either because the person is in a bent position or because the camera's pitch angle is non-zero. For an overhead image, shoulders might be parallel to the sensor plane, while torsos would be perpendicular. Whenever the assumption on a keypoint pair being parallel to the sensor plane is violated,} $D_{i}$ in Eq.~\eqref{eq:idistance} decreases. A smaller $D_{i}$ leads to a larger estimate for $d$ from Eq.~\eqref{eq:destimate}. For this reason, we select the 3D location with the smallest distance to the camera. \hl{For typical media or personal photos, where the pitch angle is small, this} means using the estimate derived from the torso whenever it is available. However, for close-up and portrait pictures, the torso is often not visible. Fig.~\ref{fig:focallengths} shows three pictures taken from the same location but with increasing focal lengths. The rightmost image in Fig.~\ref{fig:focallengths} is an example of a close-up picture where the distance estimations have to be made from the shoulder and pupil distances since there are no visible torsos. Finally, our method computes the distances between all the pairs of detected people and gives them as outputs. The pixel locations for the detected persons are given to be able to evaluate on our benchmark, while they are not needed if the method is used for analysing social distancing in novel images. The overall flowchart of the proposed social distance estimation method is illustrated in Fig.~\ref{fig:flowchart}. \section{Experimental Results} \label{sec:experimental} \subsection{Experimental Setup} All of the code was developed in Python programming language version 3.8 \cite{van1995python}. OpenPose \cite{openpose1,openpose2,openpose3,openpose4} and YOLOv4 \cite{yolov4} models were used for human detection. All of the images were resized to 50\% of their original sizes before being sent to YOLOv4 model. The input size of YOLOv4 was set to 704x704. Input size was not set for OpenPose as OpenPose is able to adapt its input size for each image. The version of the OpenPose model we were using was originally trained by using the COCO keypoint challenge dataset \cite{COCO}, combined with OpenPose authors' own annotated dataset for foot keypoint estimation which consists of a small subset of the COCO dataset where the authors labelled foot keypoints. YOLOv4 uses CSPDarknet53 \cite{darknet} as its backbone which was trained on the ImageNet dataset \cite{imagenet}. The deep learning models were downloaded from their respective official source code pages \footnote{https://github.com/CMU-Perceptual-Computing-Lab/openpose} \footnote{https://github.com/AlexeyAB/darknet} and they were loaded and used by TensorFlow library version 2.3.1 \cite{tensorflow2015}. For image processing purposes, OpenCV imaging library was used \cite{opencv}. In addition to our final method that generates 3D position estimates using torso, shoulders, and eyes and selects the estimate closest to the camera as explained in Section~\ref{sec:method}, we also evaluate variants of the proposed method, where only one of these body parts is used at the time. We use our test benchmark to compute the results for all the images and for outdoor and indoor images separately. \subsection{Results} \begin{table*}[] \centering \begin{tabular}{|c|c|cc|cc|cc|cc|} \hline \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Focal \\ Length (mm)\end{tabular}} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Number \\ of \\ Pictures\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Shoulder\\ Based \\ Method\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Pupil \\ Based\\ Method\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Torso \\ Based\\ Method\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Combined\\ Method\end{tabular}} \\ \cline{3-10} & & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} \\ \hline 16 & 11 & 0.84 & 163.91 & 0.68 & 45.81 & 0.77 & \textbf{19.94} & \textbf{0.90} & 20.50 \\ 24 & 12 & 0.83 & 230.80 & 0.61 & 65.20 & 0.84 & \textbf{17.76} & \textbf{0.93} & 21.62 \\35 & 15 & 0.84 & 101.48 & 0.70 & 52.86 & \textbf{0.96} & \textbf{20.51} & \textbf{0.96} & 22.61 \\ 50 & 18 & 0.84 & 190.37 & 0.62 & 50.35 & 0.84 & 26.16 & \textbf{0.91} & \textbf{25.52} \\ 105 & 25 & 0.82 & 116.52 & 0.80 & 52.65 & 0.72 & 34.54 & \textbf{0.95} & \textbf{34.15} \\ 200 & 7 & 0.71 & 109.99 & 0.75 & \textbf{50.61} & 0.41 & 93.54 & \textbf{0.79} & 53.68 \\ 300 & 8 & 0.72 & 288.13 & \textbf{0.89} & \textbf{34.48} & 0.18 & - & \textbf{0.89} & \textbf{34.48} \\ \hline All & 96 & 0.81 & 166.45 & 0.72 & 51.59 & 0.73 & \textbf{27.55} & \textbf{0.92} & 28.88 \\ \hline \end{tabular} \caption{Person detection rates and pair-wise percentual distance errors for each of the methods for both of the photo shoots (indoor and outdoor) combined} \label{tbl:combined} \end{table*} \begin{table*}[] \centering \begin{tabular}{|c|c|cc|cc|cc|cc|} \hline \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Focal \\ Length (mm)\end{tabular}} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Number \\ of \\ Pictures\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Shoulder\\ Based \\ Method\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Pupil \\ Based\\ Method\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Torso \\ Based\\ Method\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Combined\\ Method\end{tabular}} \\ \cline{3-10} & & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} \\ \hline 16 & 7 & \textbf{0.85} & 129.35 & 0.71 & 56.42 & \textbf{0.85} & 18.75 & \textbf{0.85} & \textbf{18.47} \\ 24 & 8 & 0.83 & 169.08 & 0.64 & 84.67 & \textbf{0.91} & \textbf{16.98} & \textbf{0.91} & 20.71 \\ 35 & 11 & 0.90 & 174.70 & 0.76 & 64.18 & \textbf{0.96} & \textbf{20.16} & \textbf{0.96} & 21.08 \\ 50 & 11 & 0.88 & 192.92 & 0.70 & 65.19 & 0.89 & \textbf{24.33} & \textbf{0.92} & 26.40 \\ 105 & 11 & \textbf{1.00} & 127.59 & \textbf{1.00} & 48.99 & 0.81 & 41.64 & \textbf{1.00} & \textbf{33.09} \\ 200 & 7 & 0.71 & 109.99 & 0.75 & \textbf{50.61} & 0.41 & 93.54 & \textbf{0.79} & 53.68 \\ 300 & 8 & 0.72 & 288.13 & \textbf{0.89} & \textbf{34.48} & 0.18 & - & \textbf{0.89} & \textbf{34.48} \\ \hline All & 63 & 0.86 & 164.43 & 0.78 & 58.73 & 0.74 & \textbf{28.82} & \textbf{0.91} & 28.87 \\ \hline \end{tabular} \caption{Person detection rates and pair-wise percentual distance errors for each of the methods for the first photo shoot (outdoor) where every person is standing up} \label{tbl:outdoor} \end{table*} \begin{table*}[] \centering \begin{tabular}{|c|c|cc|cc|cc|cc|} \hline \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Focal \\ Length (mm)\end{tabular}} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Number \\ of \\ Pictures\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Shoulder\\ Based \\ Method\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Pupil \\ Based\\ Method\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Torso \\ Based\\ Method\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Combined\\ Method\end{tabular}} \\ \cline{3-10} & & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} & \multicolumn{1}{c|}{\begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular}} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} \\ \hline 16 & 4 & 0.83 & 224.38 & 0.62 & 29.89 & 0.62 & \textbf{22.71} & \textbf{1.00} & 24.05 \\ 24 & 4 & 0.83 & 354.25 & 0.54 & 26.27 & 0.70 & \textbf{19.31} & \textbf{0.95} & 23.45 \\ 35 & 4 & 0.66 & 51.94 & 0.54 & 24.56 & \textbf{0.95} & 21.46 & \textbf{0.95} & 26.82 \\ 50 & 7 & 0.76 & 186.35 & 0.50 & 31.27 & 0.76 & 29.03 & \textbf{0.88} & \textbf{24.13} \\ 105 & 14 & 0.67 & 105.46 & 0.65 & 55.39 & 0.64 & \textbf{27.44} & \textbf{0.91} & 34.83 \\ \hline All & 33 & 0.73 & 170.57 & 0.59 & 38.92 & 0.71 & \textbf{25.24} & \textbf{0.92} & 28.90 \\ \hline \end{tabular} \caption{Person detection rates and pair-wise percentual distance errors for each of the methods for the second photo shoot (indoor) where every person is sitting down} \label{tbl:indoor} \end{table*} Tables \ref{tbl:combined}, \ref{tbl:outdoor}, and \ref{tbl:indoor} show the person detection rates and pair-wise percentual distance estimation errors for all the images, outdoor images, and indoor image, respectively. \hl{Since we are using YOLOv4 \mbox{\cite{yolov4}} in addition to OpenPose \mbox{\cite{openpose1,openpose2,openpose3,openpose4}} and they cancel each other's false positives, we have no cases with more detections than actual people in an image. This leads to zero false discovery rates as explained in Section \mbox{\ref{ssec:protocol}}}. Therefore, false discovery rates are not reported in the tables. It can be observed from Table~\ref{tbl:combined} that the most reliable body part to estimate locations is the torso. However, estimations made from the torso alone fail for close-up pictures where the torso detection rate is low. When all three body parts (shoulder, pupil, and torso) are used together for the estimations, the obtained results shown in the last column are better than the results obtained from a single body part. Although the combined method has slightly lower performance than the torso based method in terms of pair-wise percent distance error, person detection rate is significantly higher than that of the torso based method. The combined method mostly uses the torso whenever it is visible (overall shots) and uses the shoulder and pupil distances when the torso is not visible (close-up shots). \par Looking at Tables \ref{tbl:outdoor} and \ref{tbl:indoor}, it can be seen that there are no significant differences in terms of pair-wise distance errors when it comes to indoor and outdoor pictures. However, it should be noted that the person detection rates for the outdoor pictures are higher than for the indoor pictures. This is primarily caused by the fact that the body parts of the people in the indoor pictures were obstructed by the chairs. There were also more cases of people facing away from the camera and people standing in front of other people in the indoor photo shoot. \begin{table}[t] \centering \begin{tabular}{|c|c|c|} \hline \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Number\\ of\\ Pictures\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Combined\\ Method\end{tabular}} \\ \cline{2-3} & \begin{tabular}[c]{@{}c@{}}Person\\ Detection\\ Rate\end{tabular} & \begin{tabular}[c]{@{}c@{}}Pair-wise\\ Percent\\ Distance\\ Error\end{tabular} \\ \hline 16 & 1.00 & 32.88 \\ \hline \end{tabular} \caption{\hl{Person detection rates and pair-wise percentual distance errors for the combined method for the photos taken from camera location C2, for which the zero pitch angle assumption is not valid.}} \label{tbl:balcony} \end{table} \subsection{Additional results and analysis} \label{sec:additionalresults} \begin{figure}[h] \centering \includegraphics[scale=0.5]{errorGraph.png} \caption{Pair-wise distance estimation errors for each of the ground truth pair-wise distances.} \label{fig:errorsgraph} \end{figure} \hl{We separately show the results for the images that were taken from camera location C2 for the first (outdoor) photo shoot on Table \mbox{\ref{tbl:balcony}}. C2 location was at a balcony of height 230 cm relative to the ground plane where the subjects were standing on. Thus, the camera was pitched down to include the subjects within the field of view. For the other camera locations, the pitch angle was close to zero and people were mainly standing or sitting with their torsos upright. Therefore, the torsos can be expected to be almost parallel to the camera's sensor plane and, thus, produce good distance estimates whenever they are visible. For camera location C2, this may no longer be the case. However, the results show that the relative pair-wise distance estimation errors for C2 locations are only slightly higher than on the average. We can conclude that this level of pitch angle does not cause significant problems. } \hl{ A graph showing how the pair-wise distance estimation errors depend on the ground truth distances is given in Fig.~\mbox{\ref{fig:errorsgraph}}. It can be observed from this graph that the pair-wise distance estimations errors are on average slightly lower for higher ground truth distances.} We also provide additional results by formulating the social distance estimation problem as a binary classification task similar to previous works. We set four different social distance thresholds as safe distances. If the distance between a pair is smaller than the threshold, we consider the distance to be unsafe and safe otherwise. We consider the unsafe case as the positive class. The standard evaluation metrics for binary classification problems are Precision, Recall and F1-Score. The formulas for these metrics are $Precision = \frac{True Positives}{True Positives + False Positives}$ , $Recall = \frac{True Positives}{True Positives + False Negatives}$, $F1-score = 2 * (\frac{Precision*Recall}{Precision+Recall})$. F1-score is an overall measure of the binary classification performance and is always within the range of 0-1. An F1-score of 1 indicates perfect classification performance. The F1-score results of our proposed method are given in Table \ref{tbl:f1scores}. \par \begin{table}[t] \centering \begin{tabular}{|c|c|} \hline Safe Distance (m) & F1-Score \\ \hline 1 & 0.39 \\ 1.5 & 0.61 \\ 2 & 0.81 \\ 3 & 0.90 \\ \hline \end{tabular} \caption{F1-scores of our proposed method for different safe distance thresholds} \label{tbl:f1scores} \end{table} As can be seen in Table \ref{tbl:f1scores}, the choice of safe distance threshold changes the F1-scores drastically. For example, the low performance for 1m threshold follows from many ground-truth distances being just slightly above the threshold. As our methods tends to slightly underestimate the distances as explained in Section~\ref{sec:method}, these cases lead to false positives. This supports our claim that formulating the problem of social distance estimation as a binary classification task is not an optimal way to evaluate the performance of the methods. As the results depend greatly on the threshold value, F1-scores do not reflect the true capacity and accuracy of the distance estimation performance of a method. Our proposed evaluation protocol, which gives the average pair-wise percentual distance estimation error offers greater insight on the method's performance. \section{Conclusion} \label{sec:conclusion} To address the need for more accurate estimation of social distances \hl{from general images to analyze social and cultural impacts of the social distancing regulations introduced due to} the COVID-19 pandemic, we proposed a new test benchmark for automatic social distance estimation algorithms. The benchmark includes an evaluation protocol for methods producing pair-wise social distances. \hl{The images follow a typical journalistic photographing style instead of a fixed monitoring setup, and they were} taken with \hl{ varying camera} settings. Furthermore, we proposed a robust method that estimates 3D locations of persons in images and then uses these estimated locations to calculate the social distances between the people. \hl{Our method is able to estimate social distances in any single image without the need for knowing the extrinsic parameters or manually calibrating the homography matrix of the image plane to the ground plane, provided that the focal length and sensor size information of the camera are known, which enables our method to be used flexibly on all kinds of images. The proposed} method was able to obtain 92\% person detection rate along with 28.9\% pair-wise distance error on the proposed test benchmark. While our method gives satisfactory results for overall shots where the torsos of the people can be detected by OpenPose, the accuracy of the estimations gets weaker for close-up shots where the torsos are generally not visible in the image. \hl{This happens because our method assumes one of the keypoint pairs (eyes, shoulders, torso) to be parallel to the camera's sensor plane, and violations of this assumption lead to distance estimates that are longer than the ground-truth. In typical journalistic photos, where the camera's pitch angle is close to zero and the peoples' torsos are in upright positions, the assumption is typically most accurate for the torso keypoint pair whenever it is visible in the image. Thus, our method could be improved by estimating automatically also the pitch angle and persons' angles with respect to the camera.} Our method also uses average adult human body proportions for the calculations. Therefore, the estimations made for children in the images would be less accurate. \hl{Our method can be improved by taking advantage of other methods that can estimate the gender and ages of the subjects and adaptively changing the assumed body dimensions for each individual subject depending on their gender and age.} It should also be noted that our method requires the focal length and sensor plane size information of the camera. Therefore, our method cannot be applied on photos where these information are lacking. For our method to be applied on pictures where the focal length and sensor plane size are not known, these information would have to be estimated through other methods. \par In our future research, we will use our benchmark to further enhance the proposed method and then use it in an interdisciplinary study, where we will analyze the impacts of the COVID-19 \hl{regulations on} social interactions. While the COVID-19 makes the social distance analysis very topical, the benchmark and the developed methods are naturally not restricted on COVID-19 related analysis, but they can be beneficial in other image-based \hl{proxemics} studies focusing on different historical, cultural, or journalistic phenomena. \medskip \bibliographystyle{IEEEbib}
{'timestamp': '2021-06-21T02:10:05', 'yymm': '2103', 'arxiv_id': '2103.06759', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06759'}
arxiv
\section{Motivation}\label{sec:motivation} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/motivation.pdf} \caption{Profiling results for data-intensive workloads on NVIDIA Tesla V100 GPU.} \label{fig:motivation} \end{figure} \begin{figure*}[!h] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/arch.pdf} \caption{(1) MPU architecture overview. (2) Detailed microarchitecture of a MPU core (left: Subcores, middle: TSVs, right: NBUs). Added near-bank components are colored in blue. Newly supported components for instruction offloading and register movement (Sec.\ref{subsec:arch:instr_offld}) are colored in orange. Hybrid load-store unit (LSU) components (Sec.\ref{subsec:arch:hybrid_lsu}) are colored in yellow.} \vspace{-1em} \label{fig:arch} \end{figure*} Despite the success of the graphics processing unit (GPU) in accelerating data-intensive parallel programs, we observe from performance characterizations that the memory bandwidth is a serious performance challenge for these workloads on the state-of-the-art GPU. Specifically, we evaluate a set of representative data-intensive workloads from various application domains including deep learning, bioinformatics, linear algebra, and image processing applications as detailed in Table~\ref{tab:exp:benchmark}. The measured memory bandwidth, bandwidth utilization, and compute utilization of an NVIDIA Tesla V100 GPU~\cite{martineau2018benchmarking} are shown in Fig.\ref{fig:motivation}. On average, these benchmarks achieve $55.90\%$ DRAM bandwidth utilization ($503.10$ GB/s) and $2.57\%$ compute utilization. The saturation of DRAM bandwidth and the low utilization of the compute resources exhibit a memory-bandwidth bound behavior. This performance characteristic results from the low arithmetic density and the regular memory access patterns in most of these workloads. Also, we note that the workloads $HIST$ and $NW$ show relatively low bandwidth utilization as a result of the long memory access latency on GPU. For workloads suffering from either the limited DRAM bandwidth or the long DRAM access latency on GPU, near-bank computing is a promising architecture to alleviate these performance bottlenecks because of both abundant bank-level memory bandwidth and reduced memory access latency. However, prior near-bank computing accelerators~\cite{yazdanbakhsh2018dram,shin2018mcdram,aga2019co,gu2020ipim} are domain-customized, since they have simple data paths, application-specific mapping strategies, and inefficient general purpose programming language support. The lack of programmability for these accelerators confines them to a niche application market, adding non-recurring engineering costs in manufacturing. Moreover, parallel data-intensive workloads usually come from various application domains, making none of these near-bank accelerators feasible to support all of these parallel programs. In summary, the memory bandwidth bottleneck on the state-of-the-art GPU urges the need for a higher memory bandwidth for data-intensive parallel programs, and the huge overheads of placing an SIMT processor near banks introduce unique technical challenges. Both of these factors motivate us to design MPU, the first general purpose SIMT processor based on 3D-stacking near-bank computing to exploit bank-level bandwidth and alleviate the GPU bandwidth bottleneck. \section{Background}~\label{sec:bg}~\label{subsec:bg:nearbank}~\label{subsec:bg:simt} \noindent \textbf{3D-stacking Near-data Computing (3D-NDC):} 3D-NDC is based on commercially available 3D-stacking memory modules (HBM~\cite{sohn20171} and HMC~\cite{leidel2016hmc}) with DRAM dies stacked on the top of a base logic die. Previous GPU-style processing-on-logic-die solutions~\cite{zhang2014top,hsieh2016transparent,pattnaik2016scheduling,kersey2017lightweight,kim2017toward,wen2017optimizing,nai2018coolpim,wu2020tuning} usually place simple SIMT cores (Sec.\ref{subsec:bg:simt}) on the base logic die, and the cores access memory using TSVs (Through-Silicon-Vias)~\cite{xie2015stacking}, which are vertical interconnects shared among 3D layers. However, this solution is limited by the available bandwidth provided by TSVs (currently $307GB/s$ for one stack with 1024 TSVs~\cite{sohn20171}), and scaling TSVs is very difficult due to the large area overhead (already $18.8\%$ of each 3D layer~\cite{sohn20171}). To solve the TSV challenge, recent work pushes simple compute logic adjacent to each bank to utilize the enormous bank-level bandwidth for domain-specific acceleration~\cite{yazdanbakhsh2018dram,shin2018mcdram,aga2019co,gu2020ipim}. However, it is challenging to support general purpose near-bank architecture due to the large area overhead of fabricating general purpose cores in DRAM dies. We solve this challenge by a novel hybrid architecture that decouples the SIMT pipeline and duplicates some parts of the backend stages onto the near-bank DRAM dies (Sec.\ref{subsec:arch:hybrid_pipeline}). \noindent \textbf{Single-instruction-multiple-thread (SIMT) Processor:} SIMT model~\cite{nemirovsky2013multithreading} is widely adopted in modern GPUs~\cite{macri2015amd,o2014highlights} for accelerating parallel computing programs. The pipeline can be divided into front-pipeline which consists of instruction fetch, decode, and issue stages, middle-pipeline which consists of execution and writeback stages, and end-pipeline which consists of the commit stage. The front-pipeline and the end-pipeline usually involve complex control and logic circuits, such as warp table, SIMT stack, scoreboard, and load-store unit. The middle-pipeline contains arithmetic instruction and memory access instructions. MPU reduces the near-bank overhead by duplicate some part of the middle-pipeline to DRAM dies, and add corresponding instruction offloading mechanisms as detailed in Sec.\ref{subsec:arch:instr_offld}. The SIMT model also has some special features that require optimizations. First, the shared memory is extensively used for inter-thread communication inside the same thread block. Placing it in the base logic die may introduce extra communication traffic among the 3D layers. Second, the SIMT scheduling causes warps to access different row-buffers interchangeably, causing a row-buffer ping-pong effect. MPU explores architectural optimizations, near-bank shared memory and multiple activated row-buffers, for these two features detailed in Sec.\ref{subsec:arch:simt_opt}. \section{Conclusion}\label{sec:conclusion} This work proposes MPU (\underline{M}emory-centric \underline{P}rocessing \underline{U}nit), the first SIMT processor based on 3D-stacking near-bank computing architecture. First, we develop a hybrid pipeline where only a small number of hardware components are added on the DRAM dies and the instructions can be offloaded for near-bank computing. Second, we explore two architectural optimizations for the SIMT programming model, introducing a near-bank shared memory design to reduce data movements, and multiple activated row-buffers designs to increase bandwidth utilization. Third, we present an end-to-end compilation flow for MPU based on CUDA with a backend optimization to annotate the location of instructions as either near-bank or base logic die through the static analysis of programs. The end-to-end evaluation results of MPU on a set of representative benchmarks demonstrate $3.46\times$ speedup and $2.57\times$ energy reduction compared with an NVIDIA Tesla V100 GPU. We further conduct studies to show the performance improvement of MPU over prior 3D-stacking processors and identify the benefits of MPU's software and hardware optimizations. \section{Introduction}\label{sec:intro} Nowadays, parallel computing platforms play an increasingly important role in accelerating emerging data-intensive applications from various domains such as deep learning~\cite{lym2019prunetrain}, image processing~\cite{gu2020ipim}, and bioinformatics~\cite{huangfu2019medal}. In particular, a general purpose graphics processing unit (GPGPU) with its single-instruction-multiple-thread (SIMT) programming model benefits these workloads by exploiting massive memory-level parallelism and providing DRAM bandwidth higher than traditional CPUs. Despite the success of GPGPU in accelerating these workloads, its further performance scaling is constrained by the "memory bandwidth wall"~\cite{rogers2009scaling} challenge. From the application's perspective, workloads from these data-intensive applications usually require a large number of memory accesses with little computation. This characteristic makes memory bandwidth the dominating factor of performance. Unfortunately, from the technology's point of view, the scaling of main memory bandwidth for the compute-centric architecture is confined by both the insufficient number of off-chip I/O pins~\cite{liu2010understanding} and the expensive data movement energy~\cite{horowitz20141}. To further corroborate this bandwidth-bound behavior, in Sec.\ref{sec:motivation} we evaluate a set of representative benchmarks on an NVIDIA Tesla V100 GPU~\cite{Ref:GPU}, and find that on average the off-chip memory bandwidth utilization ($55.90\%$) overwhelmingly surpasses the ALU utilization ($2.57\%$) as shown in Fig.~\ref{fig:motivation}. The 3D-stacking near-data-processing (3D-NDP) architecture~\cite{balasubramonian2014near} emerges as a promising approach to alleviate this memory bandwidth bottleneck. Currently, high-end GPUs~\cite{macri2015amd,o2014highlights} are equipped with high-bandwidth memory (HBM) stacks~\cite{sohn20171}, where off-chip data transfers need to go through the low performance I/Os on the silicon interposer. The principal idea of 3D-NDP is to closely integrate affordable logic components adjacent to the memory stack. A large number of pioneering studies have adopted the processing-on-base-logic-die (PonB) architecture, where general purpose cores (e.g., SIMT cores~\cite{zhang2014top,hsieh2016transparent,pattnaik2016scheduling,kersey2017lightweight,kim2017toward,wen2017optimizing,nai2018coolpim,wu2020tuning}) are placed on the base logic die of the 3D stack to benefit from the intra-stack bandwidth enhancement (around $2\times$ w.r.t. HBM~\cite{wu2020tuning}). This solution provides a mediocre bandwidth improvement because intra-stack memory accesses are still bounded by the limited number of through-silicon-vias (TSVs) between memory dies and the base logic die. To overcome this bandwidth bottleneck of TSVs, recent near-bank accelerators~\cite{yazdanbakhsh2018dram,shin2018mcdram,aga2019co,gu2020ipim} further move simple arithmetic units closer to the DRAM banks to harvest the abundant bank-internal bandwidth (around $10\times$ w.r.t. process-on-logic-die solution~\cite{gu2020ipim}). These near-bank accelerators have demonstrated significant speedups (around $2\times-14\times$ w.r.t. GPU) thus they are promising to tackle the GPU's memory bandwidth issue. Despite its potential to provide plentiful memory bandwidth, there are still several challenges for near-bank computing in accelerating general purpose data-intensive workloads. First, the pipeline of SIMT processors contains complex logic components (e.g., load-store-unit~\cite{nyland2011systems}) and large register files~\cite{lindholm2008simulating}. Different from the prior near-bank accelerators customized for applications, the SIMT pipeline is needed for general purpose data-intensive workloads. Naively placing the whole pipeline with complex logic components and complicated data paths in the DRAM die introduces an intolerable area overhead~\cite{kogge1994execube,patterson1997case,draper2002architecture}. Second, the efficient support of the SIMT programming model on near-bank computing is needed, especially the inter-thread communication and the dynamic scheduling of warps~\cite{kirk2007nvidia}. As the shared memory is frequently used for inter-thread communication in a thread block, directly placing it on the base logic die will incur enormous TSV traffic. The dynamic scheduling of warps could disrupt the row-buffer locality of DRAM banks, seriously downgrading bandwidth utilization. Third, it requires both the end-to-end support of a parallel programming language to ease the programmers' burden and backend compiler optimizations for near-bank computing to exploit hardware potentials. To address these challenges, we design MPU (Memory-centric Processing Unit), the first SIMT processor based on 3D-stacking near-bank computing architecture, and an end-to-end compiler flow supporting CUDA programs~\cite{nvidia2007compute} with optimizations tailored to MPU. First, we design a hybrid SIMT pipeline for MPU where only a small number of registers and other lightweight components are added on the DRAM dies. At runtime, instructions are fetched, decoded, and issued on the base logic die while they can be offloaded to near-bank units (NBU) according to either compiler hints or hardware policies. To facilitate this hybrid execution of instructions, we propose an instruction offload engine to make instruction movement decisions, a register track table and a register move engine to flexibly transfer registers, and a load-store unit extension to handle near-bank load/store requests. Second, we propose two architectural optimizations for the SIMT model. For the shared memory, we move it to the DRAM die and restructure the core organization by placing all NBUs associated with the same core on the same DRAM die. For the dynamic scheduling of thread warps, we enable multiple activated row-buffers per DRAM bank to reduce the ping-pong effect thus improving the bandwidth. Third, we propose an end-to-end compilation flow to support CUDA programs. To optimize instruction offloading location on MPU's hybrid pipeline, we further propose a novel instruction and register location annotation algorithm through the static analysis of instructions, which effectively reduces the data movement among the shared TSVs. The contributions of our work are summarized as follows: \begin{itemize} \item To the best of our knowledge, we design the first near-bank SIMT processor using a hybrid pipeline with an instruction offloading mechanism. By integrating lightweight hardware components on the DRAM die, MPU achieves a small area overhead for general purpose processing. \item We propose two architectural optimizations for the SIMT model, including the near-bank shared memory to reduce data movement and multiple activated row-buffers to alleviate ping-pong effects in the dynamic warp scheduling. \item We develop an end-to-end compilation flow supporting CUDA programs on MPU and a novel backend optimization annotating the locations of registers and instructions. \item Evaluation results of representative data-intensive workloads show that MPU with all optimizations achieves $3.46\times$ speedup and $2.57\times$ energy reduction on average over an NVIDIA Tesla V100 GPU. \end{itemize} \section{Programming Interface and Compiler}\label{sec:compiler} \begin{lstlisting}[float=tp, language=C++, caption={Code example of scalar-vector multiplication.}, emph={Var, Func}, emphstyle={\color{blue}\ttfamily}, label={lst:example}, basicstyle=\footnotesize] // CUDA kernel for scalar-vector multiplication __global__ void ScalarVectorMultiply(float* input, float* output, float alpha, int len) { int numThreads = gridDim.x * blockDim.x; int tid = blockIdx.x * blockDim.x + threadIdx.x; for (int i = tid; i < len; i += numThreads) { output[i] = alpha * input[i]; } } int main() { ... // Memory allocation on MPU mpu_malloc(mpu_input_vec, len * sizeof(float)); mpu_malloc(mpu_output_vec, len * sizeof(float)); // Transfer the input data to MPU mpu_memcpy(mpu_input_vec, host_input_vec, len * sizeof(float), Host2Device); // Launch kernel for the computation on MPU ScalarVectorMultiply<<<GridCfg, BlockCfg>>>( mpu_input_vec, mpu_output_vec, alpha, len); // Transfer MPU computation results mpu_memcpy(host_output_vec, mpu_output_vec, len * sizeof(float), Device2Host); ... } \end{lstlisting} Sec.~\ref{sec:prog_interface} introduces the role of MPU in a heterogeneous platform and its programming interface. Sec.~\ref{sec:compiler} details the compiler support of transformations from high-level CUDA kernels to optimized programs running on the MPU. \subsection{Programming Interface}~\label{sec:prog_interface} MPU acts as a standalone accelerator in a heterogeneous platform with a similar usage of the GPU. In terms of the memory system abstraction, MPU has its own memory space independent from the host. In order to use MPU as an accelerator, the host is responsible to allocate the device memory on MPU, transfer input data to MPU, launch computation kernel to MPU, and transfer computation results from MPU. Listing~\ref{lst:example} is a code example of offloading scalar-vector multiplication to MPU. The main function contains code to handle the memory allocation ($mpu\_malloc$), memory transfers ($mpu\_memcpy$), and the kernel launch. These functions are implemented in MPU runtime for the communication between the host and MPU. During the kernel launch, MPU runtime is also responsible to dispatch the workload of thread blocks to MPU cores according to the thread block configurations. To ease the burden of implementing kernels on MPU, MPU supports CUDA programming language as a realization of the SIMT programming model. The $\_\_global\_\_$ function in line 2 of Listing~\ref{lst:example} for implementing the scalar-vector multiplication totally follows the CUDA syntax. As a result, we can leverage a GPU compiler as our front-end to parse the source code and generate intermediate instructions. Then, our compiler backend as detailed in Sec.~\ref{sec:compiler} is responsible for backend optimizations tailored for MPU architecture. \begin{algorithm}[!t] \begin{algorithmic} \caption{Location annotation algorithm} \label{algm:loc_annotation} \footnotesize \STATE \textbf{Input}: A kernel with a list of instructions $I$ \STATE \textbf{Output}: A location table $L$ for all registers and instructions. \STATE $L(reg)$: the location of an register $reg$. \STATE $L(instr)$: the location of an instruction $instr$. \STATE Init the location of all registers to unknown $U$. \STATE Init the location of all instructions to unknown $U$. \STATE Init the set of registers $R=\emptyset$. \STATE // Annotate the initial location to address registers, value registers, and \STATE // control registers. \FOR{$instr$ in $I$} \FOR{$reg \in \lbrace instr.SrcRegs \bigcup instr.DstRegs \rbrace$} \STATE $R = R \bigcup \lbrace reg \rbrace$ \ENDFOR \IF{$instr.type$ $\in$ $Instr_{jump}$} \STATE $L(instr.SrcRegs) = F$ \ENDIF \IF{$instr.type == ld.global$} \STATE $L(instr.SrcRegs) = F$ \STATE $L(instr.DstRegs) = N$ \ENDIF \IF{$instr.type == st.global$} \STATE $L(instr.SrcRegs) = N$ \STATE $L(instr.DstRegs) = F$ \ENDIF \IF{$instr.type \in \lbrace ld.shared, st.shared \rbrace$} \STATE $L(instr.SrcRegs) = N$ \STATE $L(instr.DstRegs) = N$ \ENDIF \ENDFOR \STATE // Propagate the location of known registers to others. \WHILE{$\forall reg \in R, L(reg)$ does not change} \FOR{$instr$ in $I$} \FOR{$reg$ in $instr.SrcRegs$} \IF{$L(reg) == U$} \STATE $L(reg) = L(instr.DstRegs)$ \ENDIF \IF{$L(reg) != L(instr.DstRegs)$} \STATE $L(reg) = B$ \ENDIF \ENDFOR \ENDFOR \ENDWHILE \STATE // Annotate the location of instructions according to the location of their \STATE // destination registers. \FOR{$instr \in I$} \STATE $L(instr) = L(instr.DstRegs)$ \ENDFOR \end{algorithmic} \end{algorithm} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/MPUCompilerBackend.pdf} \caption{The backend of MPU compiler generating MPU executable kernels from PTX kernels.} \label{fig:compiler:backend} \end{figure} \subsection{MPU Compiler}~\label{sec:compiler} To enable the SIMT programming model, MPU supports an end-to-end compilation flow from CUDA programs to MPU executable programs. This compilation flow contains a novel static analysis stage to optimize the location assignment of instructions by reducing data movement between MPU cores and near-bank units. Experimental results in Sec.\ref{subsec:exp:compiler_analysis} demonstrate that this novel location annotation improves the performance of MPU compared with a default hardware policy. The end-to-end compilation flow of MPU includes frontend stages and backend stages. In frontend stages, the MPU compiler reuses $nvcc$~\cite{nvidia2013compiler} to compile CUDA programs~\cite{kirk2007nvidia} to generate kernels in Parallel Thread Extension (PTX)~\cite{PTX} ISA which is a kind of intermediate representation of CUDA kernels. Then, the backend generates the MPU hardware executables from the PTX kernels, which includes three main stages as shown in Fig.\ref{fig:compiler:backend}. Among these three stages, the branch analysis and register allocation stages are common to support the SIMT programming model. The branch analysis stage infers the re-convergence point of each jump instruction so that the hardware can maintain a SIMT stack to handle thread divergence efficiently during the execution~\cite{fung2007dynamic}. This problem can be formulated as the post-dominator analysis of a control-flow graph representing the program. The register allocation stage analyzes the liveness of each virtual register in the program to build a register interference graph. The allocation of physical registers can then be formulated as a graph coloring problem on this register interference graph. \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/CodeBlocks.pdf} \caption{A code snippet of PTX instructions with a dependency chain of near-bank registers highlighted.} \label{fig:compiler:code-block} \end{figure} The location annotation is a novel backend stage to optimize the performance by annotating the location of instructions as either the near-bank NBU or the far-bank subcore on the base logic die. As shown in Fig.\ref{fig:instr_offld}, when executing the annotated kernels on MPU, the locations annotated on instructions will be used to finalize the runtime instruction offloading decision as explained in Sec.\ref{subsec:arch:instr_offld}. The main idea of this optimization is a heuristic approach based on the static analysis extracting the dependency chains of the control-related, address-related, and value-related registers. First, value-related registers will be annotated as near-bank registers while control-related and address-related registers will be annotated as far-bank registers. Then, instructions from the dependency chain of value-related registers are annotated as the near-bank instructions while the rest of instructions are annotated as the far-bank instructions. For example, Fig.\ref{fig:compiler:code-block} highlights a dependency chain of value registers. Offloading the compute instruction in line 3 to near-bank compute logic can eliminate the data transfer on TSVs for registers \%f1, \%f2, and \%f3. Finally, the annotated program will be passed to the register allocation stage where registers annotated as different locations will not share the same physical register. The static analysis of the location annotation is implemented as an iterative algorithm shown in Algorithm~\ref{algm:loc_annotation} to realize the idea of decoupling register dependency chains. Initially, the location of all registers is annotated as $U$ (unknown). The value registers of the global load/store instructions are annotated as $N$ (near-bank) while the address registers of these instructions are annotated as $F$ (far-bank) because of the LSU design. In addition to that, the location of predicative registers is annotated as $F$ (far-bank) because control-related instructions are executed on the far-bank pipeline stages. Then, our algorithm iteratively scans over the program to update register locations. In particular, if the destination register location is known for an instruction, its source registers will follow the same location annotation. If a register is annotated as both $N$ and $F$ from different instructions, it will be annotated as $B$, meaning that this register could appear on both far-bank and near-bank pipeline stages. This process will finish once the annotated locations of all registers converge. Finally, the location of instruction follows the same location as its destination register. \section{Architecture Design}~\label{sec:arch} First, we discuss MPU's high-level design in Sec.\ref{subsec:arch:microarch}. Second, we introduce MPU's hybrid pipeline in Sec.\ref{subsec:arch:hybrid_pipeline}, and further describe its instruction offloading mechanism in Sec.\ref{subsec:arch:instr_offld} and hybrid load-store unit in Sec.\ref{subsec:arch:hybrid_lsu}. Next, we present two architectural optimizations for SIMT model in Sec.\ref{subsec:arch:simt_opt}. \subsection{Microarchitecture Overview}~\label{subsec:arch:microarch} From the high-level, MPU adopts a scalable design with many processors (Fig.\ref{fig:arch}\circled{1}) interconnected by an off-chip network (similar to SERDES links in the HMC~\cite{leidel2016hmc}) as shown in the bottom of Fig.\ref{fig:arch} (1). Each processor is a 3D-stacking cube of a base logic die stacked with multiple DRAM dies, connected by vertically shared buses called the through silicon vias (TSVs)~\cite{xie2015stacking} (Fig.\ref{fig:arch}\circled{5}). The base logic die is horizontally partitioned into an array of SIMT cores (Fig.\ref{fig:arch}\circled{2}) interconnected by an on-chip 2D-mesh network~\cite{jiang2013detailed}. To harvest the near-bank bandwidth with small overheads on DRAM dies, MPU's SIMT core adopts a hybrid pipeline design. In the MPU core (Fig.\ref{fig:arch}\circled{2}), complex logics are placed on the base logic die, and some lightweight components in the execution stage are replicated on near-bank locations. On the base logic die, a core consists of four subcores (Fig.\ref{fig:arch}\circled{3}), an instruction cache, a warp scheduler, and components for handling inter-core traffic (network interface unit, router, and LSU-Remote). The TSVs (Fig.\ref{fig:arch}\circled{5}) are evenly divided among the cores ($64b$ data buses per core), via which the subcores can communicate with near-bank components on DRAM dies. All the core's near-bank components are located within the same DRAM die, containing four near-bank units (NBUs) (Fig.\ref{fig:arch}\circled{4}) and the shared memory. To enable efficient processing in this hybrid architecture (Sec.\ref{subsec:arch:hybrid_pipeline}), we propose a novel instruction offloading mechanism and a hybrid load-store unit design. In addition, MPU considers two architectural optimizations for the SIMT programming model in Sec.\ref{subsec:arch:simt_opt}. First, we find that naively implementing shared memory on the base logic die results in poor performance, so we restructure the core's 3D organization and develop a near-bank shared memory design. Second, we observe that the dynamic execution of SIMT warps may disrupt the row-buffer locality of DRAM banks, so we adopt a technique to enable multiple activated row-buffers inside the same DRAM bank. \subsection{Hybrid Pipeline}~\label{subsec:arch:hybrid_pipeline} As illustrated in Fig.\ref{fig:arch} (2), an MPU core (Fig.\ref{fig:arch} (2)\circled{2}) adopts a hybrid pipeline design that is split between the base logic die (subcore) (Fig.\ref{fig:arch} (2)\circled{3}) and the DRAM die (near-bank unit, NBU) (Fig.\ref{fig:arch} (2)\circled{4}). The frontend components of the SIMT pipeline mostly comprise of control flow and data dependency logic, so they are mainly contained in the subcores, including instruction fetch (I-cache, SIMT stack, warp table), decode, and issue (scoreboard) stages. For the backend pipeline, MPU duplicates some simple parts from the subcore to the NBU, including the register file, operand collectors, and ALUs. Other complex units such as LSU and network interface units are left on the base logic die. Note that the memory controller and the shared memory are entirely moved from the base logic die to the DRAM die, since near-bank memory controller will reduce TSV traffic for DRAM commands~\cite{yazdanbakhsh2018dram,gu2020ipim}, and shared memory can reduce TSV traffic for register movement (Sec.\ref{subsec:arch:simt_opt}). In addition to the original pipeline components, to assist flexible instruction offloading, each subcore also adds an instruction offload engine, a register move engine, and an associated register track table (Sec.\ref{subsec:arch:instr_offld}). Besides, the load-store unit (LSU) is modified and augmented to support remote data traffic and near-bank instruction offloading (sec.\ref{subsec:arch:hybrid_lsu}). \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/instr_offld.pdf} \caption{Instruction Offloading Mechanism.} \label{fig:instr_offld} \end{figure} \subsubsection{Instruction Offloading Mechanism}~\label{subsec:arch:instr_offld} The instruction offload engine after the issue stage will decide whether to offload the instruction for near-bank execution (\textit{Near-bank instr. data path} in Fig.\ref{fig:arch} (2)). The offloaded instruction will first travel through the TSVs, then access the near-bank operand collector to collect operand data from the near-bank register file. Then, the arithmetic and logic computation instructions will be sent to the near-bank ALUs, and the $ld/st$ instructions will be provided to the LSU-Extension for further processing, where the shared memory or the DRAM controller is involved. After the execution finishes, the resulting registers will be written back into the near-bank register file, and the instruction is returned to the subcore for the final commit, where the scoreboard clears its data dependency. The first step (Fig.\ref{fig:instr_offld}\circled{1}) is to identify the target instruction's location according to three policies with decreasing priority. The first policy will set the instruction with the far-bank location if the corresponding operation type ($OpCode$) falls in the far-bank operation set. For example, since address range checking and memory coalescing can only be performed by the LSU in the subcore, currently $ld/st.global$ instructions are classified as far-bank locations. If the first hardware policy cannot determine the location, then the compiler hint associated with the instruction will determine whether this instruction will be offloaded to NBU or not. If the instruction has no compiler hints, then the hardware will check the register track table. The instruction will be offloaded to NBU if all source registers have valid near-bank copies. Otherwise, the instruction will be passed to the far-bank. This default policy takes the far-bank subcore as a fall-back location for all instructions as it has the full pipeline support. The second step (Fig.\ref{fig:instr_offld}\circled{2}) is to determine the locations for the source registers using the hardware policy or the instruction location derived in the first step. For $ld/st.global$, the hardware policy will set the address register location to be far-bank, since it is required by the LSU. The data register location is set to near-bank. For $ld/st.shared$, both the address register and the data register are set to near-bank location. If the hardware policy is not given, all the source and destination registers' locations will follow the instruction's location. The third step (Fig.\ref{fig:instr_offld}\circled{3}) will move registers to their corresponding locations if they are not currently available in the register track table (\textit{Register Movement data path} in Fig.\ref{fig:arch} (2)). For example, the instruction offload engine may require register $\%r1$ to be valid in the far-bank register file, while the register track table indicates $\%r1$ only exists in the near-bank register file (e.g., \textit{FBValid} is False but \textit{NBValid} is True). Then, the far-bank register move engine initiates a request to the near-bank register move engine, which then reads $\%r1$ from the near-bank register file and returns it to the far-bank register move engine. The far-bank register move engine will write $\%r1$ into the far-bank register file, and the instruction offloading engine will start instruction offloading once all registers are in the target locations. Note that we optimize register locations in Sec.\ref{sec:compiler}, so a hit in the register track table will not cause register movement. In the end, the register track table is updated to reflect the most current register location information. \subsubsection{Hybrid Load-store Unit (LSU)}~\label{subsec:arch:hybrid_lsu} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/lsu.pdf} \caption{Three load-store unit (LSU) components' microarchitecture using $ld.global$ data path as an example. (1) LSU in each subcore, (2) LSU-Remote in each core, (3) LSU-Extension in each near-bank unit} \label{fig:hybrid_lsu} \end{figure} The original LSU in each subcore is augmented with the LSU-Remote in each core to handle remote traffic (\textit{Remote $ld/st.global$ data path} in Fig.\ref{fig:arch} (2)), and the LSU-Extension in each NBU to handle both near-bank instruction offloading and local DRAM transactions (\textit{Local $ld/st.global$ data path} in Fig.\ref{fig:arch} (2)). We will introduce them and use $ld.global$ instruction as an example in the following paragraphs. \textbf{LSU:} As shown in Fig.\ref{fig:hybrid_lsu} (1), after receiving a $ld.global$ instruction, the LSU first performs address range checking (Fig.\ref{fig:hybrid_lsu}\circled{1}) to split the instruction to remote access and local access. If there is remote access, it is encoded and sent to the network interface unit (Fig.\ref{fig:hybrid_lsu}\circled{2}) to request remote data. For the local access, the following steps are performed concurrently. First, the LSU will check if all the SIMT mask fields are valid or not to determine thread divergence (Fig.\ref{fig:hybrid_lsu}\circled{3}). Second, the LSU will perform memory coalescing (Fig.\ref{fig:hybrid_lsu}\circled{4}) on the local memory addresses. It will also judge if all the memory addresses are perfectly coalesced, meaning that the load request will access a continuous DRAM address space. Third, the LSU will compare the $NBU\_id$ field of the generated DRAM addresses with the $NBU\_id$ associated with the register in the given warp (Fig.\ref{fig:hybrid_lsu}\circled{5}). The $ld.global$ instruction is decided for near-bank offloading (Fig.\ref{fig:hybrid_lsu}\circled{6}) only if all threads are valid, register and DRAM addresses have the same $NBU\_id$, and all DRAM addresses are coalesced. Note that since all of the above assumptions are satisfied, we only need to transfer the leading DRAM address, register ID, and the $NBU\_id$. The SIMB mask will be ignored and restored in the LSU-Extension side. If the above conditions cannot be met, the LSU will issue DRAM transactions to the LSU-Extension (Fig.\ref{fig:hybrid_lsu}\circled{7}) and gather returned local DRAM data. Combined with the returned remote DRAM data, the final DRAM data will be used to compose a register write request and transferred for near-bank writeback. The reason to load the DRAM data first to the near-bank register file is that it can benefit near-bank execution due to the reduction of TSV traffic. For far-bank execution, the register data will eventually be brought down to the far-bank register file, so there is no increase in the TSV traffic. \textbf{LSU-Remote:} As shown in Fig.\ref{fig:hybrid_lsu} (2), LSU-Remote receives remote $ld.global$ request and decodes them into a series of DRAM addresses and DRAM $NBU\_id$. It then sends these DRAM transactions to the LSU-Extension through the TSVs. After receiving the returned DRAM data, it encodes it together with the source core location and request ID and composes a response packet, finally sending it back to the original core's LSU who requests this DRAM data. \textbf{LSU-Extension:} As shown in Fig.\ref{fig:hybrid_lsu} (3), LSU-Extension has two data paths. In Fig.\ref{fig:hybrid_lsu} (3-a), it handles DRAM transaction requests from the TSVs by sending the DRAM addresses to the memory controller, and sends back the returned DRAM data through TSV either to the LSU-Remote or the LSU. In Fig.\ref{fig:hybrid_lsu} (3-b), it handles offloaded local $ld.global$ instruction by first restoring the full address list from the leading DRAM address. Then, it sends the DRAM addresses to the memory controller, gathers returned DRAM data, and stores the data into the near-bank register file according to the register ID. \subsection{Optimizations for the SIMT model}~\label{subsec:arch:simt_opt} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/smem_arch.pdf} \caption{(1) Vertical and (2) horizontal core structure.} \label{fig:smem_arch} \end{figure} \textbf{Near-bank Shared Memory Design:} The shared memory is extensively used for inter-thread communication in the same thread block for a great number of important GPU benchmarks~\cite{kirk2007nvidia}. If the default shared memory location is set in the far-bank subcore on the base logic die, a lot of register data movement traffic will be created and the TSVs will be congested, causing significant performance loss. Thus, it will be desirable to enable a near-bank shared memory design and set the default register location for $ld/st.shared$ to the near-bank register file. However, this is impossible in the vertical core structure (Fig.\ref{fig:smem_arch} (1)) in the default HMC-style setting~\cite{leidel2016hmc}, where all the NBUs associated with a core are distributed among multiple 3D stacks. Under such an assumption, moving the shared memory ($Smem$) to each NBUs means that the shared memory is split into each 3D layer and inter-thread shared memory accesses need to go through the bandwidth-bound TSVs. To enable the near-bank shared memory, we restructure the core's 3D-organization as shown in the horizontal core design in Fig.\ref{fig:smem_arch} (2). In our solution, we put all NBUs of the same core into the same DRAM die, so that all NBUs can access the near-bank shared memory without TSV's constraints. In Sec.\ref{subsec:exp:hw_analysis}, we confirm the benefits of this optimization on benchmarks that extensively use shared memory. \textbf{Multiple Activated Row-Buffers Design:} The dynamic execution of warps will create a ping-pong effect on DRAM's row-buffer. Ideally, warps from the same thread block executing the same memory access instruction will have continuous DRAM addresses and result in a high row-buffer hit rate. However, the hardware dynamically issues available instructions from each warp, resulting in the ping-pong effect of different warps accessing a few row-buffers irregularly. Since MPU has no hardware cache, this ping-pong effect will cause frequent DRAM precharge and activations, significantly downgrade its performance. To solve this issue in a software transparent way, we observe that for a lot of benchmarks we evaluate, only a small set of row-buffers are active in a short period. If we can enable multiple row-buffers to be simultaneously activated, then this ping-pong effect will be greatly alleviated. Based on the design of MASA (Multitude of Activated Subarrays)~\cite{kim2012case} which enables multiple subarrays' row-buffers to be activated in parallel, we change our address mapping so that continuous DRAM row addresses will be mapped to interleaved subarrays' physical row. Extra row address latches and access transistors are added to enable different warps to access different row buffers in independent subarrays. Through evaluations in Sec.\ref{subsec:exp:hw_analysis}, we confirm that this design can decrease the row-buffer miss rate and increase performance for multiple benchmarks. \section{Evaluation}\label{sec:exp} In Sec.\ref{subsec:exp:setup}, we introduce the experiment setup and methodologies. In Sec.\ref{subsec:exp:ppat}, we show the performance, area, energy, and thermal results of MPU. In Sec.\ref{subsec:exp:hw_analysis}, we demonstrate the benefit of MPU's architecture optimizations and the comparison with the prior processing-on-base-logic-die designs. In Sec.\ref{subsec:exp:compiler_analysis}, we present the effectiveness of the location annotation in our compiler backend optimization. \subsection{Experimental Setup}\label{subsec:exp:setup} \begin{table}[!t] \centering \scriptsize \caption{The workloads of the benchmark suite.} \label{tab:exp:benchmark} \begin{tabular}{|l|l|l|l|} \hline Workload & App Domain & Reference & Description \\ \hline BLUR & Image Processing & Halide~\cite{ragan2013halide} & 3x3 blur. \\ CONV & Machine Learning & TensorFlow~\cite{abadi2016tensorflow} & 3x3 conv. \\ GEMV & Linear Algebra & cuBLAS~\cite{cuBLAS} & Matrix-vector multiply. \\ HIST & Image Processing & CUB~\cite{CUB} & Histogram. \\ KMEANS & Machine Learning & Rodinia~\cite{che2009rodinia} & K-means clustering. \\ KNN & Machine Learning & Rodinia~\cite{che2009rodinia} & K-nearest-neighbour. \\ TTRANS & Linear Algebra & cuBLAS~\cite{cuBLAS} & Tensor transposition. \\ MAXP & Machine Learning & TensorFlow~\cite{abadi2016tensorflow} & Max-pooling. \\ NW & Bioinformatics & Rodinia~\cite{che2009rodinia} & Sequence alignment. \\ UPSAMP & Image Processing & Halide~\cite{ragan2013halide} & Image upsample. \\ AXPY & Linear Algebra & cuBLAS~\cite{cuBLAS} & Vector add. \\ PR & Linear Algebra & CUB~\cite{CUB} & Parallel reduction. \\ \hline \end{tabular} \end{table} \noindent \textbf{Benchmark.} To evaluate the effectiveness of the MPU design in supporting data-intensive parallel programs, we select a set of representative CUDA workloads as shown in Table.\ref{tab:exp:benchmark}. In particular, these workloads are from various important application domains including image processing, machine learning, linear algebra, and bioinformatics. Because our MPU compiler needs either CUDA source code or PTX kernels to generate MPU executable programs, we have CUDA implementations of these workloads from either well-known GPU benchmarks, such as Rodinia~\cite{che2009rodinia}, or writing CUDA programs in the same functionality while achieving performance comparable to state-of-the-art libraries, such as cuBLAS~\cite{cuBLAS}. \begin{table}[!t] \scriptsize \centering \caption{MPU hardware configuration parameters.} \label{tab:hw_config} \begin{tabular}{|l|l|} \hline Parameter Names & Configuration \\ \hline \hline Proc/(3D,Core)/(Subcore,NBU/Bank/RowBuf) & 8/(4,16)/(4,4/4/4) \\ SIMT/BankIO/TSV/(on)offchip\_bus (Bit) & 32/256b/1024/(256)128 \\ Bank/Icache/(Far)Near-bank RF/Smem (Byte) & 16M/128K/(32K)16K/64K \\ \hline tRCD/tCCD/tRTP/tRP/tRAS/tRFC/tREFI~\cite{kim2015ramulator} & 14/2/4/14/33/350/3900 \\ fCore / fTSV / fRouter / f(on)offchip\_bus (GHz) & 1/2/2/(2)2 \\ \hline RD,WR/PRE,ACT/REF/RF/SMEM~\cite{chen2012cacti} (J/access) & 0.15n/0.27n/1.13n/40.0p/22.2p \\ Operand\_collector / LSU-Extension (J/access) & 41.49p/39.67p \\ TSV~\cite{o2017fine} / (on)off-chip bus~\cite{chen2012cacti,pugsley2014ndc} (J/bit) & 4.53p/(0.72p)4.50p \\ \hline DRAM\_rowbuffer\_policy / DRAM\_schedule & open\_page / FR-FCFS \\ \hline \end{tabular} \end{table} \textbf{Hardware Configuration.} Using the 3D-stacking memory configuration similar to the previous near-bank accelerators~\cite{shin2018mcdram,yazdanbakhsh2018dram,aga2019co,gu2020ipim}, MPU needs no changes to DRAM's core circuit except the multiple activated row-buffers enhancement~\cite{kim2012case}. The detailed hardware configuration, latency values, energy consumption, and DRAM settings are presented in Table.\ref{tab:hw_config}. MPU contains $8$ processors (total $\sim926mm^2$) to compare with a Tesla V100 GPU card~\cite{Ref:GPU} with $4$ HBM stacks (total $\sim1199mm^2$), where one HBM stack consumes $\sim96mm^2$ footprint~\cite{sohn20171}. \textbf{Simulation Methodology.} We develop an event-driven simulator using SimPy~\cite{matloff2008introduction}, which adapts the simulation framework from GPGPU-Sim~\cite{bakhoda2009analyzing} for SIMT core model, Ramulator~\cite{kim2015ramulator} for DRAM model, and Booksim~\cite{jiang2013detailed} for interconnect network model. MPU is designed to run at a clock frequency of 1GHz under the 20nm technology node. For \underline{energy and latency modeling}, we first use the design compiler to get the power values for the SIMT core pipeline based on Harmonica project~\cite{kersey2017lightweight}. Then, we use cacti~\cite{chen2012cacti} to evaluate the register file, shared memory, and the DRAM bank. Since the major components in the operand collector and the LSU-Extension are SRAM buffers, we also use cacti to evaluate their latency and energy values. We model the router latency and energy consumption using BookSim2's model~\cite{jiang2013detailed}, and the TSV and on/offchip buses adopt parameters from previous studies~\cite{o2017fine,chen2012cacti,pugsley2014ndc}. For the ALU, we use the measured results from PTX instructions~\cite{arafa2019low,arafa2020verified}. For \underline{area evaluation}, we use design compiler~\cite{dupenloup2004automatic} to analyse pre-layout area of the vector ALU and the SIMT core pipeline~\cite{kersey2017lightweight}. We use AxRAM's area result~\cite{li2015rram} for the in-dram memory controller and scale it to 20nm. The area for the shared memory, register file, operand collector, and LSU-Extension are derived from cacti~\cite{chen2012cacti}. For all the above-evaluated components on the DRAM die, we conservatively assume $\times2$ area overhead considering the reduced number of metal layers in the DRAM process~\cite{yazdanbakhsh2018dram}. For multi-row-buffer support, we include the overhead of $128$ extra row address latches~\cite{kim2012case} per memory controller to enable simultaneous activations of $4$ subarray row buffers. For the \underline{GPU evaluation}, the GPU performance and power results are collected with the help of \emph{nvprof} and \emph{nvidia-smi}, respectively. \subsection{Performance, Area, Energy, and Thermal Analysis}\label{subsec:exp:ppat} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/time_speedup_gpu.pdf} \caption{(1) Execution time and speedup comparison with the GPU. (2) Workloads memory intensity and speedup.} \label{fig:performance} \end{figure} \textbf{Performance.} MPU achieves $3.45\times$ speedup on average over the GPU as shown in Fig.\ref{fig:performance} (1). This speedup is contributed by the improved memory bandwidth from the hybrid-pipeline near-bank architecture, the architecture optimizations for the SIMT programming model (Sec.\ref{subsec:exp:hw_analysis}), and the compiler optimizations for the locations of instructions (Sec.\ref{subsec:exp:compiler_analysis}). To further explain different speedup numbers across workloads, we plot the memory intensity (Byte/Instruction) and the speedup of these workloads in Fig.\ref{fig:performance} (2). First, we observe that the speedup number has a strong correlation with the memory intensity because the memory intensity represents the demand of workloads for memory bandwidth. As MPU provides more memory bandwidth than the GPU ($4.13\times$ in measurement), for benchmarks with simple memory access and compute patterns (e.g., AXPY), the speedup is proportional to the memory intensity. Second, we find that some benchmarks show higher (KMEANS) and lower (TTRANS, UPSAMP) speedup numbers than their memory intensity. The reason is that memory dependency cannot reflect memory latency characteristics and complex program behaviors. For KMEANS, MPU provides additional latency reduction compared to the GPU, as the compute instructions are mostly data-dependency free so the performance is less sensitive to the number of instructions. For TTRANS and UPSAMP, complicated control flow and data-dependency hinder the memory parallelism, so the abundant memory bandwidth in MPU is not fully utilized. \begin{table}[!t] \centering \scriptsize \caption{Area evaluation of MPU components on the DRAM die considering DRAM process overheads.} \label{table:area} \begin{tabular}{|l|l|l|l|} \hline Name & Number & Area Per Die ($mm^2$) & Overhead ($\%$)\\ \hline \hline Shared Memory & 4 & 0.84 & 0.88 \\ Register File & 16 & 9.71 & 10.12 \\ Memory Controller & 16 & 0.63 & 0.66 \\ Operand Collector & 64 & 2.43 & 2.53 \\ Vector ALU & 16 & 3.74 & 3.90 \\ LSU-extension & 16 & 2.43 & 2.53 \\ Multi-row-buffer Support & 64 & 0.01 & 0.01 \\ \hline Total & - & 19.80 & 20.62 \\ \hline \end{tabular} \end{table} \textbf{Area.} MPU's hybrid pipeline architecture is area-efficient because only a small part of the pipeline backend components are added in the DRAM die, saving the area for other pipeline units. In Table.\ref{table:area}, we evaluate the area of added components and normalize the total overhead to a DRAM die ($96mm^2$~\cite{sohn20171}). Thanks for our compiler optimizations (Sec.\ref{subsec:exp:compiler_analysis}) which significantly reduce the near-bank register usage, we shrink the near-bank register file to half the size of the far-bank register file. This brings the total area overhead from $30.74\%$ to $20.62\%$. We argue this overhead is small for a general purpose SIMT processor, comparing to $10.71\%$ area overhead in previous work which only supports domain-acceleration~\cite{gu2020ipim}. According to the synthesis result of Harmonica~\cite{kersey2017lightweight} scaled to $20nm$, the $3.4mm^2$ area of the SIMT core with an instruction cache, operand collectors, and a load-store unit can perfectly fit into the available area ($3.5mm^2$~\cite{gao2017tetris}) on the base logic die. On the contrary, if the whole core is placed in the DRAM die, the total area overhead will increase significantly ($2\times$ compared with the hybrid pipeline of MPU). \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/energy.pdf} \caption{Energy and energy reduction comparison with the GPU.} \label{fig:energy} \end{figure} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/energy_breakdown.pdf} \caption{MPU energy breakdown.} \label{fig:energy_breakdown} \end{figure} \textbf{Energy.} MPU achieves $2.57\times$ energy reduction on average over the GPU (Fig.\ref{fig:energy}). The energy reduction mainly comes from the reduction of expensive data movement compared with the GPU, since MPU has a much shorter and simpler data path to access a core's local DRAM banks. Compared with the complex data path components in the GPU, where the data needs to travel through the TSVs inside the HBM, off-chip links, L2 cache, crossbar network, and then L1 cache to the local register file, the MPU directly offloads the instruction to the DRAM dies to transfer data between the near-bank register file and the DRAM banks. Also, we observe that for each benchmark the energy reduction in Fig.\ref{fig:energy} is approximately proportional to the speedup in Fig.\ref{fig:performance} (1). This is because MPU's increased bank-level bandwidth is a result of near-bank data access, which also contributes to the reduction of data movement energy. In order to further analyze the energy consumption, we provide a detailed energy breakdown in Fig.\ref{fig:energy_breakdown}. We discover that most of the energy in MPU ($92.94\%$) is spent on computation (ALU consumes $39.82\%$), data access ($31.90\%$), and data movement ($21.22\%$). The data access energy contains local register file access (operand collectors (OPC) and register file (RF) consume $15.47\%$) and DRAM accesses ($16.42\%$). For data movement, the energy spent on remote data movement (Network consumes $4.43\%$) is significantly smaller than the local data movement (TSV consumes $16.79\%$). This well explains the data movement saving advantages of MPU compared to GPU to achieve great energy reduction. \textbf{Thermal Analysis.} MPU's peak power is $83W$ per processor considering both DRAM dies and the base logic die, and the peak power density is $552mW/mm^2$. The normal operating temperature for HBM2 DRAM dies is $105^{\circ}C$~\cite{sohn20171}, and we conservatively assume the DRAM dies in our case operates under $85^{\circ}C$. A prior study on 3D PIM thermal analysis~\cite{zhu2016integrated} shows that active cooling solutions can effectively satisfy this thermal constraint ($85^{\circ}C$). Both commodity-server active cooling solution~\cite{milojevic2012thermal} (peak power density allowed: $706mW/mm^2$) and high-end-server active cooling solution~\cite{eckert2014thermal} (peak power density allowed: $1214mW/mm^2$)) can be used. \subsection{Architecture Analysis}\label{subsec:exp:hw_analysis} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/exp_smem.pdf} \caption{Comparison of near-bank / far-bank smem.} \label{fig:exp_smem} \end{figure} \textbf{Shared memory optimization.} To understand the benefit of our near-bank shared memory, Fig.\ref{fig:exp_smem} shows performance results compared with placing the shared memory on the base logic die, denoted as far-bank shared memory. In the same figure, we also plot TSV traffic improvement of near-bank shared memory design w.r.t. far-bank shared memory design. On average, near-bank shared memory design achieves $1.48\times$ speedup and $1.89\times$ TSV traffic improvement compared with far-bank shared memory design. The performance benefits of near-bank shared memory come from the extensive use of shared memory. If the shared memory location is far-bank, the contents of near-bank registers need to be brought down to the base logic die for the inter-thread communication through shared memory. This will create a lot of register movement traffic and congest the TSVs. For the near-bank shared memory design, the default locations of value registers for $ld/st.global$ and $ld/st.shared$ are all near-bank. Thus less register movement will be involved, easing the bandwidth pressure on the TSVs. However, since the number of instructions offloaded to NBUs also rises, this may increase TSV traffic, as we observe that for some workloads with speedup larger than 1, the TSV traffic improvement may be slightly less than 1 (HIST, NW). For workloads that do not use shared memory, both the performance and TSV traffic are identical to the location of shared memory. \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/exp_rb.pdf} \caption{Comparison of the number of activated row-buffers on (1) performance and (2) row-buffer miss rate} \label{fig:exp_rb} \end{figure} \textbf{Multiple activated row-buffers analysis.} To understand the benefits of multiple activated row-buffers, we compare the performance of all workloads running on MPU with different numbers of activated row-buffers. Fig.\ref{fig:exp_rb} shows such performance comparisons where the speedup is normalized to a single row-buffer. As shown in the Fig.\ref{fig:exp_rb} (1), the speedup numbers are $1.10\times$ and $1.25\times$ when we increase the number of activated row-buffers to $2$ and $4$, respectively. The row-buffer miss rate in Fig.\ref{fig:exp_rb} (2) indicates that as we increase activated row-buffer numbers to $2$ and $4$, the miss rate reduces from $15.60\%$ to $9.20\%$ and $5.45\%$, respectively. Because more activated row-buffers can effectively reduce the row-buffer ping-ping effect in the dynamic scheduling of warps, increasing the number of activated row-buffers effectively reduces average DRAM access latency to improve end-to-end time. Especially, we observe that KNN, UPSAMP, and AXPY significantly benefit from the increased number of activated row-buffers due to severe ping-pong effects on a single row-buffer. \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/mpu_pob.pdf} \caption{Execution time and speedup comparison with the processing-on-base-logic-die solution.} \label{fig:mpu_pob} \end{figure} \textbf{Comparison with processing-on-base-logic-die (PonB) solution.} We compare MPU with the state-of-the-art general purpose near-data SIMT processors by placing all compute logic on the base logic die, denoted as PonB. The end-to-end execution time shown in Fig.\ref{fig:mpu_pob} demonstrates that on average MPU achieves $1.46\times$ speedup up compared with the PonB solution. This performance improvement is contributed by a significant amount of instructions offloaded for near-bank computations. This reduces data movements on the TSVs which have a much lower bandwidth than bank-level memory bandwidth. \subsection{Effectiveness of Compiler Optimizations}\label{subsec:exp:compiler_analysis} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/register_breakdown.pdf} \caption{Register location analysis.} \label{fig:register_breakdown} \end{figure} \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{isca21-paper/fig/inst_location_perf.pdf} \caption{Comparison of performance for different instruction location policies.} \label{fig:inst_location_perf} \end{figure} We first conduct static analysis according to the iterative algorithm introduced in Sec.\ref{sec:compiler} to infer the locations of registers. The breakdown of registers on different locations for all workloads is shown in Fig.\ref{fig:register_breakdown}. On average, $32.5\%$ registers only appear in near-bank locations, $63.7\%$ registers only appear in far-bank locations, and $3.8\%$ registers could appear in both locations. Because only registers appearing in near-bank locations need to use the near-bank register file, we effectively shrink the size of the near-bank register file to reduce its area overhead. This breakdown also demonstrates a clear separation of near-bank registers from far-bank registers. Only a small portion of registers could appear in both locations. This clear separation comes from a clear separation of two classes of dependency chains. The first class involves computations on the data value loaded from the DRAM, and the second class involves integer calculations for DRAM addresses and control-flow related variables, such as loop variables. Usually registers for these two classes of dependency chains do not interfere with each other, as registers associated with the first class usually exist in near-bank locations, and registers related to the second class reside on the base logic die. Therefore, for most registers (more than $95\%$) we can assign them to a certain near/far-bank location to reduce the register file usage. We further evaluate the performance of different instruction location policies with the GPU as shown in Fig.\ref{fig:inst_location_perf}. On average, using the proposed instruction annotation optimizations, we achieve $3.45\times$ speedup w.r.t. GPU. However, using hardware's default instruction location policy, offloading all instructions to near-bank compute-logic, or offloading all instructions to far-bank compute-logic, we achieve $1.92\times$, $1.22\times$, and $1.78\times$ speedup, respectively. Compared with the default hardware policy and both naive offloading strategies, our instruction location annotation is based on the annotated register location. Because of the clear separation of two classes of aforementioned dependency chains, our instruction location annotation assigns most of the computation on data values to near-bank and computation on addresses or control-flow conditions to far-bank. As a result, the register movement traffic on TSVs is minimized, which eventually boosts the performance of programs running on MPU. \section{Related Work}\label{sec:related} \textbf{General Purpose Near-data-processing Platforms:} Pioneering studies~\cite{kogge1994execube,kang1999flexram,draper2002architecture} attempted to integrate the entire processor on the DRAM die, which incurs considerable area overheads. Compared with them, MPU only places lightweight components in the DRAM dies through a hybrid pipeline, which significantly reduces the overhead. Recently, there are a number of practical general purpose near-data-processing solutions that explore near-cache~\cite{lockerman2020livia}, near-memory-controller~\cite{onur2015reducing}, near-DIMM~\cite{asghari2016chameleon,alian2018application}, and 3D-stacking processing-on-logic-die CPU-style~\cite{ahn2015pim,boroumand2016lazypim,cho2020chonda} and GPU-style~\cite{hsieh2016transparent,pattnaik2016scheduling,kim2017toward,wen2017optimizing,wu2020tuning} platforms. However, these solutions have several drawbacks. First, they have moderate bandwidth improvement, due to the hierarchically shared bus of the main memory. To overcome this drawback, MPU unleashes bank-internal bandwidth through near-bank computing. Second, the communication between the host and the near-data logic introduces extra data traffic because of shared memory space, which may offset the benefit of near-data-processing, including fine-grained instruction offloading overhead~\cite{ahn2015pim,hsieh2016transparent}, cache coherence traffic~\cite{boroumand2016lazypim}, concurrent host access stall~\cite{cho2020chonda}, and inconsistent data layout requirement~\cite{wu2020tuning}. Different from these prior studies, MPU has an independent memory space and supports end-to-end kernel execution, the same as discrete GPU cards~\cite{macri2015amd,o2014highlights}. \textbf{Domain-specific Near-data-processing Accelerators:} A large number of previous studies have explored domain-specific accelerators using near-data-processing ideas, including approximate computing~\cite{yazdanbakhsh2018dram}, image and video processing~\cite{xie2017processing,gu2020ipim}, deep learning~\cite{akin2019case,shin2018mcdram}, graph analytics~\cite{nai2017graphpim}, bioinformatics~\cite{huangfu2019medal}, garbage collection~\cite{jang2019charon}, address translation~\cite{picorel2017near} and data transformation~\cite{akin2015hamlet}. These designs usually adopt domain-specific processing logic, customized data paths, and application-tailored software mapping strategies. The lack of programmability for these accelerators confines them to a niche application market, adding non-recurring engineering costs for silicon manufacturing. In contrast, the SIMT programming model supported by MPU can benefit a wide range of data-intensive parallel programs, and our end-to-end compilation flow greatly eases the burden of programmers. \textbf{Analog Process-in-memory Architecture:} In addition to the digital near-data-processing solutions, recently there is a surge in researches about analog process-in-memory (PIM) architecture~\cite{strukov2008missing,mittal2019survey}. Different from the digital solution where the memory array and the computing logic are separate, analog solutions modify the memory array to integrate computing functionalities within memory arrays, thus achieving extremely high computation throughput and energy efficiency. However, these designs suffer from analog noise~\cite{li2015rram}, limited write-endurance issues of non-volatile devices~\cite{imani2019floatpim}, and high overhead of analog-digital converters~\cite{xia2016switched}. Although analog PIM solutions are promising for certain application domains such as neural network~\cite{shafiee2016isaac,chi2016prime,song2017pipelayer}, they are still challenging for general purpose computing usage. In comparison, MPU adopts commercially available 3D stacking technologies~\cite{leidel2016hmc,sohn20171} without modifying the DRAM bank's circuit, and this work has demonstrated promising results of MPU on general purpose data-intensive workloads. \section*{Acknowledgements} \bibliographystyle{IEEEtranS}
{'timestamp': '2021-03-12T02:23:07', 'yymm': '2103', 'arxiv_id': '2103.06653', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06653'}
arxiv
\section*{Abstract} The Covid-19 pandemic caused disruptive effects for individuals, firms, and societies. In this paper, we offer insights on the major issues and challenges firms are facing in the Covid-19 pandemic, as well as their concerns for Corporate Social Responsibility (CSR) themes. \ale{To do so}, we investigate large Italian firms’ discussion on Twitter in the first nine months of the pandemic. Specifically, we ask: How is firms’ Twitter discussion developing during the Covid-19 pandemic? Which CSR dimensions and topics do firms discuss? To what extent do they resonate with the public?\\ \fab{We downloaded all Twitter posts from 1st of March, 2020, to 17th of November, 2020 by the accounts of the largest Italian firms, i.e. those with 250 or more employees. We then built the bipartite network of accounts and hashtags and, using an entropy-based null model as a benchmark, we projected the information contained in the network into the accounts layers, identifying a network of accounts, in which a link indicates a non trivial similarity in terms of their usage of hashtags. }\ale{We find that the conversation is focused around 13 communities, 10 of which include Covid-19 themes. The core of the network is formed of 5 communities, which deal with environmental sustainability, digital innovation and safety. Firms' ownership type does not seem to influence the conversation. 10 communities out of 13 mention hashtags related to CSR, with the environmental and social dimensions as the prevalent ones. Interestingly enough, the social dimension seems more relevant in the communities dealing with digital innovation and safety. However, the relevance of CSR hashtags is very small at the single message level, \fab{but }with some peculiarities arising in specific communities. Also, users engage very little on CSR themes, with some differences showing in a few communities.\\ \alee{Overall, our paper highlights the role of network methods on Twitter data as a tool which can support managers and policy makers to design their strategies and decision making, capturing firms’ emerging issues and relevant themes.} With the relevance of CSR dimensions and stakeholder engagement varying depending on the community, we also propose network methods as an effective way to capture the differences in firms' and stakeholders' CSR concerns. } \section{Introduction} The Covid-19 pandemic impacted multiple business dimensions and forced firms to rethink the way they do their businesses, coping with what has been called ``the new normal”~\cite{Ratten2020}. While most research~\cite{Almeida2020,Amore2020,Crick2020a,Evans2020,Ivanov2020,Juergensen2020} explored Covid-19 effects on firms using conceptual, survey or interview-based methods, only one paper, to the best of our knowledge, examined firms’ challenges through social media, focusing on the effects on supply chains~\cite{sharma2020covid}. Among others, the analysis of online social networks is a promising tool to understand current issues, trends and challenges firms are facing~\cite{Pilar2019}. In the last 15 years, social media revolutionized communication, making it cheaper and faster than ever before and opening a new channel for firms to \fab{directly} communicate and interact with their stakeholders. An increasing number of firms opened social media pages~\cite{Reilly2014}, which also allowed a new research stream to develop \cite{li2019identifying,sharma2020covid}. Management research focusing on social media mostly dealt with Corporate Social Responsibility (CSR) and stakeholder engagement, with manual collection~\cite{Reilly2014} and labelling~\cite{Manetti2016}, and linear regressions~\cite{Gomez-Carrasco2020,Yang2020,Yang2017}. These methods bring a number of limitations. First, they are able to capture only a small number of firms, which is generally less than a hundred~\cite{Saxton2019,Yang2020,Yang2017}. Second, they follow \emph{a priori} approaches~\cite{Saxton2019}, that do not allow new insights to emerge from data. To the best of our knowledge, few papers examined firms’ communication strategies adopting network methods~\cite{Chae2018a,Colleoni2013}, and none of them analyzed firms’ discussion during the pandemic. As a data-driven approach could reveal complex patterns~\cite{choudhury2018machine}, we adopt a complex network analysis to understand firms’ conversation on Twitter at the beginning of the Covid-19 pandemic. Doing so, we aim at understanding firms’ issues and challenges during the Covid-19 crisis, as reflected in the Twitter discussion. \ale{Specifically, we aim at answering three explorative research questions: How is firms’ Twitter discussion developing during the Covid-19 pandemic? Which CSR dimensions and topics do firms discuss? To what extent do they resonate with the public? \fab In order to detect similarities in the usage of hashtags, we represent the system as a bipartite network between accounts and hashtags. We then project the information contained in the network on the layer of accounts, to find users using similar hashtags. The network is then validated via a comparison with a null model. In this sense, we opt for the Bipartite Configuration Model (\emph{BiCM},~\cite{Saracco2015}), i.e. an entropy-based networks null-model, since it is unbiased by construction~\cite{Cimini2018,Squartini2017}. The validation procedure is the the one proposed in~\cite{Saracco2017}.\\} First, we find that firms' discussion on Twitter form 13 communities \fab{of accounts}, 10 of which \fab{touch upon} Covid-19 themes. The core of the network is made of 5 communities, which focus on environmental sustainability, digital transformation, remote working, digitalization and safety. This highlights that firm's dialogue on environmental, digital innovation and safety themes was central in Italian large firms' discussion on Twitter at the beginning of the Covid-19 pandemic. Second, 10 communities out of 13 use CSR hashtags. Among the communities, the environmental and social dimensions are prevalent, with the economic one being overlooked. Interestingly, communities dealing with digital innovation and safety focus more on the social dimension than the environmental one, which contrasts the main literature \cite{pedersen2010modelling} while confirming that CSR dissemination is context-dependent \cite{dahlsrud2008corporate}. However, when we focus on the message level, results show that CSR messages are a minority, with some peculiarities appearing in some communities. Last, users seem to interact little on CSR topic, showing that stakeholder engagement on these themes on Twitter is still scarce.} \ale{ Our paper brings methodological, theoretical and practical contributions. From a methodological perspective, we integrate complex network analysis in management research, thus introducing a data-driven approach. Following a non-linear approach, with no a-priori hypotheses, themes and communities freely emerge from data, allowing similarities and differences between firms to arise in real time.} \alee{This allows our contributions to span across different management fields, including the literature on firms and social media, CSR and stakeholder engagement. On the practical side, our research offers a tool for monitoring current challenges and issues firms are facing. This can be useful for policy makers and managers to orient their strategies and decision making \cite{ruhi2014social} and to understand how firms' and users' perceptions of CSR themes vary, reflecting different beliefs of what responsibilities firms have towards society~\cite{pedersen2010modelling}. } \section{Previous findings} \subsection{Firms, social media and the Covid-19 pandemic} In the last 20 years, Internet changed the ways and the speed with which firms communicate and relate to their stakeholders. At first, the social dimension of website communication was focused on blogs, which allowed firms to communicate their “personality” and incorporate a relationship strategy based on connectivity and dialogue with users. Blogs started dialogic online relationships between firms and their public. When they first appeared around 15 years ago, social media were aimed at social networking with friends, family and colleagues~\cite{Saxton2014}. They opened new paths and ways for firms to communicate with their stakeholders, shifting from a hierarchical one-to-many communication to a many-to-many collaborative type of communication~\cite{Colleoni2013}. Thus, social media became platforms for firms to share advertising, marketing and public relationship strategies~\cite{Saxton2014}.\par Among social media, Twitter is popular for business communication purposes~\cite{Gomez-Carrasco2020}, and is the one with the highest adoption rates among large firms~\cite{Yang2017}. \textcolor{black}{It is increasingly used in academic research, with most contributions arising from the computer and information science, and communications, while developing also in business and economics \cite{bruns2014topology}. While Twitter research is mostly focused on the marketing \cite{jansen2009twitter} and financial fields \cite{bollen2011twitter}, it is increasingly being used in the management and strategy fields, for example to monitor firms’ CSR dissemination and stakeholder engagement \cite{Lee2013}, the emerging trends in technology \cite{li2019identifying} or to understand the issues and challenges firms are facing on specific themes \cite{sharma2020covid}. } This literature mostly studied firms' communication on Twitter with traditional methodologies. On the data collection side, manual collection methods \cite{Reilly2014} prevail, while on the data analysis side, manual labelling \cite{Manetti2016}, and linear regressions \cite{Yang2020,Gomez-Carrasco2020,Yang2017} are the majority. However, some studies are experimenting with new approaches based on network methods, with a prevailing focus to understand CSR communication and stakeholder engagement on social media \cite{Colleoni2013,Pilar2019}. There is a prolific new research line which focuses on the impacts of Covid-19 on firms and their reactions (among others:~\cite{Eggers2020,Juergensen2020,Amore2020,Bartik2020,Rapaccini2020}) and there is an extended research about the Covid-19 as perceived on Twitter (see, for instance,~\cite{Rovetta2020, Celestini2020, Cinelli2020, Gallotti2020, yang2020covid19,Caldarelli2020b,lopreite2021early}), but, surprisingly, researchers just started to explore firms’ conversation on Covid-19 on Twitter. To the best of our knowledge, only one paper~\cite{sharma2020covid} has studied firms’ discussion during Covid-19, focusing on the pandemic’s effects on supply chains. However, the pandemic impacted multiple business dimensions, including firms’ financial resources and business models~\cite{Amore2020}, with first reactions ranging from increasing servitization, digitalization~\cite{Juergensen2020, Evans2020, Almeida2020}, and cooperation~\cite{Crick2020}. Managers and entrepreneurs had to rethink the way they do their businesses, learning to face a totally unexpected crisis~\cite{Wankmuller2020} and to cope with a “new normal” \cite{Ratten2020}. To the best of our knowledge, there is no paper currently addressing how firms’ conversation on social media is evolving during Covid-19, thus providing insights on the current issues and challenges firms are facing~\cite{Pilar2019}. Thus, we want to investigate how firms’ Twitter discussion is developing during the Covid-19 pandemic. \subsection{Firms, CSR dissemination and stakeholder engagement} \par \textcolor{black}{Although the concept of CSR has no universal meaning and has been widely defined~\cite{carroll1999corporate}, it generally refers to the relationships and responsibilities a business has towards society, interpreted as the communities of stakeholders a firm interacts with~\cite{snider2003corporate,dahlsrud2008corporate,carroll1999corporate}, going beyond what is required by law~\cite{mcwilliams2001corporate}. What CSR concerns in practical terms depends on the historical and cultural context a firm is settled in, and it can also reflect the issues a firm is facing in a particular period~\cite{snider2003corporate}, which it have been changing and increasing fast after the start of globalization~\cite{dahlsrud2008corporate}. } \par \textcolor{black}{ While the advent of the Internet pushed firms to disseminate their social reporting online~\cite{snider2003corporate}, social media opened a new channel for firms to disseminate their actions and interact with their stakeholders~\cite{Gomez-Carrasco2020}. } \par Previous studies show that firms use social media to disseminate their social, environmental or sustainability orientation and results, but it seems that social media are not fully exploited as a mean to interact with stakeholders~\cite{Manetti2016}. One explanation is legitimacy theory~\cite{guthrie1989corporate}, which argues that companies are on social media to show their presence in the digital world rather than to report their results or engaging their stakeholders. \textcolor{black}{ In this paragraph we will discuss previous research findings, focusing on (i) how the CSR dimensions are concerned in firms' discussion on Twitter and (ii) to what extent stakeholders (here considered as Twitter users) interact with firms. } Most research finds that firms' social media posts about CSR topics are a minority. Considering together firms' Facebook posts, Tweets and Youtube videos in a 3-months period in 2014,~\cite{Manetti2016} show that CSR posts are only 7\% of all posts, thus suggesting that firms do not use Twittter to disseminate their CSR activities. Focusing on the top 50 companies from the Fortune list of 2010,~\cite{Gomez2016} find similar results, highlighting that firms mostly post about topics non-related to CSR (among others, posts include marketing purposes, promotion of products and services), with only a small percentage of posts regarding CSR. This is also consistent with~\cite{Etter2013}, who finds that in general business accounts 14.5\% of tweets are about CSR topics, while they rise in CSR-dedicated Twitter pages, with more than 70\% tweets on average about CSR issues. However, there are some conflicting results. For example, taking Spanish banks after the euro zone crisis, CSR appears as a material topic discussed on Twitter~\cite{Gomez-Carrasco2020}. Few papers use network (visualization) methods, thus showing which communities around CSR topics arise. For example, selecting firms with a Twitter account dedicated to CSR and using network and machine learning methods,~\cite{Colleoni2013} finds that firms and users create several independent communities around CSR themes, instead of a unique and connected network. Combining structural topic modeling and network methods,~\cite{Chae2018} explore how the Twitter discussion around the hashtag \#CSR evolves, resulting in 20 different topics (the most prevalent one being company strategy, followed by community charity, CSR teams, business ethics, …), most of them related to one or more topics, and seven without any significant correlation with others. The paper concludes that Twitter is used as a mean to share about multiple CSR dimensions, some of them are related and they change over time. Following a similar approach, starting from the hashtag \#sustainability, \cite{Pilar2019} adopt social networks methods, finding top themes associated with \#sustainability (namely, Innovation, Environment, Climate Change, Corporate Social Responsibility, Technology, and Energy) and 6 communities (Environmental Sustainability, Sustainability Awareness, Renewable Energy and Climate Change, Innovative Technology, Green Architecture, and Food Sustainability). \newline Overall, existing research seem to agree that CSR communication on Twitter is a minority and results are quite fragmented. However, there are mixed findings and data-driven methods have been rarely used. Also following~\cite{Etter2013} call for a more in-depth study on the topics firms address on Twitter when communicating on CSR, we want to investigate which CSR dimensions and topics firms discuss. While the aforementioned results relate to one-way communication on CSR on Twitter, a few papers also question the extent to which users interact with firms on Twitter, as a measure of stakeholder engagement. \textcolor{black}{ Being a separate but related concept to CSR, stakeholder engagement can be interpreted under many different theoretical perspectives and has been variously defined. Following \cite{greenwood2007stakeholder}, “stakeholder engagement is understood as practices the organisation undertakes to involve stakeholders in a positive manner in organisational activities” (p. 315). Social media are increasingly used as a tool to measure stakeholder engagement, with the assumption that social media users are part of the firm’s stakeholders \cite{bonson2013set}. Although some preliminary evidence shows that Twitter is less used as a mean to engage stakeholders compared to Facebook \cite{manetti2017stakeholder}, it is still considered an ideal tool for firms to engage with their stakeholders, with measures like retweeting activity that can be interpreted as an implicit endorsement of the content of the message \cite{Saxton2019}.} Papers exploring firms' use of Twitter for engaging their stakeholders use different approaches and findings are quite mixed. In general, it seems that social media are not used in their full capacity to interact and engage with stakeholders on CSR topics. This is what both \cite{Gomez2016} and \cite{Manetti2016} found, the former highlighting that firms interact very little on CSR topics, the latter finding that firms' posts concerning stakeholder engagement are only the 0.22\% of total messages. This is somewhat consistent with \cite{Etter2013}, who finds that non-CSR tweets have a higher interactivity than CSR ones. However, \cite{Saxton2019} find opposite results, with CSR messages gaining a greater audience reaction than non-CSR messages, in particular when certain CSR topics (e.g. environment or education) are discussed and when the post uses a hashtag related to the topic. However, popularity was measured as a binary variable (retweeted message vs not retweeted message), not taking into account the extent to which a message is retweeted. Similarly, focusing on specific CSR dimensions, a few papers study how stakeholder engagement varies depending on the type of CSR communication. For example, using the very broad categorization of core CSR (information directly linked to the firm's core business) versus supplementary CSR (information about actions detached from the firm's core business), \cite{Gomez-Carrasco2020} find that different categories of stakeholders react differently to firm's CSR tweets depending on the content that is shared. However, results do not allow to further distinguish which CSR dimensions resonate most. \par As the literature shows very mixed results in stakeholder engagement on CSR topics on Twitter, we want to investigate to what extent the CSR dimensions resonate with the public. \section{Materials and methods} \subsection{Data set} We selected Italy for our study as it is one of the countries first and more severely hit by the pandemic~\cite{Amore2020}. Although large firms are a minority in European businesses~\cite{EuropeanCommissionReportSme2019}, they usually have more stakeholders than small and medium sized firms, are considered to have a bigger impact on society~\cite{Campopiano2015} and higher resources to invest in reporting and accountability~\cite{giacomini2020environmental} . Therefore, we expect them to have a higher adoption rate of social media. We relied on AIDA\footnote{AIDA is a database containing financial and commercial historical data from approximately 540,000 firms operating in Italy. It relies on official data retrieved from the Italian Registry of Companies and the Italian Chambers of Commerce. AIDA contains data at the firm level, which include information about the firm’s characteristics (e.g. location, industry, the year it was founded), the ownership and governance structure (e.g. the name of each shareholder and board member, the respective ownership share) and financial data (balance sheet, profit and loss accounts data, and ratios).} (\href{ https://aida.bvdinfo.com/}{ https://aida.bvdinfo.com/}), the Italian section of Bureau Van Dijk (\href{https://www.bvdinfo.com/}{https://www.bvdinfo.com/}), to select firms. We selected all Italian active firms from with 250 or more employees, resulting in 3.870 firms. We downloaded data about firms' characteristics (e.g. their names, location, ownership type, ATECO code\footnote{ATECO is the classification of economic activities used by the Italian Institute of Statistics (ISTAT). It is the national translation of NACE, which is the classification of economic activities in the European Union. It stands for “Statistical classification of economic activities in the European Community” and is derived from the French “Nomenclature statistique des activités économiques dans la Communauté européenne”. The latest classification is NACE Rev. 2, which was implemented from 2007.} and website) and financial data (e.g. total assets and revenues). As at the time of download (April 2020) not every firm's financial data was updated with information on 2019, the financial data we downloaded refer to 2018. We manually searched the firms’ websites as indicated in AIDA database, checking in each website if a Twitter account was available. For each website, we searched the home page and “contacts” sections. We found that 936 companies out of 3870 (24\%) displayed a Twitter account in their website. A few of them indicated multiple Twitter accounts on their websites. \subsubsection{Data collection and first cleaning} To collect all messages written by the selected accounts, we made use of the \href{https://developer.twitter.com/en/docs/twitter-api/v1/tweets/timelines/overview}{GET statuses/user\_timeline} Twitter API. Out of the original 936 accounts, 6 accounts were not active in the period examined, while 6 were not found (probably they were deactivated). The final data set was composed by 1.6 M of tweets. \newline The data set was cleaned further: we focused on firms writing tweets in the period from the 1st of March, 2020, to 17th of November, 2020, which includes the beginning of the Covid-19 pandemic. In order to focus on the proper set, we selected firms that wrote a message before and after the 1st of March, 2020, to explore their activity over a longer period. Literally, the \href{https://developer.twitter.com/en/docs/twitter-api/v1/tweets/timelines/overview}{GET statuses/user\_timeline} API permits to download the last circa 3200 messages written by the account\footnote{For more details, visit \href{https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/introduction}{Twitter developer webpage}.}: if the account is extremely active, these 3200 will cover just an extremely limited period and thus cannot be considered for the definition of a narrative over the entire period under analysis. It is the case, for instance, of the accounts of publishing houses owning newspapers: the Twitter accounts were used as the accounts of the newspapers, thus for communicating the latest piece of news. Other examples include public transport accounts (messages referred to traffic alerts), internet and mobile service companies (those accounts were either used to advertise the latest promotions or for the customer service) or football teams (commenting the results of the match). Selecting accounts which tweeted before and after the 1st of March 2020 also permits to get rid of those accounts that were active in the past, but did not contribute to the discussion during the pandemic. The resulting firms in our data set are a total of 417 different active accounts and 917864 different messages. \ale{Even though our research is mostly based on publicly available online data (i.e. Twitter messages), we believe it is ethically appropriate not to disclose the firms' names, usernames and quotes \cite{stommel2021ethical}.} \\ \subsubsection{Hashtag cleaning} For each firm in the data set, we extracted the hashtag used, in order to study similarities in the communication strategies. Only 401 accounts out of 417 (i.e. the 96\%) used at least one hashtag in the period under study.\\ We find frequent mistakes in typing the hashtags: to avoid considering as different two hashtag referring to the same subject, we implemented the Edit distance, as implemented by the \texttt{py\_stringmatching} python module~\cite{py_stringmatching} (more details in the hashtag data cleaning can be found in the appendix~\ref{app:hashtags}). After this cleaning, 11475 different hashtags resulted in the data set. \fab{\subsubsection{CSR hashtags}} \textcolor{black}{To recognise hashtags related to CSR issues, the widely known classification of sustainability proposed by~\cite{elkington1997cannibals} was used. It distinguishes between three dimensions: (i) the environmental dimension (i.e. attention of the company towards environmental issues), (ii) the social dimension (i.e. the relationship between business and society – consumers, employees and stakeholders in general), (iii) the economic dimension (i.e. socio-economic or financial aspects, including describing CSR in terms of business operations). In order to select relevant keywords, we adapted and integrated previous approaches. As ~\cite{Gamerschlag2011} distinguish the environmental and social dimension, using keywords from the GRI\footnote{The Global Reporting Initiative (GRI) is is an independent, international organization aimed at developing voluntary reporting guidelines for CSR. The GRI Standards are among the world’s most widely used standards for CSR reporting. For more information, please visit: \href{https://www.globalreporting.org/}{ https://www.globalreporting.org/} } (Global Reporting Initiative) 2010 standard, we updated this list with the latest GRI 2019 standards (Italian translation), also including the economic dimension. To create a comprehensive list of CSR keywords, we also integrated keywords from existing research~\cite{Etter2013,Manetti2016} and added them to their relevant CSR area. To do this, the first and fourth authors discussed the category for each item, and placed it in the category they both agreed on. } \newline \subsection{The bipartite semantic network and its validated projection}\label{ssec:bicm} We represented the system as a bipartite network, i.e. a network in which the nodes are divided into two disjointed classes (called \emph{layers}) and edges are not allowed between nodes of the same group. One layer represents the different accounts, while the second layer represents the various hashtags. A hashtag and an account are connected if, in the period analysed, the given account used the selected hashtag at least once. \newline We use the strategy described in~\cite{Saracco2017} to project the information contained in the original system on the layer of the accounts and detect similarly communicating firms. In a nutshell, this approach consists of 3 main steps: first, we consider the network of the co-occurrences of links, as they are observed in the real system. In our case, since we are interested in projecting the information contained in our system onto the company layer, for each couple of users, the co-occurrences are the number of hashtags used by both accounts. Second, we define a proper null-model as a benchmark. In the present application, we use a maximum entropy null-model, i.e. a model maximally random, but for the information contained in some constraints~\cite{Cimini2018,Squartini2017}. In particular, we can discount the information contained in the degree sequence, as in the Bipartite configuration Model (\emph{BiCM},~\cite{Saracco2015}; more details on the null-model can be found in the appendix~\ref{app:bicm}). In this way, in our analysis we are considering the attitude of the various accounts in using hashtags (that is, the degree of the various accounts) and the number of users using the given hashtag (i.e. the degree of the different hashtags). Finally, we compare the observed co-occurrences with the expectations of the null-model: if those are statistically significant, i.e. much higher than the ones predicted by the model and such that the disagreement cannot be explained by the constraint of the null-model, they are then validated. We then put an edge in the projection connecting the two accounts whose co-occurrences are statistically significant. The result of the projection is a monopartite undirected network of accounts in which a connection indicates non trivial similarities in terms of the usage of hashtags. The entire approach is described in more detail in the appendix~\ref{app:inferring}. \newline For the implementation of the BiCM, we used the recently released python module {\tt\href{https://pypi.org/project/NEMtropy/}{NEMtropy}}, presented in~\cite{vallarano2021fast}. \section{Results and Discussion} \subsection{General statistics} Before considering the accounts that have been validated by the projection techniques described in the section above, we first present some features of the data set, that includes \ale{financial data} from AIDA and \ale{online data} from Twitter.\\ \fab{Over the entire set of firms, the correlations among financial and online data remain limited: in Fig.~\ref{fig:correlation} we show the related Spearman correlation\footnote{Due to the non Gaussian distribution of the various quantities, Pearson correlation is not justified.} matrix. The correlations between quantities related to the companies' activity on online social networks and those regarding their financial performance are in general weak and rarely significant. Actually, even among Twitter quantities, the correlations are quite weak, with a few exceptions: the number of likes per message and the number of retweets per message (0.64), the number of followers and the number of messages (0.57), and the number of followers and the number of likes per message (0.57). \\ Interestingly enough, once we focus on a single ATECO code, as in the right panel of Fig.~\ref{fig:correlation} for code 62 (\emph{Computer programming, consultancy and related activities}), the situation appears slightly different. There are significant and relatively strong correlations between, for instance, the number of followers and the total assets (0.60), and the total number of messages and the total assets (0.55). This difference is probably due to the specific sector: being related to information technologies, the appearance of these companies in online social networks is an important part of their marketing strategies and depends on a firm's size (as measured in the total assets).} \begin{figure}[htb!] \includegraphics[width=.5\linewidth]{./Images/fig01a.png} \includegraphics[width=.5\linewidth]{./Images/fig01b.png} \caption{\fab{{\bf Spearman correlations among different \ale{financial and online} data.} On the left panel the correlation matrix for the entire data set: all correlations between online and financial quantities are weak. This changes once we focus on specific ATECO codes, due to their peculiarities: on the right panel the same correlation matrix for sector 62 (\emph{Computer programming, consultancy and related activitie}). A relatively strong correlation is present between the number of followers and the total assets, for instance. This behaviour may be due to the importance of the communications in online social networks for this sector, which increases with a firm's resources.}} \label{fig:correlation} \end{figure} Focusing on Twitter data, the retweeting activity is always the most frequent one, for instance representing nearly the 80\% of the actions on the platform during the Covid-19 Italian debate~\cite{Caldarelli2020a}. Interestingly enough, probably due to the different role of firms' Twitter accounts, the retweeting activity in the present data set is extremely limited: just the 22.3\% of the messages collected are retweets, while the others are original messages. \fab{A similar behaviour was detected for verified users~\cite{Caldarelli2020a}: the authors interpreted these findings maintaining that verified users are the main drivers for the development of a debate. Here, analogously, firms participate to the discussion by introducing new arguments, even if the accounts are not necessarily verified: the frequency of verified accounts in our data set is quite limited, close to 17\%.} \begin{comment} \begin{table}[htb] \centering \begin{tabular}{+c|c+c|c+} \thickhline \textbf{Hashtag} & \textbf{Occurrence} & \textbf{Hashtag} & \textbf{Occurrence}\\ \thickhline covid & 4106 & lavoro & 817\\ \hline publiacqua & 2538 &webinar & 786\\ \hline coronavirus & 2120 & lavoriincorso & 774\\ \hline acqua & 1810 & sostenibilit\`a & 726\\ \hline gruppohera & 1709 & firenze & 678\\ \hline bologna & 1203 & innovazione & 661\\ \hline muoversivenezia & 1098 & dalleregioni & 585\\ \hline acquedotto & 1044 & unicredit & 574\\ \hline ipsos & 850 & digitale & 555\\ \hline smartworking & 827 & italia2021 & 512\\ \thickhline \hline \end{tabular} \caption{\fab{{\bf Top 20 hashtag by usage.} Due to the impact that the pandemic had on firms' activities, Covid-19 related hashtags are among the most used ones. The other most frequently used hashtags are related to public utilities themes and digitalization. In order, beside the international word as ``covid" and ``coronavirus", Publiacqua is a public company for supply of drinkable water; ``acqua" is the Italian word for ``water"; ``gruppohera" refers to Hera Group, a multi-utility company. ``Muoversivenezia" (\emph{moving in Venice}) refers to the city public transport. ``Acquedotto" is ``aqueduct", while Ipsos is a company specialised in opinion surveys; ``smartworking" is the ``remote working".}} \label{tab:top_20_hash} \end{table} \end{comment} The most frequently used hashtag in the dataset is “covid”, which appears 4106 times. “Coronavirus” is the third most used hashtag, appearing 2120 times. The other most frequently used hashtags are mostly related to public utilities themes and digitalization.\\ \fab{We remind that we just selected firms' accounts, not keywords, to download the messages we analysed. Nevertheless, almost all accounts used hashtags related to pandemic, due to the obvious impact that it had on every activity in the period.} \subsection{Validated network of Twitter accounts} \begin{figure}[htb!] \includegraphics[width=.75\linewidth]{./Images/fig02_shapes.pdf} \caption{{\bf Validated projection of the network of firms.} The network is composed by 80 firms and 135 links. The dimension of each node is proportional to its degree, i.e. the number of connections. The various colors represent the different communities. The shape of the nodes indicate the GUO (Global Ultimate Owner): rectangles are firms owned by the state or other public bodies, diamonds are firms owned by mutual \& pension funds / nominal / trust funds, circles are firms owned by individuals or families (family firms), while triangles are companies; the rest are diamond shaped.} \label{fig:network} \end{figure} \fab{The result of the procedure described in Sec.~\ref{ssec:bicm} is a monopartite network of Twitter accounts composed by 80 firms and 135 links, in which links indicate a non trivial similarity in the usage of hashtags (see Fig.~\ref{fig:network}). Interestingly enough, while being heavy users of messages and hashtags and having a great number of friends, the validated accounts are not among the most popular ones, see Fig.~\ref{fig:validated_network_statistics}. Indeed, the most popular users, i.e. those with more than a million followers, are luxury brands; those accounts wrote many messages, but they limit the usage of hashtags to their merchandise, probably in order to focus on the exclusiveness of their products. In this sense, let us remark that the validated nodes are those that contribute to the formation of common narratives, shared among various accounts; these extremely popular users, instead, are marking their originality and do not intervene substantially to shape common discussions.\\ Even in the case of the firms in the validated network, there are limited correlations between online and financial data, see the left panel of Fig.~\ref{fig:correlation_validated}: the only relatively strong (and significant) one is between the number of followers and the total assets (0.51). Nevertheless, when we focus on a specific ATECO code, correlations can be much stronger and mix the online data from Twitter with the financial ones: in the right panel of Fig.~\ref{fig:correlation_validated} we observe quite a strong correlation between the number of messages and the total assets (0.73) or between the number of likes per message and the total assets (0.75). A similar behaviour was observed in the analysis of the entire data set, see Fig.~\ref{fig:correlation}; the correlations on the 62 ATECO code, were, nevertheless, a little weaker than the ones observed here.} \begin{figure}[htb!] \includegraphics[width=.5\linewidth]{./Images/fig03a.pdf} \includegraphics[width=.5\linewidth]{./Images/fig03b.pdf} \includegraphics[width=.5\linewidth]{./Images/fig03c.pdf} \includegraphics[width=.5\linewidth]{./Images/fig03d.pdf} \caption{\fab{{\bf Properties of nodes in the validated network vs. the ones in the entire set.} The various distributions show that the validated accounts are those that have a greater number of friends (top left panel), use greater number of hashtags (bottom left panel) and write more messages (bottom right panel). Interestingly enough, the validated nodes are not the most popular, i.e. those with the highest number of followers (top right panel). In order to check the most popular accounts, we focused on accounts with more than $10^6$ followers. In fact, the number of their messages is extremely limited, while their use of hashtags is extremely focused on their activities. This may be related to their strategies, to remark the exclusiveness of their products. More details can be found in the main text.}} \label{fig:validated_network_statistics} \end{figure} \begin{figure}[htb!] \includegraphics[width=.5\linewidth]{./Images/fig04a.png} \includegraphics[width=.5\linewidth]{./Images/fig04b.png} \caption{\fab{{\bf Spearman correlations among different financial and online data for firms in the validated network.} On the left panel the correlation matrix for the validated network: all correlations between online and financial quantities are weak, as in the entire data set (see left panel of Fig.~\ref{fig:correlation}), but for the one between the number of followers and the total assets (0.51). Again, the situation changes once we focus on a specific ATECO code and it is even more striking than for the entire data set (see left panel of Fig.~\ref{fig:correlation}). In fact, the same correlation matrix for sector 62 (\emph{Computer programming, consultancy and related activitie}) shows a strong correlation, for instance, between the total number of messages and the total assets (0.73) and between the number of Likes per message and the total assets (0.75). In fact, the validated accounts are those that follow a common strategy in the usage of hashtags and the importance of their appearance online increases relatively to the dimension of the company.}} \label{fig:correlation_validated} \end{figure} \fab{By running the Louvain algorithm~\cite{Blondel2008}, we identified 13 communities of accounts, identified by nodes of different colors in Fig.~\ref{fig:network}. These groups show a certain homogeneity in terms of companies' sectors (for more details, see Tables~\ref{tab:ATECO_0} and \ref{tab:ATECO_1} in the appendix). In particular, the greatest communities in the core of the network mostly include computer programming, consultancy and related activities ({\color{color02} $\bullet$}), electricity, gas, steam and air conditioning supply ({\color{color01} $\bullet$}), employment ({\color{color03} $\bullet$}), activities of head offices and management consultancy ({\color{color04} $\bullet$}) and human health ({\color{color08} $\bullet$}). Instead, }\ale{the ownership type (in term of the \emph{Global Ultimate Owner}, or GUO\footnote{As defined by Bureau Van Dijk, the GUO (Global Ultimate Owner) is the individual or entity at the top of the corporate ownership structure, thus indicating the highest parent company.}) does not seem to influence the conversation\fab{: the GUO is represented in Fig.~\ref{fig:network} as different shapes of the nodes and no significant pattern can be detected.} This is surprising, as some kinds of firms communicate in a different way, especially about CSR and environmental issues. For example, family firms are found to communicate on CSR differently from non-family firms~\cite{Campopiano2015} and publicly owned firms disclose less on environmental topics (contrary to the expectations~\cite{argento2019sustainability,giacomini2020environmental}).} Although ownership does not seem to influence the conversation, it is worth noting that the dialogue on environmental sustainability is mostly carried out by firms active in the public utilities sector. \subsubsection{The usage of hashtags in the validated network: firms' discussion during the pandemic} \fab{Remarkably, among the 13 communities detected, }10 of them have a Covid-related theme in their main hashtags (e.g. ``coronavirus”, ``covid”, ``iorestoacasa”, the latter one meaning ``stayhome”), meaning that firms’ discussion is strongly related to the pandemic. \ale{The core of the network is made of 5 interconnected communities. Based on their most frequently used hashtags, we named them ``Digital Transformation" ({\color{color02}$\sbullet$}), ``Remote Working" ({\color{color03}$\sbullet$}), ``Digitalization" ({\color{color04}$\sbullet$}), ``Environmental Sustainability" ({\color{color01}$\sbullet$}) and ``Safety" ({\color{color08}$\sbullet$}), which emerged as the main themes that firms discussed at the beginning of the Covid-19 pandemic.} The names assigned to all communities can be found in Table~\ref{tab:recap}.\\ \begin{table}[htb!] \centering \begin{tabular}{+ll+} \thickhline \textbf{Comm.} & \textbf{Theme} \\ \thickhline {\color{color02}$\sbullet$} & Digital Transformation \\ {\color{color01}$\sbullet$} & Environmental Sustainability \\ {\color{color03}$\sbullet$} & Remote Working \\ {\color{color04}$\sbullet$} & Digitalization \\ {\color{color05}$\sbullet$} & Restart\\ {\color{color08}$\sbullet$} & Safety \\ {\color{color06}$\sbullet$} & Mobility\\ {\color{color07}$\sbullet$} & Slowing the Spread\\ {\color{color00}$\sbullet$} & Solidarity\\ {\color{color09}$\sbullet$} & Space\\ {\color{color10}$\sbullet$} & Nursing Homes\\ {\color{color11}$\sbullet$} & Locality\\ {\color{color12} $\sbullet$} & Reading\\ \thickhline \end{tabular} \caption{{\bf Identification between themes and the community displayed in Fig.~\ref{fig:network}:} as it can be further observed, the themes the different groups of accounts deal with are closely related to their ATECO codes, i.e. to their sector.} \label{tab:recap} \end{table} \begin{table}[htb!] \hskip-1.5cm \begin{tabular}{+c|c|c+c|c|c+} \thickhline \textbf{Comm.} & \textbf{Hashtag} & \textbf{Occurrence} & \textbf{Comm.} & \textbf{Hashtag} & \textbf{Occurrence}\\ \thickhline {\color{color02} $\sbullet$} & smartworking & 15 & {\color{color05} $\sbullet$} & ripartiamodallitalia & 5 \\ \cline{2-3} \cline{5-6} & cloud & 15 && covid & 5 \\ \cline{2-3} \cline{5-6}& covid & 13 && italia & 5 \\ \cline{2-3} \cline{5-6}& innovazione & 13 & & coronavirus & 5 \\ \cline{2-3} \cline{5-6}& ai & 12 & & aprile & 4 \\ \cline{2-3} \cline{5-6}& sicurezza & 12 & & turismo & 4 \\ \cline{1-3} \cline{5-6} {\color{color01} $\sbullet$} & sostenibilità & 13 & & estate & 4 \\ \cline{2-3} \cline{5-6} & covid & 12 & & estatepostcovid & 4 \\ \cline{2-3} \cline{5-6} & innovazione & 11 & & sostenibilità & 4 \\ \cline{2-3} \cline{5-6} & greendeal & 11 & & coop & 4 \\ \cline{2-3} \cline{4-6} & energia & 11 & {\color{color08} $\sbullet$} & covid & 6 \\ \cline{1-3} \cline{5-6} {\color{color03} $\sbullet$} & covid & 11 & & italia & 6 \\ \cline{2-3} \cline{5-6}& digitale & 10 & & coronavirus & 6 \\ \cline{2-3} \cline{5-6}& coronavirus & 10 & & diabete & 5 \\ \cline{2-3} \cline{5-6}& lavoro & 9 & & scuola & 5 \\ \cline{2-3} \cline{5-6}& smartworking & 9 & & sanità & 5\\ \cline{1-3} \cline{5-6} {\color{color04} $\sbullet$} & smartworking & 9 & & mascherine & 5 \\ \cline{2-3} \cline{4-6}& covid & 9 & {\color{color06} $\sbullet$} & settembre & 5 \\ \cline{2-3} \cline{5-6}& lavoro & 8 & & coronavirus & 5 \\ \cline{2-3} \cline{5-6}& webinar & 7 & & agosto & 5 \\ \cline{2-3} \cline{5-6}& coronavirus & 6 & & covid & 5 \\ \cline{2-3} \cline{5-6}& digitale & 6 & & ottobre & 5 \\ \cline{2-3} \cline{5-6}& economia & 6 & & maggio & 5 \\ \cline{2-3} \cline{5-6}&&&& marzo & 5 \\ \cline{1-3} \cline{5-6} \thickhline \end{tabular} \caption{{\bf The top 5 frequent hashtags for the communities in the Largest Connected Component of Fig.~\ref{fig:network}}. Due to the great number of \emph{ex aequo}, the top 5 most frequent hashtags is, in general, longer than 5. } \label{tab:hashtag_0} \end{table} In the “Environmental Sustainability” community ({\color{color01}$\sbullet$}), the most important hashtags are ``sostenibilità” (meaning ``sustainability”), ``covid”, ``innovazione” (``innovation”), ``greendeal”, ``energia” (``energy”), thus showing that the environmental themes are relevant and linked to the innovation ones, see Table~\ref{tab:hashtag_0}. This community is mostly formed by firms managing national infrastructures, and public utilities. Three communities capture the digital innovation debate: “Digital Transformation” ({\color{color02}$\sbullet$}) , “Remote Working” ({\color{color03}$\sbullet$}) and “Digitalization” ({\color{color04}$\sbullet$}) . The “Digital Transformation” community deals with the themes of digital transformation, innovation and covid, with the most relevant hashtags being: “smartworking” (“remoteworking”), “cloud”, “covid”, \ale{"ai" and "sicurezza" ("security")}. This community is made of private firms, regionally-owned companies, software companies, consultancies. The other two communities (“Remote Working” and “Digitalization”) are mostly concerned with the changing nature of work. One has “covid”, “digitale” (“digital”), “coronavirus”, “lavoro” (“work”), “smartworking” (“remoteworking”) as the most relevant hashtags, which reflect the workplace adjustments during the pandemic. This community is mostly composed of recruitment agencies, along with consultancies, telecommunication companies, a trade fairs organizer, and an agency for the digital innovation. The “Digitalization” community also focuses on work digital adjustments, with “smartworking” (“remoteworking”), “covid”, “lavoro” (“work”), “webinar” and “digitale” (“digital”) as the main hashtags. It is mostly composed of consultancy companies. The “Safety” community ({\color{color08}$\sbullet$}) is made of biopharmaceutical companies, a hospital group and a university consortium. Its hashtags are: “covid”, “italia” (“Italy”), “coronavirus”, “sanità” (“healthcare”), “mascherine” (“facemasks”), thus showing that their main concerns are safety measures against Covid-19. These results show that the digital innovation debate is central in firms' discussion on Twitter, with themes related to digitalization and the introduction of new tools as remote working, webinars, cloud services. This is consistent with the first results of firms’ reactions to the Covid-19 crisis~\cite{Almeida2020}: the needs to social distancing and to shelter at home pushed towards an acceleration of the digital transformation, which was ongoing before the pandemic, thus changing firms’ business models and strategies. On one hand, this appeared in an increase in the demand for technology products (e.g. laptops) and services (e.g. cloud computers, digital services). On the other hand, many jobs went remote. While digital transformation processes were already ongoing \cite{matt2015digital}, the pandemic highlighted the need to leverage technology to overcome the challenges and environmental uncertainty, and accelerated a trend towards different life styles, increasing the importance of technology in our economy and society~\cite{Evans2020}. \fab{Smaller communities are described in details in the appendix~\ref{app:smaller_communities}.} \subsubsection{CSR dissemination and stakeholder engagement} {\color{black} In this second part of the analysis, we study CSR dissemination and stakeholder engagement in the communities previously identified.\\ \fab{Before starting, let us make a few remarks. First, the number of CSR hashtags is extremely limited, being of 30 different words, compared to a set of 6036 different hashtag used by the validated accounts, resulting respectively as the 0.17\% (environmental dimension), 0.28\% (social dimension) and 0.05\% (economic dimension). Despite these small numbers, it is crucial to notice that, when we also consider the repetitions (i.e. the number of times an account used the various hashtags), the fractions are quite different, that is respectively the 1.17\%, 0.42\% and 0.07\%. In this sense, even if the set of keywords we are considering is quite limited, firms' accounts are particularly inclined to use it: if the number of repetitions per hashtag were constant, we would not observe a change in its percentage when considering their total presence. In this sense, also considering the repetitions, the environmental dimension seems particularly popular among the validated accounts.} \begin{table}[htb] \centering \begin{tabular}{+c+c|c|c|c|c+} \thickhline \textbf{Comm.} & \textbf{Accounts} & \textbf{CSR (total)} & \textbf{Env.} & \textbf{Soc.} & \textbf{Econ.}\\ \thickhline {\color{color02} $\sbullet$} & 16 & 9 & 6 & 8 & 2\\ \hline {\color{color01} $\sbullet$} & 14 & 14 & 14 & 8 & 2\\ \hline {\color{color03} $\sbullet$} & 11 & 10 & 6 & 9 & 2\\ \hline {\color{color04} $\sbullet$} & 9 & 7 & 5 & 7 & 2\\ \hline {\color{color05} $\sbullet$} & 6 & 4 & 4 & 1 & 0\\ \hline {\color{color08} $\sbullet$} & 6 & 3 & 1 & 2 & 0\\ \hline {\color{color06} $\sbullet$} & 5 & 3 & 3 & 1 & 0\\ \hline {\color{color07} $\sbullet$} & 3 & 3 & 3 & 2 & 2\\ \hline {\color{color11} $\sbullet$} & 2 & 2 & 2 & 0 & 0\\ \hline {\color{color12} $\sbullet$} & 2 & 1 & 1 & 0 & 0\\ \thickhline \end{tabular} \caption{\textbf{Frequency of accounts using the various CSR hashtags.} The frequency of accounts using CSR hashtags is higher in the greater communities, with a 100\% covering in the case of ``Environmental Sustainability" ({\color{color01}$\sbullet$}).} \label{tab:CSR_fraction} \end{table} \paragraph{CSR usage in the validated network} At the community level, 10 communities out of 13 use CSR hashtags (see Table \ref{tab:CSR_fraction}), with most accounts in each community using CSR hashtags. Environmental and social themes are prevalent, with their relevance differing depending on the community. In the ``Environmental Sustainability” community ({\color{color01}$\sbullet$}), all accounts (14) use hashtags related to CSR. This community is mainly composed of public utilities companies, and highlight that the sustainability debate is prevalent in these kinds of firms, and it is joint with the innovation debate. In this community, all the 14 accounts use hashtags related to the environmental dimension. Hashtags related to the social dimension are also tweeted by most accounts (8 out of 14), while hashtags related to the economic dimension are a minority (tweeted by 2 out of 14 accounts).\\ In the ``Digital Transformation” community ({\color{color02}$\sbullet$}), 9 accounts out of 16 use hashtags related to CSR. Among them, 6 discuss environmental themes, 8 social ones and 2 economic ones. This shows that digital transformation themes are more connected to social aspects than environmental ones – among the most frequently used hashtags, words like ``formazione” (``training") and ``istruzione” (``education") appear. Considered together with the prevalent hashtags of the community (``smartworking", ``cloud", ``covid", ...), it seems that firms are discussing the learning process associated with the new technologies, which is consistent with the period of observation.\\ In the ``Remote working” community ({\color{color03}$\sbullet$}), 10 out of 11 accounts use CSR hashtags. Again, the social dimension is prevalent (9 accounts use social hashtags, in contrast to 6 accounts that use environmental hashtags and 2 that use economic hashtags). The hashtags related to the social dimension include training themes (``formazione", ``istruzione”, meaning ``training" and ``education", respectively), but are more varied than the previous community – they concern work-related themes, as ``corruzione”(``corruption"), ``discriminazione” (``discrimination") and ``diversity”. This is partly intuitive, as this community is mainly composed by recruitment agencies, consultancies, and telecommunication companies.\\ In the ``Digitalization" community ({\color{color04}$\sbullet$}), 7 out of 9 accounts use CSR hashtags. Consistently with the previous communities, accounts that use hashtags related to the social dimension are more (7) than the ones posting about the environmental dimension (5), while the economic dimension is still the minor one (2).\\ Again, the “Safety” community ({\color{color08}$\sbullet$}) has 2 accounts tweeting about the social dimension and 1 about the environmental dimension, and no accounts tweeting about the economic dimension. \newline These results show that CSR dissemination is not evenly distributed among communities and firms. The prevalent CSR dimension firms disseminate on Twitter is contingent to the community they belong to, which is somehow related to the firms’ sectors – showing that different types of firms emphasize different dimensions of CSR. The communities focused on digital innovation (``Digital Transformation", ``Remote Working", ``Digitalization") and safety are more concerned on the social dimension of CSR. In these communities, the environmental dimension is present, but it is less relevant compared to the social dimension, which is somehow surprising, as the environmental dimension is usually the one managers put more attention on~\cite{pedersen2010modelling}. Last, the economic dimension of CSR is overlooked in all communities. We do not know if the higher relevance of the social dimension of CSR in the digital innovation and safety communities is an effect of the pandemic or if this also happens in non-crisis times. One option is that the pandemic pushed firms to see the social dimension as the most relevant one, and it became prevalent compared to the environmental one. This would confirm CSR as a concept evolving depending on the present circumstances~\cite{snider2003corporate}. In any case, it is worth noting that, differently from the main literature~\cite{pedersen2010modelling}, in some communities the social dimension is more relevant than the environmental one. Further research could investigate this trend, checking if these communities mostly communicate on social CSR themes over a wider time span, also considering non-crisis times. \newline The analysis of the smallest communities concerns for CSR themes can be found in the appendix~\ref{app:smaller_communities_CSR}} \ale{However, when considering the dissemination of the CSR dimensions focusing on hashtags as a unit of analysis, the relevance of CSR changes. Table~\ref{tab:hash_frequency_by_CSR} shows the occurrence of CSR hashtags among the hashtags in the validated network. Overall, CSR hashtags are less then 2\% of all hashtags, with hashtags related to the environmental dimension being the majority (1.17\%) compared to the social dimension (0.42\%) and the economic one (0.07\%). On one hand, this is consistent with previous literature, which argues that the CSR dimension is overlooked in firms' social media posts \cite{Manetti2016,Gomez2016,Etter2013}. However, a methodological note is needed. As the hashtags we included in the CSR dimensions are only 30 in total, representing the 0.5\% of the total hashtags in the (validated) network, it is easily predictable that they will represent a minority. Actually, their occurrence in the validated network is higher then expected (1.67\%), thus highlighting that firms use the hashtags related to CSR more frequently then the others. Further research should widen the hashtags considered as related to the CSR dimensions - as for now, we believe that the hashtags we used as representative for the CSR dimension do not entirely capture the phenomenon. In any case, some communities show that specific CSR dimensions are more prevalent than others. It is the case of the "Environmental Sustainability" community ({\color{color01}$\sbullet$}), where hashtags related to the environmental dimension are the 3.51\% of the total. Firms in the "{Remote Working}" community ({\color{color03}$\sbullet$}), instead, use more hashtags related to the social dimension, which account for the 1.12\% of the total. Again, the "{Restart}" community ({\color{color04}$\sbullet$}) shows a higher prevalence of the environmental dimension (1.62\%). } \begin{table}[htb!] \centering \begin{tabular}{+c|c|c|c|c+} \thickhline & \textbf{Hashtags} & \textbf{ENV (\%)} & \textbf{SOC (\%)} &\textbf{ECON (\%)}\\ \thickhline Validated network & 67805 & 1.17 & 0.42 & 0.07\\ {\color{color02} $\sbullet$} & 12646 & 0.38 &0.29 & 0.05\\ {\color{color01} $\sbullet$} & 14541 & 3.51 &0.50 & 0.04\\ {\color{color03} $\sbullet$} & 10921 & 0.51 &1.12 & 0.07\\ {\color{color04} $\sbullet$} & 7164 & 1.62 &0.52 & 0.08\\ {\color{color05} $\sbullet$} & 3312 & 0.63 &0.06 & 0.00\\ {\color{color08} $\sbullet$} & 4751 & 0.04 &0.08 & 0.00\\ {\color{color06} $\sbullet$} & 8223 & 0.32 &0.02 & 0.00\\ {\color{color07} $\sbullet$} & 2115 & 0.28 &0.47 & 1.13\\ {\color{color00} $\sbullet$} & 1142 & 0.00 &0.00 & 0.00\\ {\color{color09} $\sbullet$} & 272 & 0.00 &0.00 & 0.00\\ {\color{color10} $\sbullet$} & 10 & 0.00 &0.00 & 0.00\\ {\color{color11} $\sbullet$} & 1708 & 0.35 &0.00 & 0.00\\ {\color{color12} $\sbullet$} & 1000 & 0.40 &0.00 & 0.00\\ \thickhline \end{tabular} \caption{\fab{\textbf{Frequency of hashtags in the validated network, by community and CSR dimension}. As expected by analysing the community composition in terms of ATECO code, the attention on the various group is quite different: for instance, the ``Environmental Sustainability" community {\color{color01} $\sbullet$} has a frequency of hashtags in the Environmental dimension that is greater than twice the value observed on the entire validated network. Similar considerations apply to the ``Remote Working" community {\color{color03} $\sbullet$} for the social dimension and the ``Mobility" one {\color{color07} $\sbullet$} for the social one.}} \label{tab:hash_frequency_by_CSR} \end{table} \begin{table}[htb!] \hskip-2cm \begin{tabular}{+c|c|c|c+c|c|c|c+} \thickhline \multicolumn{4}{+c+}{\textbf{Likes}} & \multicolumn{4}{c+}{\textbf{Retweets}} \\ \thickhline & \textbf{ENV} & \textbf{SOC} & \textbf{ECON} & & \textbf{ENV} & \textbf{SOC} & \textbf{ECON}\\ \thickhline Validated network & 2.42 & 2.76 &1.47 & Validated network & 2.44 & 3.69 &1.79\\ \thickhline {\color{color02} $\sbullet$} & 2.75 & 2.22 &0.80 & {\color{color02} $\sbullet$} & 2.49 & 2.88 &1.70\\ \hline {\color{color01} $\sbullet$} & 2.27 & 3.13 &1.79 & {\color{color01} $\sbullet$} & 2.31 & 3.80 &2.03\\ \hline {\color{color03} $\sbullet$} & 2.20 & 2.84 &0.80 & {\color{color03} $\sbullet$} & 2.33 & 3.99 &1.70\\ \hline {\color{color04} $\sbullet$} & 2.50 & 2.72 &1.27 & {\color{color04} $\sbullet$} & 2.51 & 3.91 &1.39\\ \hline {\color{color05} $\sbullet$} & 2.72 & 1.31 &0.00 & {\color{color05} $\sbullet$} & 2.79 & 1.89 &0.00\\ \hline {\color{color08} $\sbullet$} & 2.83 & 2.39 &0.00 & {\color{color08} $\sbullet$} & 2.92 & 2.85 &0.00\\ \hline {\color{color06} $\sbullet$} & 2.55 & 5.03 &0.00 & {\color{color06} $\sbullet$} & 2.46 & 4.86 &0.00\\ \hline {\color{color07} $\sbullet$} & 2.83 & 2.81 &2.78 & {\color{color07} $\sbullet$} & 2.92 & 4.02 &2.35\\ \hline {\color{color00} $\sbullet$} & 0.00 & 0.00 &0.00 & {\color{color00} $\sbullet$} & 0.00 & 0.00 &0.00\\ \hline {\color{color09} $\sbullet$} & 0.00 & 0.00 &0.00 & {\color{color09} $\sbullet$} & 0.00 & 0.00 &0.00\\ \hline {\color{color10} $\sbullet$} & 0.00 & 0.00 &0.00 & {\color{color10} $\sbullet$} & 0.00 & 0.00 &0.00\\ \hline {\color{color11} $\sbullet$} & 2.83 & 0.00 &0.00 & {\color{color11} $\sbullet$} & 2.92 & 0.00 &0.00\\ \hline {\color{color12} $\sbullet$} & 2.88 & 0.00 &0.00 & {\color{color12} $\sbullet$} & 3.23 & 0.00 &0.00\\ \thickhline \end{tabular} \caption{\fab{\textbf{Average number of likes (left) and retweets (right) per message containing a hashtag in the environmental (\textbf{ENV}), social (\textbf{SOC}) and economic (\textbf{ECON}) dimensions.} Interestingly enough, the frequency of the CSR hashtags used (reported in Table~\ref{tab:hash_frequency_by_CSR}) is not necessarily mirrored in the number of likes or retweets received on average per hashtag.}} \label{tab:user_engagement} \end{table} \paragraph{Stakeholder engagement on CSR dimensions} \ale{We measure stakeholder (user) engagement as the number of retweets and likes per hashtag. Table~\ref{tab:user_engagement} shows stakeholder engagement on all posts and CSR dimensions. Results show that posts with hashtags related to the three CSR dimensions are retweeted and liked less then the rest of the posts, thus confirming that social media are not fully exploited to interact and engage on CSR themes \cite{Gomez2016,Manetti2016,Etter2013}. In the entire data set, on average, each message containing a hashtag concerning CSR is retweeted 2.99 times, against an average of 5.39 retweets for all the hashtags. However, a closer look at the communities and CSR dimensions highlights some peculiarities. While the number of retweets for the environmental dimension is more or less stable in the communities, the ``Mobility" ({\color{color06}$\sbullet$}) community has a higher number of retweets in the social dimension (4.86 on average). With a few exceptions, the social dimension has on average a higher number of retweets compared to the other CSR dimensions and to the dataset.\\ In terms of the number of likes per hashtag, in the entire dataset each message containing a CSR hashtag obtains on average 2.59 likes, against an average of 14.83 likes for all the hashtags. When we look at the various communities, again the number of likes in the environmental dimension is quite stable, while social hashtags show a few different trends, with the ``Mobility" ({\color{color06}$\sbullet$}) and ``Environmental Sustainability" ({\color{color01}$\sbullet$}) communities having a higher number of likes (5.03 and 3.13 respectively) and the ``Restart" one ({\color{color05}$\sbullet$}) having a lower number of likes than the average (1.31). Thus, it seems that stakeholder engagement shows similar trends with both measures (retweets and likes), while the extent to which users interact is unevenly distributed among dimensions and communities.} \newline \ale{Overall, these findings show that firms' dissemination on CSR dimensions and stakeholder engagement are not homogeneous and vary depending on the communities. Thus, studies enquiring on firms' CSR concerns and stakeholder engagement should consider this when formulating their research questions and methods. These findings also show that network methods, allowing firms' discussions to emerge from data without any a priori hypothesis are an effective way to show firms' and users' different attitudes towards the CSR dimensions. } \begin{comment} \begin{table}[htb] \centering \begin{tabular}{|c||m{3cm}|c|c|c|c|c|} \hline ATECO & Description & \# & CSR (total) & Env & Soc & Econ\\ \hline\hline 62 & produzione di software, consulenza informatica e attività connesse & 10 & 6 & 5 & 5 & 1 \\ \hline 78 & attività di ricerca, selezione, fornitura di personale & 6 & 4 & 2 & 3 & 0 \\ \hline 35 & fornitura di energia elettrica, gas, vapore e aria condizionata & 5 & 5 & 5 & 2 & 2 \\ \hline 70 & attività di direzione aziendale e di consulenza gestionale & 5 & 5 & 3 & 5 & 1 \\ \hline 21 & fabbricazione di prodotti farmaceutici di base e di preparati farmaceutici & 5 & 3 & 3 & 2 & 2 \\ \hline 52 & magazzinaggio e attività di supporto ai trasporti & 4 & 4 & 4 & 0 & 0 \\ \hline 71 & attività degli studi di architettura e d'ingegneria; collaudi ed analisi tecniche & 4 & 3 & 3 & 1 & 0 \\ \hline 47 & commercio al dettaglio (escluso quello di autoveicoli e di motocicli) & 4 & 3 & 3 & 1 & 0 \\ \hline \end{tabular} \caption{Frequency of accounts using CSR keywords per ATECO code.} \label{tab:CSR_frequency} \end{table} \begin{table}[htb] \centering \begin{tabular}{|c|p{6cm}|c|c|} \hline\hline Community & Tweet & Account & Likes\\ \hline\hline {\color{color02} $\sbullet$} & `Auguri di Buona \#pasqua2020 da \#enav \#HappyEaste \#ansp \#air \#traffic \#Management and \#smartworking \#SocialDistancing \#enav \#torneremoavolare \href{https://t.co/d5gynharmU}{https://t.co/d5gynharmU}' & ENAVSpA & 41\\ \hline {\color{color01} $\sbullet$} & ``Smettiamo di utilizzare \#energia quando non ce n’\`e bisogno. L'energia pi\`u virtuosa \`e quella che non consumiamo. Cambiamo insieme prospettiva per contribuire a un progresso pi\`u armonioso." & ENGIEitalia & 572\\ \hline {\color{color03} $\sbullet$} & `@ehileus ci racconta come \`e nata la sua passione per i \#video e come \`e diventata la sua prima esperienza di \#lavoro \#ExperienceWorkDay \href{https://t.co/7TxO5dK8h0}{https://t.co/7TxO5dK8h0}' & AdeccoItalia & 89\\ \hline {\color{color04} $\sbullet$} & `La grandezza di un mito si misura dall'imponente \#lavoro che lo ha generato. Congratulazioni ai campioni d'Italia, @juventusfc festeggiamo insieme questo traguardo!\#MY7H' & RandstadItalia & 999\\ \hline {\color{color08} $\sbullet$} & ``Il Gruppo San Donato \`e in prima linea nell'emergenza \#covid19: gi\`a operativi i 15 medici della task force che da oggi si alterneranno nelle terapie intensive di \#Lodi \#Crema \#Cremona per una settimana h 24. \#Coronavirus \#FermiamoloInsieme \href{https://t.co/Kb1Nh6wOD8}{https://t.co/Kb1Nh6wOD8}" & grupposandonato & 1138\\ \hline \hline \hline \end{tabular} \caption{Most liked tweets by the various communities and relative number of `Likes'.} \label{tab:tweets} \end{table} \end{comment} \section{Conclusion} Our paper presents large Italian firms' discussion on Twitter during the first 9 months of the Covid-19 pandemic. Specifically, our explorative research questions followed three lines: 1) firms’ general Twitter discussion during the Covid-19 pandemic; 2) the CSR dimensions being discussed; 3) stakeholder engagement on CSR themes. First, we show that the discussion is formed of 13 communities of firms, with Covid-19 themes appearing in 10 of them. The core of the network, which reflects firms’ major challenges during the pandemic, is composed of five communities (i.e. ``Digital Transformation", ``Remote Working", ``Digitalization", ``Environmental Sustainability" and ``Safety"). Firms' ownership type does not seem to affect the debate. Second, we show that 10 communities out of 13 use CSR hashtags. While the environmental and the social dimensions are the prevalent ones, the economic dimension is generally overlooked. Moreover, the social dimension is more relevant than the environmental one in the three digital innovation communities and the safety one. Third, stakeholder engagement on CSR themes is limited, and unevenly distributed among communities and themes. This work has methodological, theoretical and practical implications. On the methodological side, we integrate a new methodology (i.e. complex network analysis) in management research, widening the methods and focus of current research, that mostly uses manual labelling \cite{Manetti2016}, and linear regressions \cite{Yang2020,Gomez-Carrasco2020,Yang2017} and centers on specific \cite{Pilar2019,sharma2020covid} or CSR themes~\cite{Chae2018a,Colleoni2013,Pilar2019}). \alee{Theoretically, we contribute to the literature on firms and social media, showing that digital innovation, environmental sustainability and safety are the main challenges firms are facing during Covid-19; to the CSR literature \cite{Manetti2016,giacomini2020environmental}, highlighting that the relevance of the CSR dimensions varies depending on the community; and to the stakeholder engagement literature \cite{manetti2017stakeholder,bonson2016corporate,okazaki2020exploring}, confirming that Twitter is overlooked as a tool to interact on CSR issues, with peculiarities arising in some communities. \par Businesses today use social media as predictive tools on various sides, including product design, relations management and marketing \cite{lu2014integrating}. For management scholars, social media are a promising tool for a series of aspects, including stock market volatility \cite{antweiler2004all}, product sales \cite{ghose2010estimating}, and financial performances \cite{kim2017social}. However, the potential of social media for strategic decision making is widely overlooked. Today, social media can provide businesses a rich source of naturally occurring data \cite{ruhi2014social}, which can be exploited to detect emerging issues and relevant themes. Thus, on the practical side, we believe our research contributes to provide an analytics tool based on firms’ Twitter data to support managers, entrepreneurs and policy makers when designing their strategies and decision making.} Applied to the CSR field, a network-based analysis of Twitter represents an alternative way to understand the managerial perceptions of CSR themes, which are the responsibilities managers believe a business should pursue towards society~\cite{pedersen2010modelling}. Some further questions remain to be addressed. First, our analyses focus on large firms in only one country, thus not considering small and medium businesses, which form the backbone of Italian and European economies, and other national contexts. An extension of this research will also include SMEs, to allow a wider understanding of firm's discussion on Twitter. In fact, due to the selection of large firms, firms' sectors are not evenly distributed, neither is firms' geographical location. A larger set of firms' account will overcome this limitation.\\ Second, the examined list of CSR hashtags is quite limited and, even if those hashtags are quite popular, we run the risk of capturing just a portion of the entire CSR debate; in further research we will expand this list, increasing our coverage of all the variations of the CSR discussion. \section*{Acknowledgments} GC acknowledges from the EU grant ``Humane-AI-net" (Grant nr. 952026). \fab{FS acknowledges support from the EU project SoBigData++ (Grant nr. 871042) and the PAI (\emph{Progetto di Attivit\`a Integrata}) project TOFFEe, funded by the IMT School For Advanced Studies Lucca}. \nolinenumbers
{'timestamp': '2021-03-12T02:25:29', 'yymm': '2103', 'arxiv_id': '2103.06705', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06705'}
arxiv
\section{Introduction} \begin{figure}[h] \begin{center} \includegraphics[width=0.6\linewidth]{figures/image_datasets_clusters.png} \end{center} \caption{In standard image classification datasets, classes are typically composed of multiple clusters of similarly looking images. We call intraclass clustering a model's ability to differentiate such clusters despite their association to identical labels.} \label{image_datasets_clusters} \end{figure} The generalization ability of deep neural networks remains largely unexplained. In particular, the traditional view that explicit forms of regularization (e.g. dropout, $\mathcal{L}_2$-regularization, data augmentation) are the sole factors for generalization performance of state of the art neural networks has been experimentally invalidated \citep{Neyshabur2015,Zhang2017}. Today's conventional wisdom rather conjectures the presence of implicit forms of regularization, emerging from the interactions between neural network architectures, optimization, and the inherent structure of the data itself \citep{Arpit2017}. One structural component that seems to occur in most image classification datasets is the presence of multiple clusters amongst the samples of a class (or \textit{intraclass clusters}, cfr. Figure \ref{image_datasets_clusters}). The extraction of such structure in the context of supervised learning is not self-evident, as today's standard training algorithms are designed to group samples from a class together, without any considerations for eventual intraclass clusters. \textit{This paper hypothesizes that the identification of intraclass clusters emerges during supervised training of deep neural networks, despite the absence of supervision or explicit training mechanisms targeting this behaviour. Moreover, our study suggests that this phenomenon improves the generalization ability of deep neural networks, hence constituting an implicit form of regularization.} To verify our hypotheses, we define four measures of intraclass clustering and inspect the correlation between those measures and a network's generalization performance. These measures are designed to capture intraclass clustering from four different perspectives, defined by the representation level (neuron vs. layer) and the amount of knowledge about the data's inherent structure (datasets with or without hierarchical labels). To evaluate these measures' predictive power, we train more than 500 models, varying standard hyperparameters in a principled way in order to generate a wide range of generalization performances. The measures are then evaluated qualitatively through visual inspection of their relationship with generalization and quantitatively through the granulated Kendall rank-correlation coefficient introduced by \citet{Jiang}. Both evaluations reveal a tight connection between intraclass clustering measures and generalization ability, providing important evidence to support this work's hypotheses. \section{Measuring intraclass clustering in internal representations} A challenge of our work resides in measuring a model's ability to differentiate intraclass clusters, without knowing which mechanisms underlie such ability. In such context, the design of multiple complementary measures (i) offers different perspectives that will help better characterize intraclass clustering mechanisms and (ii) reduces the risk that their potential correlation with generalization is induced by other phenomena independent of intraclass clustering. This section thus describes four measures of intraclass clustering, differing in terms of representation level (neuron vs. layer) and the amount of knowledge about the data's inherent structure (datasets with or without hierarchical labels). \subsection{Terminology and notations} $D$ denotes the training dataset. Let $I$ be the number of classes in the dataset $D$, we denote the set of samples from class $i$ by $C_i$ with $i\in \mathcal{I}=\lbrace 1,2,...,I \rbrace$. In the case of hierarchical labels, $C_i$ denotes the samples from subclass $i$ and $S_{s(i)}$ the samples from the superclass containing subclass $i$. We denote by $\mathcal{N}=\lbrace 1,2,...,N \rbrace$ and $\mathcal{L}=\lbrace 1,2,...,L \rbrace$ the indexes of the $N$ neurons and $L$ layers of a network respectively. Neurons are considered across all the layers of a network, not a specific layer. The methodology by which indexes are assigned to neurons or layers does not matter. We further denote by $\text{mean}_{j\in \mathcal{J}}$ and $\text{median}_{j\in \mathcal{J}}$ the mean and median operations over the index $j$ respectively. Moreover, $\text{mean}^k_{j\in \mathcal{J}}$ corresponds to the mean of the top-$k$ highest values, over the index $j$. We call pre-activations (and activations) the values preceding (respectively following) the application of the ReLU activation function \citep{Nair2010}. In our experiments, batch normalization \citep{Ioffe2015} is applied before the ReLU, and pre-activation values are collected after batch normalization. In convolutional layers, a neuron refers to an entire feature map. The spatial dimensions of such a neuron's (pre-)activations are reduced through a global max pooling operation before applying our measures. \subsection{measures based on label hierarchies} The first two measures take advantage of datasets that include a hierarchy of labels. For example, CIFAR100 is organized into 20 superclasses (e.g. flowers) each comprising 5 subclasses (e.g. orchids, poppies, roses, sunflowers, tulips). We hypothesize that these hierarchical labels reflect an inherent structure of the data. In particular, we expect the subclasses to approximately correspond to different clusters amongst the samples of a superclass. Hence, measuring the extent by which a network differentiates subclasses when being trained on superclasses should reflect its ability to extract intraclass clusters during training. \subsubsection{Neuron-level subclass selectivity} The first measure quantifies how selective individual neurons are for a given subclass $C_i$ with respect to the other samples of the associated superclass $S_{s(i)}$. Here, strong selectivity means that the subclass $C_i$ can be reliably discriminated from the other samples of $S_{s(i)}$ based on the neuron's pre-activations\footnote{In other words, we are interested in evaluating whether the linear projection implemented by the neuron has been effective in isolating a given subclass.}. Let $\mu _{n,E}$ and $\sigma _{n,E}$ be the mean and standard deviation of a neuron $n$'s pre-activation values taken over the samples of set $E$. The measure is defined as follows: \begin{equation} \label{eq:c1} c_1 = \text{median}_{i\in \mathcal{I}} \text{ mean}^k_{n\in \mathcal{N}} \text{ } \frac{\mu _{n,C_i} - \mu _{n,S_{s(i)}\setminus C_i}}{\sigma _{n,C_i} + \sigma _{n,S_{s(i)}\setminus C_i}} \end{equation} Since we cannot expect all neurons of a network to be selective for a given subclass, we only consider the top-$k$ most selective neurons. The measure thus relies on $k$ neurons to capture the overall network's ability to differentiate each subclass. We noticed slightly better results when using the median operation instead of the mean to aggregate over the subclasses. We suspect this arises from the outlier behaviour of certain subclasses that we observe in Section \ref{sec:visu}. \subsubsection{Layer-level Silhouette score} The second measure quantifies to what extent the samples of a subclass are close together relative to the other samples from the associated superclass \textit{in the space induced by a layer's activations}. In other words, we measure to what degree different subclasses can be associated to different clusters in the intermediate representations of a network. We quantify this by computing the pairwise cosine distances\footnote{Using cosine distances provided slightly better results than euclidean distances.} on the samples of a superclass and applying the Silhouette score \citep{Kaufman2009} to assess the clustered structure of the subclasses. Let $\textit{silhouette}(a_l,S_{s(i)},C_i)$ be the mean silhouette score of subclass $C_i$ based on the activations $a_l$ of superclass $S_{s(i)}$ in layer $l$, the measure is then defined as: \begin{equation} c_2 = \text{median}_{i\in \mathcal{I}} \text{ mean}^k_{l\in \mathcal{L}} \text{ } \textit{ silhouette}(a_l,S_{s(i)},C_i) \end{equation} \subsection{Measures based on variance} To establish the generality of our results, we also design two measures that can be applied in absence of hierarchical labels. We hypothesize that the discrimination of intraclass clusters should be reflected by a high variance in the representations associated to a class. If all the samples of a class are mapped to close-by points in the neuron- or layer-level representations, it is likely that the neuron/layer did not identify intraclass clusters. \subsubsection{Variance in the neuron-level representations of the data} The first variance measure is based on standard deviations of a neuron's pre-activations. If the standard deviation computed over the samples of a class is high compared to the standard deviation computed over the entire dataset, we infer that the neuron has learned features that differentiate samples belonging to this class. The measure is defined as: \begin{equation} \label{eq:c3} c_3 = \text{mean}_{i\in \mathcal{I}} \text{ mean}^k_{n\in \mathcal{N}} \text{ } \frac{\sigma _{n,C_i}}{\sigma _{n,D}} \end{equation} A visual representation of the measure is provided in Figure \ref{neural_intraclass_selectivity}. \subsubsection{Variance in the layer-level representations of the data} The fourth measure transfers the neuron-level variance approach to layers by computing the standard deviations over the pairwise cosine distances calculated in the space induced by the layer's activations. Let $\Sigma _{l,E}$ be the standard deviation of the pairwise cosine distances between the samples of set $E$ in the space induced by layer $l$. The measure is defined as: \begin{equation} c_4 = \text{mean}_{i\in \mathcal{I}} \text{ mean}^k_{l\in \mathcal{L}} \text{ } \frac{\Sigma _{l,C_i}}{\Sigma _{l,D}} \end{equation} To compute this measure, we found it helpful to standardize the representations of different neurons. More precisely, we normalize each neuron's pre-activations to have zero mean and unit variance, then apply a bias and ReLU activation function such that $25\%$ of the samples are activated\footnote{Activating $25\%$ of the samples was an arbitrary choice that we did not seek to optimize. Studying the influence of this hyperparameter on the results is left as future work.}. This makes the measure invariant to rescaling and translation of each neuron's preactivations. \begin{figure}[h] \begin{center} \includegraphics[width=0.4\linewidth]{figures/neural_intraclass_selectivity.png} \end{center} \caption{Our simplest measure (denoted $c_3$) quantifies intraclass clustering through the ratio of standard deviations $\sigma _{n,C_i}$ and $\sigma _{n,D}$ associated to the class $C_i$ and the entire dataset $D$ respectively. Intuitively, a high ratio means that the neuron relies on features that \textit{differentiate} samples from $C_i$ although they belong to the same class. Despite its simplicity, our results in Section \ref{sec:results} suggest a remarkably strong connection between $c_3$ and generalization performance. This illustration of measure $c_3$ is based on a neuron from our experimental study, and the associated ratio is $2.47$. \label{neural_intraclass_selectivity} \end{figure} \section{Experimental setup} \label{sec:expsetup} The purpose of our experimental endeavour is to assess the predictive power of the proposed intraclass clustering measures with respect to the generalization performance. To this end, we reproduce the methodology introduced by \citet{Jiang}. First of all, this methodology puts emphasis on the scale of the experiments to improve the generality of the observations. Second, it tries to go beyond standard measures of correlation, and puts extra care to detect causal relationships between the measures and generalization performance. This is achieved through a systematic variation of multiple hyperparameters when building the set of models to be studied, combined with the application of principled correlation measures. \subsection{Building a set of models with varying hyperparameters} \label{sec:hyperparam} Our experiments are conducted on three datasets and two network architectures. The datasets are CIFAR10, CIFAR100 and the coarse version of CIFAR100 with 20 superclasses \citep{Krizhevsky2009}. The two network architectures are Wide ResNets \citep{He2016,Zagoruyko2016} (applied on CIFAR100 datasets) and VGG variants \citep{Simonyan2014} (applied on CIFAR10 dataset). Both architectures use batch normalization layers \citep{Ioffe2015} since they greatly facilitate the training procedure. In order to build a set of models with a wide range of generalization performances, we vary hyperparameters that are known to be critical. Since varying multiple hyperparameters improves the identification of causal relationships, \textit{we vary 8 different hyperparameters}: learning rate, batch size, optimizer (SGD or Adam \citep{Kingma2015}), weight decay, dropout rate \citep{Srivastava2014}, data augmentation, network depth and width. In total, we elaborated a set of 192 hyperparameter configurations for each dataset-architecture pair\footnote{The final set of VGG variants trained on CIFAR10 results from only 144 hyperparameter configurations as the network could not reach $\sim 100\%$ training accuracy with high dropout rates.}. More information about the hyperparameter configurations, training procedures and the resulting model performances are provided in Appendix (\ref{app:hyperparam}, \ref{app:hyperparam2}, \ref{app:training} and \ref{app:model_perfs}). It is worth noting that most models achieve close to $100\%$ training accuracy. Hence, models with poor test accuracy largely overfit. \subsection{Evaluating the measures' predictive power} \label{sec:kendall} \citet{Jiang} provides multiple criteria to evaluate generalization measures. We opted for the granulated Kendall coefficient for its simplicity and intuitiveness. This coefficient compares two rankings of the models, respectively provided by (i) the generalization measure of interest and (ii) their actual generalization performance. The Kendall coefficient is computed across variations of each hyperparameter independently. The average over all hyperparameters is then computed for the final score. The goal of this approach is to better capture causal relationships by not overvaluing measures that correlate with generalization only when specific hyperparameters are tuned. We compare our intraclass clustering-based measures to sharpness-based measures. The latter constituted the most promising measure family from the large-scale study presented in \citet{Jiang}. Among the many different sharpness measures, we leverage the magnitude-aware versions that measure sharpness through random and worst-case perturbations of the weights (denoted by $\frac{1}{\sigma '}$ and $\frac{1}{\alpha '}$, respectively, in \citet{Jiang}). We also include the application of these measures with perturbations applied on kernels only (i.e. not on biases and batch normalization weights) with batch normalization layers in batch statistics mode (i.e. not in inference mode). We observed that these alternate versions often provided better estimations of generalization performance. We denote these measures by $\frac{1}{\sigma ''}$ and $\frac{1}{\alpha ''}$. \section{Results} \label{sec:results} This section starts with a thorough evaluation of the relationship between the four proposed measures and the generalization performance, using the setup described in \ref{sec:expsetup}. Then, it presents a series of experiments to better characterize intraclass clustering, the phenomenon we expect to be captured by the measures. These experiments include (i) an analysis of the measures' evolution across layers and training iterations, (ii) a study of the neuron-level measures' sensitivity to $k$ in the mean over top-$k$ operation, as well as (iii) visualizations of subclass extraction in individual neurons. \subsection{Evaluating the measures' relationships with generalization} \label{sec:evaluation} We compute all four measures on the models trained on the CIFAR100 superclasses, and the two variance-based measures on the models trained on standard CIFAR100 and CIFAR10. We set $k=30$ for the neuron-level measures, meaning that $30$ neurons per subclass (for $c_1$) or class (for $c_3$) are used to capture intraclass clustering. For the layer-level measures, we set $k=5$ for residual networks and $k=1$ for VGG networks. We start our assessment of the measures' predictive power by visualizing their relationship with generalization performance in Figure \ref{generalization_intraclass}. \textit{We observe a clear trend across datasets, network architectures and measures, suggesting a tight connection between intraclass clustering and generalization.} To further support the conclusions of our visualizations, we evaluate the measures' predictive power through the granulated Kendall coefficient (cfr. Section \ref{sec:kendall}). Tables \ref{results_1}, \ref{results_2} and \ref{results_3} present the granulated Kendall rank-correlation coefficients associated with intraclass clustering and sharpness-based measures, for the three dataset-architecture pairs (Tables \ref{results_2} and \ref{results_3} are in Appendix \ref{app:suppres}). The Kendall coefficients further confirm the observations in Figure \ref{generalization_intraclass} by revealing strong correlations between intraclass clustering measures and generalization performance \textit{across all hyperparameters}. In terms of overall score, intraclass clustering measures surpass the sharpness-based measures variants by a large margin across all dataset-architecture pairs. On some specific hyperparameters, sharpness-based measures outperform intraclass clustering measures. In particular, $\frac{1}{\alpha '}$ performs remarkably well when the batch size parameter is varied, which is coherent with previous work \citep{Keskar2017}. \begin{figure}[h] \begin{center} \includegraphics[width=.9\linewidth]{figures/generalization_intraclass.png} \end{center} \caption{Visualization of the relationship between the four proposed intraclass clustering measures and generalization performance, across datasets and network architectures. The four columns correspond to $c_1$, $c_2$, $c_3$ and $c_4$ measures respectively. All measures display a tight connection with generalization performance, suggesting a crucial role for intraclass clustering in the implicit regularization of deep neural networks.} \label{generalization_intraclass} \end{figure} \renewcommand\cellalign{cc} \begin{table}[h] \caption{Kendall coefficients for resnets trained on CIFAR100 superclasses. Overall, the intraclass clustering measures surpass the sharpness-based measures by a large margin.} \label{results_1} \begin{center} \resizebox{\textwidth}{!}{ \begin{tabular}{cc cccccccc |c} & & \makecell{learning \\ rate }&\makecell{batch \\ size }&\makecell{weight \\ decay } & optim. &\makecell{dropout \\ rate }&\makecell{data \\ augm. } & width &depth&\makecell{ total \\ score }\\ \hline \multirow{4}{*}{\makecell{Intraclass \\ clustering }} & \multicolumn{1}{|c|}{$c_1$} & 0.88 & 0.31 & 0.38 & 0.67 & 0.96 &\bf 1.0 &\bf 0.81 & 0.69 & 0.71\\ & \multicolumn{1}{|c|}{$c_2$} & 0.86 & 0.5 &\bf 0.67 & 0.58 &\bf 0.99 &\bf 1.0 & 0.38 & 0.62 & 0.7\\ & \multicolumn{1}{|c|}{$c_3$} & 0.88 & 0.6 & 0.46 & 0.62 & 0.81 &\bf 1.0 &\bf 0.81 & 0.66 & \bf 0.73\\ & \multicolumn{1}{|c|}{$c_4$} &\bf 0.89 & 0.69 & 0.62 & 0.65 & 0.86 &\bf 1.0 & 0.44 & 0.69 & \bf 0.73\\ \hline \multirow{4}{*}{\makecell{Sharpness}} & \multicolumn{1}{|c|}{$1$ / $\sigma '$} & 0.81 & 0.51 & 0.31 & 0.69 & 0.28 & -0.58 & 0.67 & 0.61 & 0.41\\ &\multicolumn{1}{|c|}{$1$ / $\sigma ''$} & 0.86 & 0.58 & 0.17 & 0.4 & -0.05 & 0.42 & 0.69 & \bf 0.72 & 0.47\\ & \multicolumn{1}{|c|}{$1$ / $\alpha '$} & 0.88 &\bf 0.94 & 0.29 & 0.26 & 0.6 & 0.08 & -0.03 & -0.09 & 0.37\\ & \multicolumn{1}{|c|}{$1$ / $\alpha ''$} & 0.85 & 0.8 & 0.48 &\bf 0.71 & 0.16 & -0.08 & 0.08 & 0.34 & 0.42\\ \hline \end{tabular}} \end{center} \end{table} \subsection{Influence of $k$ on the Kendall coefficients of neuron-level measures} \label{sec:k_sensitivity} In our evaluation of the measures in Section \ref{sec:evaluation}, the $k$ parameter, which controls the number of highest values considered in the mean over top-$k$ operations, was fixed quite arbitrarily. Figure \ref{fig:locality} shows how the Kendall coefficient of $c_1$ and $c_3$ changes with this parameter. We observe a relatively low sensitivity of the measures' predictive power with respect to $k$. In particular, in the case of Resnets trained on CIFAR100 the Kendall coefficient associated with $c_3$ seems to stay above $0.7$ for any $k$ in the range $[1,900]$. The optimal $k$ value changes with the considered dataset and architecture. We leave the study of this dependency as a future work. Observing the influence of $k$ also confers insights about the phenomenon captured by the measures. Figure \ref{fig:locality} reveals that very small $k$ values work remarkably well. Using a single neuron per subclass ($k=1$ in Equation \ref{eq:c1}) confers a Kendall coefficient of $0.69$ to $c_1$. Using a single neuron per class confers a Kendall coefficient of $0.78$ to $c_3$ in the case of VGGs trained on CIFAR10. \textit{These results suggest that individual neurons play a crucial role in the extraction of intraclass clusters during training.} The fact that the Kendall coefficients monotonically decrease after some $k$ value suggests that the extraction of a given intraclass cluster takes place in a sub part of the network, indicating some form of specialization. \begin{figure}[h] \begin{center} \includegraphics[width=.85\linewidth]{figures/locality.png} \end{center} \caption{Plots showing how the Kendall coefficients of $c_1$ and $c_3$ change with parameter $k$ (cfr. Equations \ref{eq:c1} and \ref{eq:c3}). The $k$ parameter associated to $c_1$ is multiplied by $5$ in the plots, to enable comparison with $c_3$ (there are $5$ subclasses in each of CIFAR100's superclasses). The total number of neurons varies from $1920$ to $2880$ in Resnets and from $960$ to $1440$ in VGGs. The plots reveal that generalization performance can be quite accurately estimated using the representations of a surprisingly small set of neurons ($k=1$, i.e. a single neuron per class, suffices in some cases).} \label{fig:locality} \end{figure} \subsection{Evolution of the measures across layers} We pursue our experimental endeavour with an analysis of the proposed measures' evolution across layers. For each dataset-architecture pair, we select $64$ models which have the same depth hyperparameter value. We then compute the four measures on a layer-level basis (we use the top-5 neurons of each layer for the neuron-level measures) and average the resulting values over the $64$ models. Figure \ref{fig:layerwise_C100coarse} depicts how the average value of each measure evolves across layers for Resnets trained on CIFAR100 superclasses. The results associated with the two other dataset-architecture pairs are in Appendix \ref{app:suppres}, Figures \ref{fig:layerwise_C100} and \ref{fig:layerwise_C10}. We observe two interesting trends. First, all four measures tend to increase with layer depth. \textit{This suggests that intraclass clustering also occurs in the deepest representations of neural networks, and not merely in the first layers, which are commonly assumed to capture generic or class-independent features.} Second, the variance based measures ($c_3$ and $c_4$) decrease drastically in the penultimate layer. We suspect this reflects the grouping of samples of a class in tight clusters in preparation for the final classification layer (such behaviour has been studied in \citet{Kamnitsas2018,Muller2019}). The measures $c_1$ and $c_2$ are robust to this phenomenon as they rely on relative distances inside a single class, irrespectively of the representations of the rest of the dataset. \begin{figure}[h] \begin{center} \includegraphics[width=.7\linewidth]{figures/layerwise_C100coarse-WRN.png} \end{center} \caption{Evolution of each measure (after averaging over 64 models) across layers. The overall increase of the measures with layer depth suggests that intraclass clustering occurs even in the deepest representations of neural networks.} \label{fig:layerwise_C100coarse} \end{figure} \subsection{Evolution of the measures over the course of training} \label{sec:evolution_training} In this section, we provide a small step towards the understanding of the dynamics of the phenomenon captured by the measures. We visualize in Figure \ref{train_evolution} the evolution of the measures over the course of training of three Resnet models. The first interesting observation comes from the comparison of models with high and low generalization performances. It appears that \textit{their differences in terms of intraclass clustering measures arise essentially during the early phase of training}. The second observation is that significant increases in intraclass clustering measures systematically coincide with significant increases of the training accuracy (in the few first epochs and around epoch $150$, where the learning rate is reduced). This suggests that supervised training could act as a necessary driver for intraclass clustering ability, despite not explicitly targeting such behaviour. \begin{figure}[h] \begin{center} \includegraphics[width=1.\linewidth]{figures/train_evolution.png} \end{center} \caption{Evolution of the intraclass clustering measures over the course of training for three models with different generalization performances. We observe that the differences between models with high and low generalization performance arise essentially in the early phase of training. \label{train_evolution} \end{figure} \subsection{Visualization of subclass extraction in individual neurons} \label{sec:visu} We have seen in Section \ref{sec:k_sensitivity} that the measure $c_1$ reaches a Kendall coefficient of $0.69$ when considering a single neuron per subclass ($k=1$ in Eq. \ref{eq:c1}). Visualizing the training dynamics in this specific neuron should enable us to directly observe the phenomenon captured by $c_1$. We study a Resnet model trained on CIFAR100 superclasses with high generalization performance ($82.31\%$ test accuracy). For each of the $100$ subclasses, we compute the selectivity value and the index of the most selective neuron based on the part of Eq. \ref{eq:c1} to which the median operation is applied. We then rank the subclasses by their selectivity value, and display the training dynamics of the neurons associated to the subclasses with maximum and median selectivity values in Figure \ref{fig:selectivity_visu}. The evolution of the neurons' preactivation distributions along training reveals that the 'Rocket' subclass, which has the highest selectivity value, is progressively distinguished from its corresponding superclass during training. \textit{The neuron behaves like it was trained to identify this specific subclass although no supervision or explicit training mechanisms were implemented to target this behaviour.} The same phenomenon occurs to a lesser extent with the 'Ray' subclass, which has the median selectivity value. We observed that very few subclasses reached selectivity values as high as the 'Rocket' subclass (the distribution of selectivity values is provided in Figure \ref{fig:selectivity_distrib} in Appendix \ref{app:suppres}). We suspect that the occurrence of such outliers explain why the median operation outperformed the mean in the definition of $c_1$ and $c_2$. \begin{figure}[h] \begin{center} \includegraphics[width=.85\linewidth]{figures/neural_selectivity_visu.png} \end{center} \caption{Evolution along training of the preactivation distributions associated with the neurons that are the most selective (cfr. Eq. \ref{eq:c1}) for 'Rocket' and 'Ray' subclasses. The neurons behave like they were trained to identify these specific subclasses although no supervision or explicit training mechanisms were implemented to target this behaviour.} \label{fig:selectivity_visu} \end{figure} \subsection{Discussion} Our results show that all four measures (i) strongly correlate with generalization, (ii) tend to increase with layer depth and (iii) change mostly in the early phase of training. These similarities suggest that the four measures capture one unique phenomenon. Since all measures quantify to what extent a neural network differentiates samples from the same class, the captured phenomenon presumably consists in the identification of intraclass clusters by neural networks. This hypothesis is further supported by the neuron-level visualizations provided in Section \ref{sec:visu}. Overall, our results thus provide empirical evidence for this works hypotheses, i.e. that intraclass clustering emerges during standard neural network training and constitutes an implicit form of regularization. The mechanisms that induce intraclass clustering in deep neural networks remain undisclosed, leaving a lot of room for future work. In particular, Section \ref{sec:k_sensitivity} reveals that understanding the local nature of intraclass clustering could lead to better estimation of the optimal $k$ parameter and increase the measures' predictive power. Additionally, the neuron-level visualizations in Figures \ref{neural_intraclass_selectivity} and \ref{fig:selectivity_visu} suggest that quantifying the bimodal shape of a neuron's preactivations for each class might provide an alternative measure of intraclass clustering that doesn't require hierarchical labels. \section{Related work} This work follows the line of inquiry initiated by \citet{Neyshabur2015,Zhang2017}, and tries to unveil the phenomena underlying the generalization ability of deep neural networks. We follow an empirical approach based on the design of measures that correlate with generalization performance. This approach has been extensively used in recent years, leading to measures such as sharpness of minima \citep{Keskar2017}, sensitivity \citep{Novak2018}, reliance on single directions \citep{Morcos2018a} and stiffness \citep{Fort}. To our knowledge, we are the first work to empirically study the relationship between intraclass clustering measures and generalization. Many observations made in our paper are coherent with previous work. In the context of transfer learning, \citet{Huh2016a} shows that representations that discriminate ImageNet classes naturally emerge when training on their corresponding superclasses, suggesting the occurrence of intraclass clustering. Sections \ref{sec:k_sensitivity} and \ref{sec:visu} suggest a key role for individual neurons in the extraction of intraclass clusters. This is coherent with the large body of work that studied the emergence of interpretable features in the hidden neurons (or feature maps) of deep nets \citep{Zeiler2014,ZissermanICLR2014,Yosinski2015,Zhou2015, Bau}. In Section \ref{sec:evolution_training}, we notice that intraclass clustering occurs mostly in the early phase of training. Previous works have also highlighted the criticality of this phase of training with respect to regularization \citep{Golatkar2019}, optimization trajectories \citep{Jastrzebski2020,Fort2020}, Hessian eigenspectra \citep{Gur-Ari2016}, training data perturbations \citep{Achille2019} and weight rewinding \citep{Frankle2020a, Frankle2020}. \citet{Morcos2018a,Leavitt2020} have shown that class-selective neurons are not necessary and might be detrimental for performance. This is coherent with our observation that neurons that differentiate samples from the same class improve performance. \section{Conclusion} Our work starts from the observation that classes of samples from standard image classification datasets are usually structured into multiple clusters. Since learning structure in the data is commonly associated to generalization, we ask if state-of-the-art neural network extract such clusters. While no supervision or training mechanisms are explicitly programmed into deep neural networks for targeting this behaviour, it is possible that this learning ability implicitly emerges during training. Such a hypothesis is especially compelling as recent work on generalization conjectured the emergence of implicit forms of regularization during deep neural network training. Our work provides four different attempts at quantifying intraclass clustering. We then conduct a large-scale experimental study to characterize intraclass clustering and its potential relationship with generalization performance. Overall, the results suggest a crucial role for intraclass clustering in the regularization of deep neural networks. We hope our work will stimulate further investigations of intraclass clustering and ultimately lead to a better understanding of the generalization properties of deep neural networks. \subsubsection*{Acknowledgments} Thanks to the reviewers for suggesting several experiments that were added during the rebuttal phase and increased the quality of this paper. Thanks to Amirafshar Moshtaghpour, Anne-Sophie Collin, Antoine Vanderschueren, Victor Joos de ter Beerst, Tahani Madmad, Pierre Carbonnelle, Vincent Francois, Gilles Peiffer for proofreading and helpful feedback. Thanks to the Reddit r/machinelearning community for keeping us up to date with our fast-moving field. Simon and Christophe are Research Fellows of the Fonds de la Recherche Scientifique – FNRS, which provided funding for this work.
{'timestamp': '2021-03-12T02:26:37', 'yymm': '2103', 'arxiv_id': '2103.06733', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06733'}
arxiv
\section{Introduction} Best match graphs (BMGs) are vertex-colored digraphs that appear in mathematical phylogenetics as a repesentation of a gene's evolutionary closest relatives in another species \cite{Geiss:19a}. That is, given a rooted tree $T$, a vertex (gene) $x$ in the BMG $G(T,\sigma)$ is colored by the species $\sigma(x)$ in which it resides, and there is an arc $(x,y)$ if there is no other gene $y'$ in species $\sigma(y')=\sigma(y)\ne\sigma(x)$ with a later last common ancestor than the last common ancestor $\lca_T(x,y)$ of $x$ and $y$ in $T$. Although rooted trees are crucial for the definition of BMGs, they are, however, unknown in practice and we are often only left with estimates of their BMGs. In general, there are multiple trees that ``explain'' the same BMG. There is, however, a unique least resolved tree (LRT) for each BMG, which can be obtained from $T$ by contracting certain edges \cite{Geiss:19a}. The LRTs will play a central role in this contribution. The subgraph of a BMG induced by the vertices of some subset of colors is again a BMG. Every BMG therefore can be viewed as the disjoint union of (the arc sets of) 2-colored BMGs. These 2-BMGs \cite{Geiss:19a,Korchmaros:20a,Korchmaros:20b} are bipartite and form a common subclass of the \emph{sink-free} digraphs \cite{Cohn:02,Abrams:10} and the \emph{bi-transitive} digraphs \cite{Das:20}. Estimates of graphs from real-life data tend to be affected by noise and thus typically will violate the defining properties of the desired graph class. The solution of a corresponding graph modification problem \cite{Natanzon:2001} therefore can by employed as a means of noise reduction, see e.g.\ \cite{Hellmuth:15a}. The arc modification problems (deletion, completion, and editing) for BMGs are NP-complete in general \cite{Schaller:21b}, and remain hard even for the special case of 2 colors. Phylogenetic trees are often considered to be binary in theory. Most polytomies are therefore considered a limitation of the available data or method of tree reconstruction \cite{Maddison:89,DeSalle:94} rather than a biological reality \cite{Hoelzer:94,Slowinski:01}. In the setting of BMGs, this distinction is important because not all BMGs can be derived from binary gene trees. Instead, \emph{binary-explainable} BMGs (beBMGs) form a proper subclass \cite{Schaller:21c} that is distinguished by a single forbidden induced subgraph, the \emph{hourglass}, from other BMGs \cite{Schaller:21a}. The arc modification problems for beBMGs are NP-complete \cite{Schaller:21b,Schaller:21c} as well. In the context of correcting empirical best match data, it is natural to ask whether the problem of modifying a BMG to a beBMG is as difficult as the general case. It is, in fact, not unusual that graph modification problems that are hard in general become easy when the input is confined to a -- usually restrictive -- class of graphs, see e.g.\ \cite{Liu:11,Gao:13}. Here we show that the problem of completing a 2-colored BMG to a beBMG can indeed be solved in polynomial time. To prove this result we make use of the fact that every BMG is associated with a unique \emph{least resolved tree} (LRT). Thm.~\ref{thm:edge-contr-supergraph} shows that the property of being the LRT for some BMG is preserved under contraction of inner edges. This observation leads to the explicit construction of a ``collapsed tree'' from the LRT of the input BMG $(G,\sigma)$ which not only is the LRT of a 2-colored beBMG but also minimizes the number of arcs that need to be inserted to obtain a beBMG from $(G,\sigma)$. The construction does not generalize to more than $2$ colors. \section{Notation} We consider simple directed graphs (digraphs) $G=(V,E)$ with vertex set $V$ and \emph{arc} set $E\subseteq V\times V \setminus \{(v,v)\mid v\in V\}$ and rooted (undirected) trees $T$ with root $\rho$. Correspondingly, we write $(x,y)$ for directed arcs from $x$ to $y$, and $xy$ for undirected tree edges. Given a tree $T$, we write $V(T)$ and $E(T)$ for its set of vertices and edges, resp., $L(T)$ for the set of leaves, and $V^0(T)=V(T)\setminus L(T)$ for the set of inner vertices. A vertex coloring of a graph is a map $\sigma:V\to S$, where $S$ is a non-empty set of colors. A vertex coloring of $G$ is \emph{proper} if $\sigma(x)\ne\sigma(y)$ for all $(x,y)\in E(G)$. We will also consider \emph{leaf-colorings} $\sigma\colon L(T)\to S$ for trees $T$, and denote by $(G,\sigma)$ and $(T,\sigma)$ vertex-colored graphs and leaf-colored trees, respectively. Given a rooted tree, we write $x \preceq_T y$ if $y$ is an \emph{ancestor} of $x$, i.e., if $y$ lies along the unique path from $\rho$ to $x$ in $T$. We write $x \prec_T y$ if $x \preceq_T y$ and $x\ne y$. The relation $\preceq_T$ is a partial order on $T$. If $xy\in E(T)$ and $x\prec_T y$, then $y$ is the unique \emph{parent} of $x$, denoted by $\mathsf{par}_T(x)$, and $x$ a \emph{child} of $y$. The set of children of a vertex $u\in V(T)$ is denoted by $\mathsf{child}_T(u)$. A rooted tree $T$ is phylogenetic if every inner vertex $x\in V^0(T)$ has at least two children. All trees in this contribution are assumed to be phylogenetic. Furthermore, we write $T(u)$ for the subtree rooted in $u$, i.e., $V(T(u))=\{y\in V(T) \mid y\preceq_T u\}$. The \emph{last common ancestor} of a non-empty subset $A\subseteq V(T)$ is the unique $\preceq_T$-minimal vertex of $T$ that is an ancestor of every $u\in A$. For convenience, we write $\lca(x,y,\dots)$ instead of $\lca(\{x,y,\dots\})$. A triple $xy|z$ is a rooted tree with the three leaves $x$, $y$, and $z$ such that $\lca(x,y)\prec \lca(x,y,z)$. If $e\in E(T)$, we denote by $T_e$ the tree obtained by contracting the edge $e$. We will only be interested in contractions of inner edges, i.e., those that preserve the leaf set. We say that $T$ \emph{displays} a tree $T'$, in symbols $T'\le T$, if $T'$ can be obtained from $T$ as the minimal subtree of $T$ that connects all elements in $L(T')$ with root $\lca_{T}(L(T'))$ and by suppressing all inner vertices that only have one child left. \section{Best Match Graphs, Least Resolved Trees, and Binary-Explainable BMGs} In this section, we first summarize some properties of best match graphs and their least resolved trees. We then show that the contraction of inner edges in least resolved trees always leads to least resolved trees. Furthermore, we recall some properties of binary-explainable best match graphs that will be needed later. \begin{Definition} Let $(T,\sigma)$ be a leaf-colored tree. A leaf $y\in L(T)$ is a \emph{best match} of the leaf $x\in L(T)$ if $\sigma(x)\neq\sigma(y)$ and $\lca(x,y)\preceq_T \lca(x,y')$ holds for all leaves $y'$ of color $\sigma(y')=\sigma(y)$. \label{def:BMG} \end{Definition} Given $(T,\sigma)$, the graph $G(T,\sigma) = (V,E)$ with vertex set $V=L(T)$, vertex-coloring $\sigma$, and with arcs $(x,y)\in E$ if and only if $y$ is a best match of $x$ w.r.t.\ $(T,\sigma)$ is called the \emph{best match graph} (BMG) of $(T,\sigma)$ \cite{Geiss:19a}: \begin{Definition}\label{def:BestMatchGraph} An arbitrary vertex-colored graph $(G,\sigma)$ is a \emph{best match graph (BMG)} if there exists a leaf-colored tree $(T,\sigma)$ such that $(G,\sigma) = G(T,\sigma)$. In this case, we say that $(T,\sigma)$ \emph{explains} $(G,\sigma)$. \end{Definition} \begin{Proposition} \cite[Lemma~8]{Schaller:21a} If $T_A$ is obtained from a tree $T$ by contracting all edges in a subset $A$ of inner edges in $T$, then $G(T,\sigma)\subseteq G(T_A,\sigma)$. \label{prop:TA} \end{Proposition} An edge $e$ of a leaf-colored tree is \emph{redundant} (w.r.t.\ $(G,\sigma)$) if it can be contracted without affecting the BMG, i.e., if $G(T,\sigma)=G(T_e,\sigma)$. \begin{Definition} A leaf-colored tree $(T,\sigma)$ is \emph{least resolved} if there is no non-empty subset $A\subseteq E(T)$ such that $G(T,\sigma)=G(T_A,\sigma)$. \end{Definition} We define the notion of being least resolved here as a property of the tree $(T,\sigma)$ alone. Of course, every least resolved tree is also \emph{least resolved w.r.t.\ some BMG}, namely the (uniquely defined) graph $G(T,\sigma)$. It is shown in \cite{Geiss:19a} that $(T,\sigma)$ is least resolved if and only if it does not contain a redundant edge. In particular, we have \begin{Proposition} \cite[Thm.~8]{Geiss:19a} Every BMG $(G,\sigma )$ is explained by a unique least resolved tree (LRT), which is obtained from an arbitrary tree $(T,\sigma)$ that explains $(G,\sigma)$ by contraction of all redundant edges of $(T,\sigma)$. \label{prop:LRTuniq} \end{Proposition} In particular, therefore, there is a bijection between BMGs and LRTs. Surprisingly, the property of being least resolved for some BMG is preserved under contraction of inner edges of $T$. \begin{Theorem} \label{thm:edge-contr-supergraph} Suppose $(T,\sigma)$ is least resolved and let $A$ be a set of inner edges of $T$, and denote by $T_A$ the tree obtained from a tree $T$ by contracting all edges in $A$. Then $(T_A,\sigma)$ is again least resolved. \end{Theorem} \begin{proof} Assume that $(T,\sigma)$ is least resolved, i.e., it does not contain any redundant edges, and set $(G,\sigma)\coloneqqG(T,\sigma)$. Lemma~7 in \cite{Schaller:21a} states that an inner edge $e=uv$ with $v\prec_{T} u$ in $(T,\sigma)$ is non-redundant if and only if there is an arc $(a,b)\in E(G)$ such that $\lca_{T}(a,b)=v$ and $\sigma(b)\in \sigma( L(T(u)) \setminus L(T(v)) )$. The statement trivially holds if $(T,\sigma)$ has at most one inner edge. Hence, we assume that $(T,\sigma)$ has at least two distinct inner edges $e=uv$ and $e'$. We show that every non-redundant edge $e$ in $T$ remains non-redundant in $T_{e'}$. Thus, let $e$ be a non-redundant edge in $T$. Hence, there is an arc $(a,b)\in E(G)$ such that $\lca_{T}(a,b)=v$ and $\sigma(b)\in \sigma( L(T(u)) \setminus L(T(v)) )$. Now consider the tree $T_{e'}$ obtained from $T$ by contraction of the inner edge $e'\ne e$. Clearly, we also have $\lca_{T_{e'}}(a,b)=v$ and $\sigma(b)\in \sigma( L(T_{e'}(u)) \setminus L(T_{e'}(v)) )$. Prop.~\ref{prop:TA} implies $G(T,\sigma)\subseteqG(T_{e'},\sigma)$, and thus, $(a,b)\in E(G(T_{e'},\sigma))$. Making again use of the characterization of redundant edges in \cite[Lemma~7]{Schaller:21a}, we conclude that $e$ is non-redundant in $(T_{e'},\sigma)$. Since both $e$ and $e'$ were chosen arbitrarily, we observe that the contraction of a single inner edge does not produce new redundant edges. We can therefore apply this argument for each step in the consecutive contraction of all edges in $A$ (in an arbitrary order) to conclude that $(T_A,\sigma)$ does not contain redundant edges. Therefore, Prop.~\ref{prop:LRTuniq} implies that $(T_A,\sigma)$ is least resolved. \end{proof} \begin{Corollary} If $(T,\sigma)$ is least resolved and $A$ is a non-empty set of inner edges of $T$, then $G(T,\sigma)\subsetneqG(T_A,\sigma)$. \end{Corollary} \begin{proof} By Prop.~\ref{prop:TA}, we have $G(T,\sigma)\subseteqG(T_A,\sigma)$. By Thm.~\ref{thm:edge-contr-supergraph}, $(T_A,\sigma)$ is least resolved. Since the LRT of a BMG is unique (cf.\ Prop.~\ref{prop:LRTuniq}), we have $G(T,\sigma)\neqG(T_A,\sigma)$. \end{proof} As another immediate consequence of Thm.~\ref{thm:edge-contr-supergraph} and uniqueness of the LRT of a BMG (Prop.~\ref{prop:LRTuniq}), we obtain \begin{Corollary} If $e$ and $e'$ are two distinct inner edges of a least resolved tree $(T,\sigma)$, then $G(T_{e},\sigma)\neG(T_{e'},\sigma)$. \end{Corollary} Let us now turn to the subclass of BMGs that can be explained by a binary tree. \begin{Definition}\label{def:beBMG} A \emph{binary-explainable BMG} (\emph{beBMG}) is a BMG $(G,\sigma)$ such that there is a binary leaf-colored tree $(T,\sigma)$ that explains $(G,\sigma)$. \end{Definition} As shown in \cite{Schaller:21a}, beBMGs can be characterized among BMGs by means of a simple forbidden colored induced subgraph: \begin{Definition} An \emph{hourglass} in a properly vertex-colored graph $(G,\sigma)$, denoted by $[xy \mathrel{\text{\ooalign{$\searrow$\cr$\nearrow$}}} x'y']$, is a subgraph $(G[Q],\sigma_{|Q})$ induced by a set of four pairwise distinct vertices $Q=\{x, x', y, y'\}\subseteq V(G)$ such that (i) $\sigma(x)=\sigma(x')\ne\sigma(y)=\sigma(y')$, (ii) $(x,y),(y,x)$ and $(x'y'),(y',x')$ are bidirectional arcs in $G$, (iii) $(x,y'),(y,x')\in E(G)$, and (iv) $(y',x),(x',y)\notin E(G)$. \end{Definition} An hourglass together with a (non-binary) tree explaining it is illustrated in Fig.~\ref{fig:forb-sg-and-hourglass.pdf}(A). A properly vertex-colored digraph that does not contain an hourglass as an induced subgraph is called \emph{hourglass-free.} \begin{figure}[htb] \centering \includegraphics[width=0.75\textwidth]{./forb-sg-and-hourglass.pdf} \caption{(A): An hourglass as the characteristic forbidden induced subgraph of beBMGs and its non-binary explaining tree. (B): The three classes of forbidden induced subgraphs of 2-colored BMGs (see Def.~\ref{def:forbidden-subgraphs} below). The gray dashed arcs may or may not exist.} \label{fig:forb-sg-and-hourglass.pdf} \end{figure} \begin{Proposition}{\cite[Lemma~31 and Prop.~8]{Schaller:21a}} \label{prop:binary-iff-subtree-colors} For every BMG $(G,\sigma)$ explained by a tree $(T,\sigma)$, the following three statements are equivalent: \begin{enumerate} \item $(G,\sigma)$ is binary-explainable. \item $(G,\sigma)$ is hourglass-free. \item There is no vertex $u\in V^0(T)$ with three distinct children $v_1$, $v_2$, and $v_3$ and two distinct colors $r$ and $s$ satisfying \begin{enumerate} \item $r\in\sigma(L(T(v_1)))$, $r,s\in\sigma(L(T(v_2)))$, and $s\in\sigma(L(T(v_3)))$, and \item $s\notin\sigma(L(T(v_1)))$, and $r\notin\sigma(L(T(v_3)))$. \end{enumerate} \end{enumerate} \end{Proposition} It is worth noting that the LRTs of beBMGs are usually not binary. In fact, it is shown in \cite{Schaller:21c} that, for a beBMG $(G,\sigma)$, there exists a unique \emph{binary refinable tree} (BTR) $B(G,\sigma)$ with the property that every binary tree $(T,\sigma)$ that displays $B(G,\sigma)$ explains $(G,\sigma)$. The BRT is in general much better resolved than the LRT of $(G,\sigma)$. \section{Two-Colored BMGs} Let us now briefly focus on 2-colored BMGs (2-BMGs). Since arcs in BMG can only connect vertices with different colors, every 2-BMG is bipartite. Furthermore, every leaf $x$ in a tree with two leaf colors has at least one best match $y$. Every 2-BMG is therefore \emph{sink-free}, i.e., every vertex has at least one out-neighbor. Furthermore, \citet{Schaller:21b} showed that the following graphs (see also Fig.~\ref{fig:forb-sg-and-hourglass.pdf}(B)) are forbidden induced subgraphs for 2-BMGs. \begin{Definition}[F1-, F2-, and F3-graphs]\par\noindent \begin{itemize} \item[\AX{(F1)}] A properly 2-colored graph on four distinct vertices $V=\{x_1,x_2,y_1,y_2\}$ with coloring $\sigma(x_1)=\sigma(x_2)\ne\sigma(y_1)=\sigma(y_2)$ is an \emph{F1-graph} if $(x_1,y_1),(y_2,x_2),(y_1,x_2)\in E$ and $(x_1,y_2),(y_2,x_1)\notin E$. \item[\AX{(F2)}] A properly 2-colored graph on four distinct vertices $V=\{x_1,x_2,y_1,y_2\}$ with coloring $\sigma(x_1)=\sigma(x_2)\ne\sigma(y_1)=\sigma(y_2)$ is an \emph{F2-graph} if $(x_1,y_1),(y_1,x_2),(x_2,y_2)\in E$ and $(x_1,y_2)\notin E$. \item[\AX{(F3)}] A properly 2-colored graph on five distinct vertices $V=\{x_1,x_2,y_1,y_2,y_3\}$ with coloring $\sigma(x_1)=\sigma(x_2)\ne\sigma(y_1)=\sigma(y_2)=\sigma(y_3)$ is an \emph{F3-graph} if \newline $(x_1,y_1),(x_2,y_2),(x_1,y_3),(x_2,y_3)\in E$ and $(x_1,y_2),(x_2,y_1)\notin E$. \end{itemize} \label{def:forbidden-subgraphs} \end{Definition} \begin{Proposition} \cite[Thm.~4.4]{Schaller:21b} \label{prop:forb-subgraph-charac} A properly 2-colored graph is a BMG if and only if it is sink-free and does not contain an induced F1-, F2-, or F3-graph. \end{Proposition} A peculiar property of 2-BMGs is that their LRTs can be constructed efficiently by recursively decomposing an input 2-BMG into non-trivial induced subgraphs and individual vertices \cite{Schaller:21c}. Although we will not need this construction here, one of its corner stones plays an important role below. \begin{Definition}[Support Leaves] For a given tree $T$, the set $S_{u} \coloneqq \mathsf{child}_T(u)\cap L(T)$ is the set of all \emph{support leaves} of vertex $u\in V(T)$. \end{Definition} We note in passing that every inner vertex $u$ of the LRT of a 2-BMG $(G,\sigma)$, with the possible exception of the root $\rho$, has a non-empty set of support leaves $S_{u}$, and $S_{\rho}\ne\emptyset$ if and only if $(G,\sigma)$ is connected \cite{Schaller:21x}. In the following, we will make use of a connection between a 2-BMG and its LRT: \begin{Lemma} \label{lem:2-BMG-outneighbors-subtree} Let $(G,\sigma)$ be a 2-BMG, $(T,\sigma)$ its LRT and $x,y\in L(T)=V(G)$. Then $(x,y)\in E(G)$ if and only if $\sigma(x)\ne \sigma(y)$ and $y\in L(T(\mathsf{par}_T(x)))$. \end{Lemma} \begin{proof} First note that, since $(G,\sigma)$ is 2-colored, $(T,\sigma)$ has at least two leaves and $u\coloneqq\mathsf{par}_T(x)$ is always defined. First, assume $\sigma(x)\ne\sigma(y)$, and thus $x\ne y$, and let $y\in L(T(u))$. Since $x$ is a child of $u$, we have $\lca_{T}(x,y)=u$. Moreover, since $u$ is the parent of $x$, there is no vertex $y'$ of color $\sigma(y)$ such that $\lca_{T}(x,y')\prec_T\lca_T(x,y)=u$. Hence, $y$ is a best match of $x$, i.e., $(x,y)\in E(G)$. Now suppose, for contraposition, that $\sigma(x)=\sigma(y)$ or $y\notin L(T(u))$. If $\sigma(x)=\sigma(y)$, then, by definition, $(x,y)\notin E(G)$. If $y\notin L(T(u))$, then $u\prec_{T}\rho_T$. Hence, we can apply Cor.~1 in \cite{Schaller:21x} to the inner vertex $u$ to conclude that $|\sigma(L(T(u)))|>1$, i.e., the subtree $L(T(u))$ contains both colors. Thus, we can find a vertex $y'$ of color $\sigma(y)$ such that $\lca_{T}(x,y')\preceq_{T}u\prec_{T}\lca_{T}(x,y)$ which implies that $(x,y)\notin E(G)$. \end{proof} As an immediate consequence, we find \begin{Corollary} \label{cor:reciprocal-iff-same-parent} Let $(G,\sigma)$ be a 2-BMG, $(T,\sigma)$ its LRT and $x,y\in V(G)=L(T)$. Then $(x,y),(y,x)\in E(G)$ if and only if $\sigma(x)\ne \sigma(y)$ and $\mathsf{par}_T(x)=\mathsf{par}_T(y)$. \end{Corollary} \section{Completion of a 2-BMG to a 2-beBMG} Writing $G+F\coloneqq (G, E\cup F)$ for a graph $G=(V,E)$ and arc set $F\subseteq V\times V \setminus \{(v,v)\mid v\in V\}$, consider the following graph completion problem: \begin{Problem}[\PROBLEM{2-BMG Completion restricted to Binary-Explainable Graphs (2-BMG CBEG)}]\ \\ \begin{tabular}{ll} \emph{Input:} & A properly 2-colored digraph $(G =(V,E),\sigma)$ and an integer $k$.\\ \emph{Question:} & Is there a subset $F\subseteq V\times V \setminus (\{(v,v)\mid v\in V\} \cup E)$ such that\\ & $|F|\leq k$ and $(G+ F,\sigma)$ is a binary-explainable 2-BMG? \end{tabular} \end{Problem} In the general case, \PROBLEM{2-BMG CBEG} is NP-complete \cite[Cor.~5.11]{Schaller:21c}. Here we are interested in the restriction of the \PROBLEM{2-BMG CBEG} problem with BMGs as input. The following result holds for BMGs and their completions to beBMGs with an arbitrary number of colors. \begin{Lemma} \label{lem:fill-houglass} Let $(G',\sigma)$ be a completion of a BMG $(G,\sigma)$ to a beBMG, and let $[xy\mathrel{\text{\ooalign{$\searrow$\cr$\nearrow$}}} x'y']$ be an induced hourglass in $(G,\sigma)$. Then $(G',\sigma)$ contains both arcs $(x',y)$ and $(y',x)$. \end{Lemma} \begin{proof} It is shown in \cite[Obs.~1]{Geiss:19a} that the subgraphs of a BMG induced by all vertices with any two given colors is a 2-BMG. Since $(G',\sigma)$ is a (binary-explainable) BMG, all of its 2-colored induced subgraphs are therefore 2-BMGs. By assumption, $(G,\sigma)$ is not binary-explainable since it contains the hourglass $[xy\mathrel{\text{\ooalign{$\searrow$\cr$\nearrow$}}} x'y']$ as an induced subgraph (cf.\ Prop.~\ref{prop:binary-iff-subtree-colors}). The hourglass contains all possible arcs between vertices of different colors except $(x',y)$ and $(y',x)$. Since $(G',\sigma)$ contains no hourglass, and $G'$ is a completion of $G$, i.e., $E(G)\subseteq E(G')$, we conclude that $(G',\sigma)$ contains at least one of the arcs $(x',y)$ and $(y',x)$. Assume for contradiction that, w.l.o.g., $(G',\sigma)$ only contains $(x',y)$. We have $(y',x'),(y,x)\in E(G')$ and $\sigma(y')=\sigma(y)\ne\sigma(x')=\sigma(x)$ by the definition of hourglasses, and by assumption $(x',y)\in E(G')$ and $(y',x)\notin E(G')$. Hence, the four vertices $x,x',y,y'$ induce an F2-graph in $(G',\sigma)$. By Prop.~\ref{prop:forb-subgraph-charac}, the 2-colored subgraph of $(G',\sigma)$ induced by the two colors $\sigma(x)$ and $\sigma(y)$ is not a BMG. Consequently, $(G',\sigma)$ is not a BMG either; a contradiction. Hence, $(G',\sigma)$ contains both arcs $(x',y)$ and $(y',x)$. \end{proof} \begin{Definition} Let $(T,\sigma)$ be a tree with a 2-colored leaf set, i.e., $|\sigma(L(T))|=2$. Denote by $(T^*,\sigma)$ the \emph{collapsed tree} obtained from $(T,\sigma)$ by contraction of all inner edges in $T(u)$ for all $u\in V^0(T)$ that have support leaves of both colors. \end{Definition} In other words, $(T^*,\sigma)$ is obtained from $(T,\sigma)$ by collapsing every subtree $T(u)$ to a star if $u$ has support leaves of both colors. \begin{Lemma} The collapsed tree $(T^*,\sigma)$ of $(T,\sigma)$ is uniquely defined and can be computed from $(T,\sigma)$ in $O(|V(T)|)$-time. \label{lem:collaps} \end{Lemma} \begin{proof} The collapsed tree $(T^*,\sigma)$ is well-defined because whenever $v\prec_T u$, then collapsing the subtree $T(v)$ to a star does not change the set of support leaves $S_u$. Similarly, collapsing $T(v)$ if $v$ is not $\prec_T$-comparable with $u$ does not change $S_u$. Thus $(T^*,\sigma)$ is uniquely defined. To see that $(T^*,\sigma)$ can be computed in $O(|V(T)|)$ operations, we observe that it suffices to collapse all subtrees $T(u)$ such that $u\in V^0(T)$ has support leaves of both colors and there is no $u'\prec_{T}u$ with this property, i.e., $u$ is $\preceq_{T}$-maximal in that sense. These vertices $u$ for which $T(u)$ is replaced by a star are found by a top-down traversal of $T$ and evaluating $|\sigma(S_u)|$, all of which can be computed in linear total time. \end{proof} As an immediate consequence of the uniqueness of $T^*$ and the construction in the second part of the proof of Lemma~\ref{lem:collaps}, we obtain \begin{Corollary} The collapsed tree $(T^{**},\sigma)$ of a collapsed tree $(T^{*},\sigma)$ satisfies $T^{**}=T^{*}$. \end{Corollary} \begin{Lemma} If $(T^*,\sigma)$ is the collapsed tree of an LRT $(T,\sigma)$ with 2-colored leaf set, then $G(T^*,\sigma)$ is binary-explainable. \label{lem:T*be} \end{Lemma} \begin{proof} Since the collapsed tree $(T^*,\sigma)$ is obtained from the LRT $(T,\sigma)$ by contraction of edges, Thm.~\ref{thm:edge-contr-supergraph} implies that $(T^*,\sigma)$ is also least resolved. Now suppose, for contradiction, that $G(T^*,\sigma)$ is not binary-explainable. By, Prop.~\ref{prop:binary-iff-subtree-colors}(3), $(T^*,\sigma)$ has a vertex $u\in V^0(T^*)$ with three distinct children $v_1$, $v_2$, and $v_3$ and two distinct colors $r$ and $s$ satisfying (i) $r\in\sigma(L(T^*(v_1)))$, $r,s\in\sigma(L(T^*(v_2)))$, and $s\in\sigma(L(T^*(v_3)))$, and (ii) $s\notin\sigma(L(T^*(v_1)))$, and $r\notin\sigma(L(T^*(v_3)))$. Since $(G,\sigma)$ is only 2-colored, the latter arguments imply that $|\sigma(L(T^*(v_1)))|=|\sigma(L(T^*(v_3)))|=1$ and $|\sigma(L(T^*(v_2))|=2$. Since moreover $(T^*,\sigma)$ is least resolved and none of the vertices $v_1$, $v_2$, and $v_3$ is the root of $T^*$, we can apply Cor.~1 in \cite{Schaller:21x} to conclude that $v_1$ and $v_2$ are leaves, and that $v_3$ is an inner vertex, respectively. In particular, $\sigma(v_1)=r\ne s=\sigma(v_3)$. Hence, $T^*(u)$ is not a star tree and $u$ has support leaves of both colors in $T^*$; a contradiction to its construction. Therefore, we can apply Prop.~\ref{prop:binary-iff-subtree-colors} to conclude that $G(T^*,\sigma)$ is binary-explainable. \end{proof} \begin{Theorem} \label{thm:2BMG-CBEG-BMG-input} The optimization version of \PROBLEM{2-BMG CBEG} with a 2-BMG $(G,\sigma)$ as input has the unique solution $F\coloneqq E(G(T^*,\sigma))\setminus E(G)$, where $(T^*,\sigma)$ is the collapsed tree of the LRT $(T,\sigma)$ of $(G,\sigma)$. \end{Theorem} \begin{proof} First note that the optimization version of \PROBLEM{2-BMG CBEG} always has a solution. To see this, consider the complete bipartite and properly 2-colored graph $(G',\sigma)$ with vertex set $V(G)$. This graph is explained by the star tree with leaf set $V(G)$. Moreover, $(G',\sigma)$ is clearly hourglass-free since hourglasses require non-arcs (between vertices of distinct colors). By Prop.~\ref{prop:binary-iff-subtree-colors}, the BMG $(G',\sigma)$ is binary-explainable. Now consider the collapsed tree $(T^*,\sigma)$ of $(T,\sigma)$. Since $T^*$ is obtained from $T$ by contraction of inner edges, Prop.~\ref{prop:LRTuniq} implies $(G,\sigma)=G(T,\sigma)\subseteq G(T^*,\sigma)\eqqcolon(G^*,\sigma)$. Furthermore, $(G^*,\sigma)$ is binary-explainable by Lemma~\ref{lem:T*be}. Therefore, $(G^*,\sigma)$ is a valid completion of $(G,\sigma)$ to a beBMG. We continue by showing the existence of certain arcs in every (not necessarily optimal) completion $(G',\sigma)$ of $(G,\sigma)$ to a beBMG. To this end, consider a $\preceq_{T}$-maximal vertex $u$ such that the subtree $T(u)$ is not a star tree and $u$ has support leaves $S_u$ of both colors in $T$. We will make frequent use of the fact that $E(G)\subseteq E(G')$. We consider the following cases in order to show that all arcs between vertices $x, y\in L(T(u))$ with $\sigma(x)\ne\sigma(y)$ exist in $(G',\sigma)$: \begin{description} \item[(i)] $x,y\in S_u$, \item[(ii)] $x\in L(T(u))\setminus S_u$ and $y\in S_u$, and \item[(iii)] $x,y\in L(T(u))\setminus S_u$. \end{description} In Case~(i), the leaves $x$ and $y$ are both children of $u$. Together with Cor.~\ref{cor:reciprocal-iff-same-parent}, this implies $(x,y),(y,x)\in E(G)\subseteq E(G')$. In Case~(ii), we can find a vertex $x'\in S_u$ of color $\sigma(x)$ since $S_u$ contains vertices of both colors. As in Case~(i), we have $(x',y),(y,x')\in E(G)\subseteq E(G')$. Since $x\in L(T(u))\setminus S_u$, we can conclude that $v\coloneqq \mathsf{par}_T(x)\prec_T u$ by the definition of support leaves. Hence, the inner vertex $v$ is not the root of $T$ and we can apply Cor.~1 in \cite{Schaller:21x} to conclude that the subtree $T(v)$ of the inner vertex $v$ contains both colors. The latter together with Lemma~10 in \cite{Geiss:19b} implies that there are arcs $(x'',y''),(y'',x'')\in E(G)\subseteq E(G')$ with $x'',y''\in L(T(v))$ and $\sigma(x)=\sigma(x'')\ne \sigma(y)=\sigma(y'')$. Note that $x=x''$ is possible. Since $x,x'',y''$ in $L(T(v))\subset L(T(u))$, $x',y\in L(T(u))\setminus L(T(v))$ and $v\prec_T u$, we can apply Lemma~\ref{lem:2-BMG-outneighbors-subtree} to conclude that $(x',y''),(y,x),(y,x'')\in E(G)\subseteq E(G')$ and $(y'',x'),(x,y),(x'',y)\notin E(G)\subseteq E(G')$. Together with $(x',y),(y,x'),(x'',y''),(y'',x'')\in E(G)$ and the coloring, this implies that $x',y,x'',y''$ induce an hourglass $[x'y\mathrel{\text{\ooalign{$\searrow$\cr$\nearrow$}}} x''y'']$ in $(G,\sigma)$. By Lemma~\ref{lem:fill-houglass}, we have arcs $(x'',y),(y'',x')\in E(G')$. If $x=x''$, we immediately obtain $(x,y), (y,x)\in E(G')$. Now suppose $x\ne x''$, i.e., it remains to show that $(x,y)\in E(G')$. Thus assume, for contradiction, that $(x,y)\notin E(G')$. Lemma~\ref{lem:2-BMG-outneighbors-subtree} together with $\sigma(x)\ne\sigma(y'')$ and $y''\in L(T(\mathsf{par}_T(x)=v))$ implies that $(x,y'')\in E(G)\subseteq E(G')$. Hence, we have the arcs $(x,y''), (y'',x'), (x',y)\in E(G')$ but $(x,y)\notin E(G')$, i.e., $x,x',y,y''$ induce a forbidden F2-graph. Together with Prop.~\ref{prop:forb-subgraph-charac}, this is a contradiction to $(G',\sigma)$ being a 2-BMG. Therefore, we conclude that $(x,y)\in E(G')$. In Case~(iii), we have $x,y\in L(T(u))\setminus S_u$. We can find two vertices $x',y'\in S_u$, which are distinct from $x$ and $y$ and satisfy $\sigma(x)=\sigma(x')\ne\sigma(y)=\sigma(y')$. From Cases~(i) and~(ii), we obtain $(x',y'),(y',x')\in E(G')$ and $(x',y),(y,x'),(x,y'),(y',x)\in E(G')$, respectively. Now assume for contradiction that $(x,y)\notin E(G')$. Thus, we have $(x,y'),(y',x'),(x',y)\in E(G')$ and $(x,y)\notin E(G')$, i.e., $x,x',y,y'$ induce a forbidden F2-graph in $(G',\sigma)$; a contradiction to $(G',\sigma)$ being a 2-BMG. Hence, we conclude that $(x,y)\in E(G')$. The existence of the arc $(y,x)\in E(G')$ can be shown by analogous arguments. We will now show that $E(G^*)\subseteq E(G')$ for every (not necessarily optimal) completion $(G',\sigma)$ of the 2-BMG $(G,\sigma)$ to a beBMG. To this end, consider an arbitrary arc $(x,y)\in E(G^*)$. If $(x,y)\in E(G)$, then $(x,y)\in E(G')$ follows immediately. Now assume that $(x,y)\in F=E(G^*)\setminus E(G)$. Since $(G,\sigma)$ is a 2-BMG and thus properly-colored and sink-free (cf.\ Prop.~\ref{prop:forb-subgraph-charac}), there must be a vertex $y'$ of color $\sigma(y)$ such that $(x,y')\in E(G)$. Since $(x,y)\notin E(G)$, we have $\lca_T(x,y')\prec_T \lca_T(x,y)$ and thus the LRT $(T,\sigma)$ displays the triple $xy'|y$. However, $(x,y), (x,y')\in E(G^*)$ implies that $(T^*,\sigma)$ does not display the triple $xy'|y$, i.e., all edges on the path from $\lca_{T}(x,y')$ to $\lca_{T}(x,y)$ have been contracted. Therefore, there is a $\preceq_{T}$-maximal inner vertex $u\in V^0(T)$ such that $x,y\in L(T(u))$, $T(u)$ is not a star tree and $u$ has support leaves of both colors in $T$. By the arguments above, we can conclude that $(x,y)\in E(G')$. In summary, $F$ is a solution for \PROBLEM{2-BMG CBEG} with the 2-BMG $(G,\sigma)$ (and some integer $k\ge|F|$) as input, and $F\subseteq F'$ for every other solution $F'= E(G')\setminus E(G)$. Therefore, we conclude that $F$ is the unique optimal solution. \end{proof} As a direct cosequence of Thm.~\ref{thm:2BMG-CBEG-BMG-input}, the fact that LRTs can be constructed in $O(|V| + |E|\log^2 |V|)$ (cf.\ \cite{Schaller:21x}) and Lemma~\ref{lem:collaps}, we have \begin{Corollary} \PROBLEM{2-BMG CBEG} with a 2-BMG as input can be solved in $O(|V| + |E|\log^2 |V|)$ time. \end{Corollary} We also immediately obtain a characterization of the LRTs of 2-beBMGs. \begin{Corollary} A 2-colored least resolved tree $(T,\sigma)$ is the LRT of 2-beBMG if and only if it is a collapsed tree. \end{Corollary} \section{Concluding Remarks} Starting from the observation that the property of being least resolved is preserved under contraction of inner edges, we have obtained a characterization of the LRTs that explain 2-colored beBMGs. The construction of these ``collapsed trees'' corresponds to the completion of BMGs to beBMGs, resulting in a simple, polynomial-time algorithm for this problem. \begin{figure}[htb] \centering \includegraphics[width=0.85\textwidth]{./CBEG-3-colors.pdf} \caption{Example for \PROBLEM{3-BMG CBEG} with the 3-BMG $(G,\sigma)$ (explained by the LRT $(T,\sigma)$) as input that has no unique optimal solution. Insertion of the missing arcs $(a_2,b_1)$ and $(b_2,a_1)$ produces a graph that is not a BMG. At least one of the arcs $(c,a_1)$ or $(c,b_1)$ has to be inserted additionally to obtain the beBMGs $(G_1,\sigma)$ and $(G_2,\sigma)$ (shown with their LRTs $(T_1,\sigma)$ and $(T_2,\sigma)$), respectively.} \label{fig:CBEG-3-colors} \end{figure} In contrast to the 2-colored case, \PROBLEM{$\ell$-BMG CBEG} with a BMG as input and $\ell\ge 3$ in general does not have a unique optimal solution. In the example in Fig.~\ref{fig:CBEG-3-colors}, the missing arcs $(a_2,b_1)$ and $(b_2,a_1)$ in the induced hourglass $[a_1 b_1 \mathrel{\text{\ooalign{$\searrow$\cr$\nearrow$}}} a_2 b_2]$ must be inserted. The resulting graph is not a BMG. To obtain a BMG, it suffices to insert in addition either the arc $(c,a_1)$ or the arc $(c,b_1)$ to obtain a beBMG. (cf. Prop.~\ref{prop:binary-iff-subtree-colors}). The simple solution of \PROBLEM{$2$-BMG CBEG} begs the question whether other arc modification problems for beBMGs, in particular the corresponding deletion and editing problems, have a similar structure. This does not seem to be case, however. Neither \PROBLEM{$2$-BMG EBEG} nor \PROBLEM{$2$-BMG DBEG} with a $2$-BMG as input have a unique optimal solution. To see this, consider the 2-BMG consisting of the hourglass $[xy\mathrel{\text{\ooalign{$\searrow$\cr$\nearrow$}}} x'y']$ which is explained by the unique non-binary tree $(x,y,(x',y'))$ (in Newick format, see also Fig.~\ref{fig:forb-sg-and-hourglass.pdf}(A)). Deletion of the arcs $(x,y)$ or $(y,x)$ results in a graph that is explained by the binary trees $(y,(x,(x',y')))$ or $(x,(y,(x',y')))$, respectively. We suspect that a BMG as input does not make these problems easier than the general case -- the complexity of which remains an open questions, however. \paragraph{Author Contributions} Conceptualization, methodology, formal analysis, and writing, D.S., M.G., M.H., and P.F.S. All authors have read and agreed to the published version of the manuscript. \paragraph{Funding} This research was funded in part by the German Research Foundation (DFG), the Austrian Federal Ministries BMK and BMDW and the Province of Upper Austria in the frame of the COMET Programme managed by FFG. \paragraph{Conflicts of Interest} The authors declare no conflict of interest.
{'timestamp': '2021-03-12T02:23:48', 'yymm': '2103', 'arxiv_id': '2103.06665', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06665'}
arxiv
\subsubsection{\@startsection{subsubsection}{3}{\z@}% {-10\p@ \@plus -3\p@ \@minus -4\p@}% {2\p@ \@plus 2\p@ \@minus 2\p@}% {\normalfont\normalsize \rightskip=\z@ \@plus 8em\pretolerance=10000 }} \newcommand\footnoteref[1]{\protected@xdef\@thefnmark{\ref{#1}}\@footnotemark} \IEEEoverridecommandlockouts \title{Controlled Gaussian Process Dynamical Models with Application to Robotic Cloth Manipulation} \author{Fabio Amadio$^1$, Juan Antonio Delgado-Guerrero$^2$, Adrià Colomé$^2$, and Carme Torras$^2$ \thanks{\scriptsize This work was partially developed in the context of the project CLOTHILDE ("CLOTH manIpulation Learning from DEmonstrations"), which has received funding from the European Research Council (ERC) under the European Union’s Horizon 2020 research and innovation programme (Advanced Grant agreement No 741930). \thanks{$^1$Department of Information Engineering, Università di Padova, Italy {\tt\footnotesize [email protected]} } \thanks{$^2$Institut de Robòtica i Informàtica Industrial (IRI), CSIC-UPC, Spain {\tt\footnotesize [jdelgado, acolome, torras]@iri.upc.edu}} } \begin{document} \thispagestyle{empty} \pagestyle{empty} \maketitle \begin{abstract} Over the last years, robotic cloth manipulation has gained relevance within the research community. While significant advances have been made in robotic manipulation of rigid objects, the manipulation of non-rigid objects such as cloth garments is still a challenging problem. The uncertainty on how cloth behaves often requires the use of model-based approaches. However, cloth models have a very high dimensionality. Therefore, it is difficult to find a middle point between providing a manipulator with a dynamics model of cloth and working with a state space of tractable dimensionality. For this reason, most cloth manipulation approaches in literature perform static or quasi-static manipulation. In this paper, we propose a variation of Gaussian Process Dynamical Models (GPDMs) to model cloth dynamics in a low-dimensional manifold. GPDMs project a high-dimensional state space into a smaller dimension latent space which is capable of keeping the dynamic properties. Using such approach, we add control variables to the original formulation. In this way, it is possible to take into account the robot commands exerted on the cloth dynamics. We call this new version Controlled Gaussian Process Dynamical Model (CGPDM). Moreover, we propose an alternative parametric structure for the model, that is richer than the one employed in previous GPDM realizations. The modeling capacity of our proposal has been tested in both a simulated and a real scenario, where CGPDM proved to be capable of generalizing over a wide range of movements and correctly predicting the cloth motions obtained by previously unseen sequences of control actions. \end{abstract} \section{Introduction} Robotic cloth manipulation has a wide range of applications, from textile industry to assistive robotics \cite{laundryFolding2011Bersch, towelFolding2012Abbeel, lakshmanan2013constraint, DeformableSurvey, BenchmarkBimanual, GraspingCentered}. However, the complexity of cloth behaviour results in a high uncertainty in the state transition given a certain action. This uncertainty is what makes cloth manipulation much harder than manipulating rigid objects. Intuitively, learning the cloth's dynamics is the solution to reduce such uncertainty. In literature, we can find several cloth models that simulate the internal cloth state \cite{Cloth1,Cloth3,Cloth2}. They represent cloth as a mesh of material points, and simulate their behaviour taking into account physical constraints. However, fitting those models to real data can be a complex task. Moreover, such models need not only to behave similarly enough to the cloth garment, but to have a tractable dimension, for computational reasons. As an example, an $8\times 8$ mesh representing a square towel results in a $192$-dimensional manifold. Such dimensionality is unmanageable, not only in terms of computational costs, but also for building a tractable state-action space policy. Such is the case of \cite{MPCCloth}, where simulated results are obtained after hours of computations. Hence, Dimensionality Reduction (DR) methods are necessary. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{Figure/latent_mapping_final_v2.png} \caption{The same CGPDM predicts two distinct latent state trajectories in response to two different sequences of unseen control actions. Each point in the latent space has associated a particular configuration of the modeled cloth.} \label{fig: latent mapping} \end{figure} In \cite{ColomeTRO}, linear DR techniques were used for learning cloth manipulation by biasing the latent space projection with each execution's performance. Nonlinear methods, such as Gaussian Process Latent Variable Models (GPLVM) \cite{lawrence2005probabilistic} have also been applied for this purpose. In \cite{Koganti}, GPLVM was employed to project task-specific motor-skills of the robot onto a much smaller state representation, whereas in \cite{juananCovariate} GPLVM was also used to represent a robot manipulation policy in a latent space, taking contextual features into account. However, these approaches focus the dimensionality reduction in the robot action characterization, rather than in the manipulated object's dynamics. Instead, in \cite{koganti2017bayesian} the same DR technique was applied to learn a latent representation of the cloth state from point clouds taken by depth sensors. However, such approach did not consider the dynamics of the cloth handling task, and its applicability is limited to a quasi-static manipulation. In this paper, we assume to have recorded data from several cloth motions, as a time-varying mesh of points. This data will often come from the processed RGB-D data of a camera. To fit such data into a tractable dynamical model, we consider Gaussian Process Dynamical Models (GPDM), first introduced in \cite{wang2005gaussian}, which are an extension of the GPLVM structure explicitly oriented to the analysis of high-dimensional time series. GPDMs have been applied in several different fields, from human motion tracking \cite{wang2007gaussian, urtasun20063d} to dynamic texture modeling \cite{zhu2016dynamic}. In the context of cloth manipulation, GPDMs were adopted in \cite{koganti2015cloth} to learn a latent model of the dynamics of a cloth handling task. However, this framework, as it stands, lacks in its structure a fundamental component to correctly describe the dynamics of a system, namely control actions, limiting generalization capacity. Therefore, we propose here an extension of the GPDM structure, that takes into account the influence of external control actions on the modeled dynamics. We call it \textit{Controlled Gaussian Process Dynamical Models} (CGPDMs). In this new version, control actions directly affect the dynamics in the latent space. Thus, a CGPDM, trained on a sufficiently diverse set of interactions, is able to predict the effects of control actions never experienced before inside a space of reduced dimensions, and then reconstruct high-dimensional motions by projecting the latent state trajectories into the observation space. We tested the applicability of such solution in both a simulated and a real cloth manipulation scenario. CGPDM has proved capable of fitting different types of cloth movement, and predict the results of control actions never seen during training. As an example, in Fig. \ref{fig: latent mapping}, we show the trajectories predicted by the same CGPDM subject to two different sequences of control actions. Note how the two trajectories, starting from the same latent state, are driven into different regions of the latent space, where different cloth poses are reconstructed. Previous GPDM applications \cite{wang2005gaussian, wang2007gaussian, urtasun20063d} were based on Gaussian Processes (GPs) equipped with isotrophic squared exponential (SE) and homogeneous linear kernel functions. The limited number of hyper-parameters of such GPs could limit the generalization properties of the overall model. In this work, we study the effects that a richer parameterization could possibly have on prediction accuracy and generalization capabilities. In particular, we compare two distinct CGPDM implementations: (i) the \textit{lowly-parameterized} CGPDM is a direct extension of the standard GPDM's maps to the case of a controlled dynamical system; (ii) the \textit{highly-parameterized} CGPDM, instead, is characterized by the presence of a higher number of hyper-parameters. In the last case, we employed SE kernels with automatic relevance determination (ARD) \cite{neal2012bayesian} and inhomogeneous linear kernels, together with tunable scaling factors in the dynamical map. Despite these kernels are commonly used in GP regression, they have not yet been applied in the context of GPDM. In fact, to the best of our knowledge, only \cite{zhu2016dynamic} proposed to use kernels different from the naive ones adopted in the original implementation \cite{wang2005gaussian}, but it introduced a multi-kernel structure only for the GPs modeling the dynamics, without modifying the latent map. The remainder of the paper is structured as follows. Preliminaries are given in Sec. \ref{sec: Pre}. CGPDM framework is presented in Sec. \ref{sec: CGPDM}. Sec. \ref{sec: CGPDM learning and pred} treats its training and explains how to make predictions, in both latent and observation spaces. Experimental results on a simulated robotic cloth manipulation scenario are reported in Sec. \ref{sec: experiment}, while the application of CGPDM on a real setup is described in Sec. \ref{sec: real_experiment}. Sec. \ref{sec: conclusions} draws the conclusions. \section{Preliminaries: From GPs to GPDMs}\label{sec: Pre} GPs \cite{rasmussen2003gaussian} are the infinite-dimensional generalization of multivariate Gaussian distributions. They are defined as infinite-dimension stochastic processes such that, for any finite set of input locations $\mathbf{x}_1, ..., \mathbf{x}_n$, the random variables $f(\mathbf{x}_1), ..., f(\mathbf{x}_n)$ have joint Gaussian distributions. A GP is defined by its mean function $m(\mathbf{x})$ and kernel $k(\mathbf{x}, \mathbf{x}')$, that must be symmetric and positive semi-definite. Usually GPs are indicated as \begin{equation*} f(\mathbf{x}) \sim \mathcal{GP}(m(\mathbf{x}), k(\mathbf{x}, \mathbf{x}'))\text{.} \end{equation*} GPs can be used for regression models of the form $y = f(\mathbf{x}) + \varepsilon$, with $\varepsilon$ an i.i.d. Gaussian noise, as they provide closed formulae to predict new target $y^*$, given new input $\mathbf{x}^*$. GP regression has been widely applied as a data-driven tool for dynamical system identification \cite{kocijan2005dynamic}, usually describing each state by its own GP. Nevertheless, such approach is unfeasible when dealing with high-dimensional systems, due to the high computational demands. Thus, DR strategies must be included. GPLVMs \cite{lawrence2005probabilistic, GPLVMsurvey} emerged as feature extraction methods that can be used as multiple-output GP regression models. These models, under a DR perspective, associate and learn low-dimensional representations of higher-dimensional observed data, assuming that observed variables are determined by the latent ones. Finally, GPLVMs provide, as a result of an optimization, a mapping from the latent space to the observation space, together with a set of latent variables representing the observed values. However, GPLVMs are not explicitly thought to deal with data from time series, where observations at different time steps are connected by some form of dynamics. Thus, \cite{wang2005gaussian} first introduced Gaussian Process Dynamical Models (GPDM), an extension of the GPLVM structure explicitly oriented to the analysis of high-dimensional time series. A GPDM entails essentially two stages: (i) a latent mapping that projects high-dimensional observations to a low-dimensional latent space \eqref{eq:gpdm_base1}; (ii) a discrete-time Markovian dynamics that captures the evolution of the time series inside the reduced latent space \eqref{eq:gpdm_base2}. GPs are used to model both the latent map, as in GPLVMs, and the undergoing dynamics transition function. GPDMs are then defined by \begin{equation}\label{eq:gpdm_base1} \boldsymbol{y}_t = g(\boldsymbol{x}_t) + \boldsymbol{n}_{y,t}\text{,} \end{equation} \begin{equation}\label{eq:gpdm_base2} \boldsymbol{x}_{t+1} = h(\boldsymbol{x}_t) + \boldsymbol{n}_{x,t}\text{,} \end{equation} where $\boldsymbol{y}_t$ is the high-dimensional observation vector and $\boldsymbol{x}_t$ represents the latent state, at time step $t$. Here, $\boldsymbol{n}_{y,t}$ and $\boldsymbol{n}_{x,t}$ are two zero-mean isotropic white Gaussian noise processes, while $g$ and $h$ are two unknown functions. \section{Controlled GPDM}\label{sec: CGPDM} Let us consider a system governed by an unknown dynamics. At each time step $t$, it is possible to influence it by applying control actions $\boldsymbol{u}_t \in \mathbb{R}^E$ and getting an observation $\boldsymbol{y}_t \in \mathbb{R}^D$. For high-dimensional observation spaces, it could be unfeasible to directly model the evolution of a sequence of observations in response to a series of inputs. For instance, in the case of a robot moving a piece of cloth, we can consider as control actions $\boldsymbol{u}_t$ the instantaneous movement of the end-effector, while the observations $\boldsymbol{y}_t$ could be the coordinates of a mesh of material points, representing the cloth configuration. In this context, it could be convenient to capture the dynamics of the system in a low-dimensional latent space $\mathbb{R}^d$, with $d<<D$. Let $\boldsymbol{x}_t \in \mathbb{R}^d$ be the latent state associated with $\boldsymbol{y}_t$. We propose to use a variation of the GPDM that keeps into account the influence of control actions, while maintaining the dimensionality reduction properties of the original model. We call it \textit{Controlled Gaussian Process Dynamical Model} (CGPDM). A CGPDM consists of a latent map \eqref{eq: latent mapping} projecting observations $\boldsymbol{y}_t$ into latent states $\boldsymbol{x}_t$, and a dynamics map \eqref{eq: markov dynamics} that describes the evolution of the latent state $\boldsymbol{x}_t$, subject to $\boldsymbol{u}_t$. \begin{equation}\label{eq: latent mapping} \boldsymbol{y}_t = g(\boldsymbol{x}_t) + \boldsymbol{n}_{y,t}\text{,} \end{equation} \begin{equation}\label{eq: markov dynamics} \boldsymbol{x}_{t+1} - \boldsymbol{x}_t = h(\boldsymbol{x}_t, \boldsymbol{u}_t) + \boldsymbol{n}_{x,t}\text{.} \end{equation} Differently from original GPDM \eqref{eq:gpdm_base2}, control actions have influence on the CGPDM transition function \eqref{eq: markov dynamics}. On the other hand, latent map \eqref{eq: latent mapping} is identical to \eqref{eq:gpdm_base1} because control actions should not affect the dimensionality reduction process. Note that we consider $\boldsymbol{x}_{t+1} - \boldsymbol{x}_t$ to be the output of the CGPDM dynamic map, \cite{wang2007gaussian} suggested that this choice can help to improve the smoothness of latent trajectories. In the following, we report how to model \eqref{eq: latent mapping} and \eqref{eq: markov dynamics} by means of GPs. \subsection{Latent variable mapping}\label{sec: latent map} Each component of the observation vector $\boldsymbol{y}_t = [y_t^{(1)}, \dots, y_t^{(D)}]^T$ can be modeled a priori as a zero-mean GP that takes as input $\boldsymbol{x}_t$, for $t=1,\dots,N$. Let $Y = [ \boldsymbol{y}_1,\dots, \boldsymbol{y}_N]^T \in \mathbb{R}^{N \times D}$ be the matrix that collects the set of $N$ observations, and $X = [ \boldsymbol{x}_1,\dots, \boldsymbol{x}_N]^T \in \mathbb{R}^{N \times d}$ be the matrix of associated latent states. We denote with $Y_{:,j}$ the vector containing the $j$-th components of all the $N$ observations. Then, if we assume that the $D$ observation components are independent variables, the probability over the whole set of observations can be expressed by the product of the $D$ GPs. In addition, if we choose the same kernel function $k_y(\cdot,\cdot)$ for each GP, differentiated only through a variable scaling factor $w_{y,j}^{-2}$, with $j=1,\dots,D$, the joint likelihood over the whole set of observations is given by \begin{equation}\label{eq: latent simplified density} p(Y| X) =\frac{|W_y|^N \text{exp}\left( -\frac{1}{2} \text{tr}\left(\left(K_y(X)\right)^{-1} Y W_y^2 Y^T\right)\right)}{\sqrt{(2\pi)^{ND} |K_y(X)|^D}}\text{,} \end{equation} where $W_y=\text{diag}(w_{y,1},\dots, w_{y,D})$, $K_y(X)$ is the covariance matrix defined element-wise by $k_y(\cdot,\cdot)$. Independence assumption may be relaxed by applying, for instance, coregionalization models \cite{vectorKernels}, at the cost of greater computational demands. In previous works on GPDMs \cite{wang2005gaussian, wang2007gaussian, urtasun20063d}, the GPs of the latent map were equipped with an isotrophic SE kernel, \begin{equation}\label{eq: old y kernel} k_y'(\boldsymbol{x}_r, \boldsymbol{x}_s) = \text{exp}\left(-\frac{\beta_1}{2}||\boldsymbol{x}_r-\boldsymbol{x}_s||^2\right) +\beta_2^{-1} \delta(\boldsymbol{x}_r,\boldsymbol{x}_s)\text{,} \end{equation} with parameters $\beta_1$ and $\beta_2$ ($\delta(\boldsymbol{x}_r,\boldsymbol{x}_s)$ is the Kronecker delta). Instead here, we adopt the richer ARD structure for the SE kernel, characterized by the presence of length-scales that can weight differently each component of the latent state: \begin{equation}\label{eq: my y kernel} k_y(\boldsymbol{x}_r, \boldsymbol{x}_s) = \text{exp}\left(-||\boldsymbol{x}_r-\boldsymbol{x}_s||_{\Lambda_y^{-1}}\right) +\sigma_y^2 \delta(\boldsymbol{x}_r,\boldsymbol{x}_s)\text{.} \end{equation} $\Lambda_y^{-1} = \text{diag}(\lambda_{y,1}^{-2},\dots,\lambda_{y,D}^{-2})$ is a positive definite diagonal matrix, which weights the norm used in the SE function, and $\sigma_y^2$ is the variance of the isotropic noise in \eqref{eq: latent mapping}. The trainable hyper-parameters of the latent map model are then $\theta_y = \{w_{y,1},\dots, w_{y,D}, \lambda_{y,1},\dots,\lambda_{y,D}, \sigma_y\}$. \subsection{Dynamics mapping}\label{sec: dynamic map} Similarly to Sec. \ref{sec: latent map}, we can model a priori each component of the latent state difference $\boldsymbol{x}_{t+1}-\boldsymbol{x}_t = [x_{t+1}^{(1)}-x_t^{(1)}, \dots, x_{t+1}^{(d)}-x_t^{(d)} ]^T$ as a zero-mean GP that takes as input the pair $(\boldsymbol{x}_t,\boldsymbol{u}_t)$, for $t=1,\dots,N-1$. Let $X = [ \boldsymbol{x}_1,\dots, \boldsymbol{x}_N]^T \in \mathbb{R}^{N\times d}$ be the matrix collecting the set of $N$ latent states, we can denote by $X_{r:s,i}$ the vector of the $i$-th components from time step $r$ to time step $s$, with $r,s=1,\dots,N$. We indicate the vector of differences between consecutive latent states along their $i$-th component with $\Delta_{:,i} = (X_{2:N,i} - X_{1:N-1,i})\in \mathbb{R}^{N-1}$. $\Delta = [\Delta_{:,1},\dots,\Delta_{:,d} ]\in \mathbb{R}^{(N-1)\times d}$ is the matrix that collects differences along all the components. Finally, we compactly represent the GP input of the dynamic model as $\tilde{\boldsymbol{x}}_t = [\boldsymbol{x}_t^T, \boldsymbol{u}_t^T]^T \in \mathbb{R}^{d+E}$, and refer to the the matrix collecting $\tilde{\boldsymbol{x}}_t$ for $t=1,\dots,N-1$ with $\tilde{X} = \left[ \tilde{\boldsymbol{x}}_1,\dots, \tilde{\boldsymbol{x}}_{N-1}\right]^T \in\mathbb{R}^{(N-1) \times (d+E)}$. With similar assumptions to the ones made for the latent map, and denoting the common kernel function for all the GPs with $k_x$, and the different scaling factors with $w_{x,1}$, for $i=1,\dots,d$, the joint likelihood is given by \begin{equation}\label{eq: dynamic simplified density} p(\Delta|\tilde{X}) =\frac{|W_x|^{N-1} \text{exp}\left( -\frac{1}{2} \text{tr}\left(\left(K_x(\tilde{X})\right)^{-1} \Delta W_x^2 \Delta^T\right)\right)}{\sqrt{(2\pi)^{(N-1)d} |K_x(\tilde{X})|^d}}\text{,} \end{equation} where $W_x=\text{diag}(w_{x,1},\dots,w_{x,d})$ and $K_x(\tilde{X})$ is the covariance matrix defined element-wise by $k_x(\cdot,\cdot)$. In standard GPDM \cite{wang2005gaussian}, dynamic mapping GPs have been proposed with constant scaling factors $w_{x,i}=1$ for $i=1,\dots,d$, and equipped with the simple kernel resulting from the sum of an isotrophic SE and an homogeneous linear function, characterized only by four trainable parameters: \begin{equation}\label{eq: old x kernel} k_x'(\tilde{\boldsymbol{x}}_r, \tilde{\boldsymbol{x}}_s) = \alpha_1\text{exp}\left(-\frac{\alpha_2}{2}||\tilde{\boldsymbol{x}}_r-\tilde{\boldsymbol{x}}_s||^2\right)+\dots \end{equation} \begin{equation*} \dots+ \alpha_3 \tilde{\boldsymbol{x}}_r^T\tilde{\boldsymbol{x}}_s + \alpha_4^{-1} \delta(\tilde{\boldsymbol{x}}_r,\tilde{\boldsymbol{x}}_s)\text{.} \end{equation*} Analogously to the latent mapping, we decided to adopt a more complex kernel function, detailed in the following, \begin{equation}\label{eq: my x kernel} k_x(\tilde{\boldsymbol{x}}_r, \tilde{\boldsymbol{x}}_s) = \text{exp}\left(-||\tilde{\boldsymbol{x}}_r-\tilde{\boldsymbol{x}}_s||_{\Lambda_{x}^{-1}}\right) +\dots \end{equation} \begin{equation*} \dots + [\tilde{\boldsymbol{x}}_r^T, 1]\Phi [\tilde{\boldsymbol{x}}_s^T 1]^T + \sigma_x^2\delta(\tilde{\boldsymbol{x}}_r,\tilde{\boldsymbol{x}}_s) \text{.} \end{equation*} $\Lambda_{x}^{-1} = \text{diag}(\lambda_{x,1}^{-2},\dots,\lambda_{x,d+E}^{-2})$ is a positive definite diagonal matrix, which weights the norm used in the SE component of the kernel. Also $\Phi = \text{diag}(\phi_{1}^2,\dots,\phi_{d+E+1}^2) $ is a positive definite diagonal matrix that describes the linear component. $\sigma_x^2$ is the variance of the isotropic noise in \eqref{eq: markov dynamics}. In comparison to \eqref{eq: old x kernel}, the adopted kernel weights differently the various components of the input in both SE and linear part, where the GP input is also extended as $[\tilde{\boldsymbol{x}}_s^T, 1]^T$. The trainable hyper-parameters of the dynamic map model are then $\theta_x = \{w_{x,1},\dots, w_{x,d}, \lambda_{x,1},\dots,\lambda_{x,d}, \phi_{1},\dots,\phi_{d+E+1}, \sigma_x\}$. In the following we will refer to the proposed CGPDM structure with kernels \eqref{eq: my y kernel} and \eqref{eq: my x kernel}, and trainable scaling factors in the dynamical map, as \textit{highly-parameterized} CGPDM. On the contrary, \textit{lowly-parameterized} CGPDM will indicate the version that straightforwardly extends the standard GPDM structure from \cite{wang2005gaussian}, using its same kernels, \eqref{eq: old y kernel} and \eqref{eq: old x kernel}, and constant scaling factors. Although kernels such \eqref{eq: my y kernel} and \eqref{eq: my x kernel} are commonly adopted in GP regression literature \cite{rasmussen2003gaussian}, to the best of our knowledge, they have not been tested before in the context of GPDM. Furthermore, also the adoption of trainable scaling factors constitutes a novelty for this kind of models. \section{CGPDM Training and Predictions}\label{sec: CGPDM learning and pred} Training the CGPDM entails using numerical optimization techniques to estimate the unknowns in the model, i.e., latent states $X$ and the hyper-parameters $\theta_x,\theta_y$. Latent coordinates $X$ are initialized by means of PCA \cite{bishop2006pattern}, selecting the first $d$ principal components of $Y$. A natural approach for training CGPDMs is to maximize the joint log-likelihood $\text{ln}\; p(Y|X) +\text{ln}\; p(\Delta|\tilde{X})$ w.r.t. $\{X, \theta_x,\theta_y\}$. As regards numerical optimization, we used the L-BFGS algorithm \cite{byrd1995limited}. Hence, the overall loss will be given by \begin{equation}\label{eq: loss} \mathcal{L} = \mathcal{L}_y+ \mathcal{L}_x\text{,} \end{equation} where \begin{equation*} \mathcal{L}_y = \frac{D}{2}\text{ln}|K_y(X)| + \frac{1}{2}\text{tr}(K_y(X)^{-1}Y W_y^2 Y^T)-N \text{ln} |W_y|\text{,} \end{equation*} \begin{equation*} \mathcal{L}_x = \frac{d}{2}\text{ln}|K_x(\tilde{X})| + \frac{1}{2}\text{tr}(K_x(\tilde{X})^{-1} \Delta W_x^2 \Delta^T)-(N-1) \text{ln} |W_x|\text{.} \end{equation*} A trained CGPDM can be used to fulfill two different purposes: (i) map a given new latent state $\boldsymbol{x}_t^*$ to the corresponding $\boldsymbol{y}_t^*$ in observation space, (ii) predict the evolution of the latent state at the next time step $\boldsymbol{x}_{t+1}^*$, given $\boldsymbol{x}_{t}^*$ and a certain control $\boldsymbol{u}_{t}^*$. The two processes, together, can predict the observations produced by a given series of control actions. \subsection{Latent prediction}\label{sec: latent pred} Given $\boldsymbol{x}_t^*$, its corresponding observation $\boldsymbol{y}_t^*$ is distributed as $p(\boldsymbol{y}_t^*|\boldsymbol{x}_t^*, X, \theta_y) = \mathcal{N}(\mu_y(\boldsymbol{x}_t^*),v_y(\boldsymbol{x}_t^*)W_y^{-2})$, with \begin{equation*} \mu_y(\boldsymbol{x}_t^*) = Y^T K_y(X)^{-1} \boldsymbol{k}_y(\boldsymbol{x}_t^*,X) \end{equation*} \begin{equation*} v_y(\boldsymbol{x}_t^*) = k_y(\boldsymbol{x}_t^*,\boldsymbol{x}_t^*) - \boldsymbol{k}_y(\boldsymbol{x}_t^*,X)^T K_y(X)^{-1} \boldsymbol{k}_y(\boldsymbol{x}_t^*,X) \text{,} \end{equation*} where $\boldsymbol{k}_y(\boldsymbol{x}_t^*,X) = \left[k_y(\boldsymbol{x}_t^*,\boldsymbol{x}_1),\dots, k_y(\boldsymbol{x}_t^*,\boldsymbol{x}_N)\right]^T$. \subsection{Dynamics prediction}\label{sec: dyn pred} Given $\boldsymbol{x}_t^*$ and $\boldsymbol{u}_t^*$, let's define $\tilde{\boldsymbol{x}}_t^*=[\boldsymbol{x}_t^{*T},\boldsymbol{u}_t^{*T}]^T$. The probability density of the latent state at the next time step $\boldsymbol{x}_{t+1}^*$ is $p(\boldsymbol{x}_{t+1}^*|\tilde{\boldsymbol{x}}_t, X, \theta_x) = \mathcal{N}(\mu_x(\boldsymbol{x}_t^*),v_x(\boldsymbol{x}_t^*)W_x^{-2})$, with \begin{equation*} \mu_x(\boldsymbol{x}_t^*) = \boldsymbol{x}_t^* + {\Delta}^T K_x(\tilde{X})^{-1} \boldsymbol{k}_x(\tilde{\boldsymbol{x}}_t^*,\tilde{X})\text{,} \end{equation*} \begin{equation*} v_x(\boldsymbol{x}_t^*) = k_x(\tilde{\boldsymbol{x}}_t^*,\tilde{\boldsymbol{x}}_t^*) - \boldsymbol{k}_x(\tilde{\boldsymbol{x}}_t^*,\tilde{X})^T K_x(\tilde{X})^{-1} \boldsymbol{k}_x(\tilde{\boldsymbol{x}}_t^*,\tilde{X})\text{,} \end{equation*} where $\boldsymbol{k}_x(\tilde{\boldsymbol{x}}_t^*,\tilde{X}) = \left[k_x(\tilde{\boldsymbol{x}}_t^*,\tilde{\boldsymbol{x}}_1),\dots, k_x(\tilde{\boldsymbol{x}}_t^*,\tilde{\boldsymbol{x}}_{N-1})\right]^T$. \subsection{Trajectory prediction}\label{sec: trajectory prediction} Starting from an initial latent state $\boldsymbol{x}_1^*$, one can predict the evolution of the system over a desired horizon of length $N_d$, when subject to a given sequence of control actions $\boldsymbol{u}_1^*,\dots,\boldsymbol{u}_{N_d-1}^*$. At each time step $t=1,\dots,N_d-1$, $\boldsymbol{x}_{t+1}^*$ can be sampled from the normal distribution $p(\boldsymbol{x}_{t+1}^*|\tilde{\boldsymbol{x}}_t, X, \theta_x)$ defined in Sec. \ref{sec: dyn pred}. Hence, the generated trajectory in the latent space $\boldsymbol{x}_1^*,\dots,\boldsymbol{x}_{N_d}^*$ can be mapped into the associated predicted sequences of observations $\boldsymbol{y}_1^*,\dots,\boldsymbol{y}_{N_d}^*$ by mean of $p(\boldsymbol{y}_t^*|\boldsymbol{x}_t^*, X, \theta_y)$, defined in Sec. \ref{sec: latent pred}. \section{Experiment with Simulated Cloth}\label{sec: experiment} \begin{figure}[t] \centering \includegraphics[trim=0cm 0.5cm 0cm 0.5cm, width=0.65\linewidth]{Figure/first_frame_v3.png} \caption{Simulated setup for cloth manipulation with bimanual robot. The cloth is positioned in its starting configuration.} \label{fig: robot picture} \end{figure} Initially, we validated CGPDM in a simulated scenario, consisting of a bimanual robot that moves a piece of cloth by holding its two upper corners. The cloth is modeled as an 8$\times$8 mesh of material points. The two points in the upper corners are assumed to be attached to the two robot's end-effectors, while the other points move following the dynamical model proposed in \cite{francoModel}. In this context, the observation vector is given by the Cartesian coordinates of all the points in the mesh (measured in meters); hence $\boldsymbol{y}_t\in\mathbb{R}^D$ with $D=192$. We assume that the two end-effectors can be controlled exactly in the operational space. In this system, the controls acting at time step $t$ are the differences between position commands at instant $t+1$ and $t$ (measured in meters); so $\boldsymbol{u}_t\in\mathbb{R}^E$ with $E=6$. The overall setup is shown in Fig. \ref{fig: robot picture}. The objective of the experiment is to learn the high-dimensional cloth dynamics using CGPDM, in order to make predictions about cloth movements in response to sequences of actions that were not seen during training. We adopted a latent space of dimension $d=3$, resulting in a dimensionality reduction factor of $D/d=64$. Such high-dimensional task would be unfeasible to model by standard GP regression without DR. CGPDMs was implemented in Python\footnote[1]{Code publicly available at \url{https://bitbucket.org/fabio_ama/gpdm_lib}.}, employing PyTorch library \cite{paszke2019pytorch}. We aim to evaluate how prediction accuracy is affected by \begin{itemize} \item the number of observation sequences used for training, \item the range of the cloth movements, \item the use of \textit{lowly} or \textit{highly} CGPDM (defined in Sec. \ref{sec: CGPDM}). \end{itemize} \subsection{Data collection} Data were obtained by recording mesh trajectories associated with several types of cloth oscillation, obtained by applying different sequences of control actions. All the considered trajectories start from the same cloth configuration and last 5 seconds. Observations were recorded at 20 Hz, hence $N=100$ total number of steps for each sequence. Let $\boldsymbol{u}_t = \left[^r\delta^X_t, ^r\delta^Y_t, ^r\delta^Z_t,^l\delta^X_t, ^l\delta^Y_t, ^l\delta^Z_t\right]^T$, where $^r\delta^X_t$, $^r\delta^Y_t$ and $^r\delta^Z_t$ ($^l\delta^X_t$, $^l\delta^Y_t$ and $ ^l\delta^Z_t$) indicate the displacement of the right (left) end-effector position along the three Cartesian axes, between step $t$ and $t+1$. Specifically, we used the same commands for both end-effectors. Denoting with $\left(\delta^X_t, \delta^Y_t, \delta^Z_t\right)$ the common displacements, the applied $\boldsymbol{u}_t$ were given by, \begin{equation} \label{eq: oscillation control} \begin{array}{rl} \delta^X_t = 0,\; \delta^{[Y,Z]}_t=A\cdot \textrm{cos}(2\pi f_Y t) \left[-\textrm{cos}(\gamma),\textrm{sin}(\gamma)\right] \end{array} \end{equation} \iffalse Thus, the applied $\boldsymbol{u}_t$ were such that, \begin{subequations}\label{eq: oscillation control} \begin{align} & ^r\delta^X_t = 0\\ & ^r\delta^Y_t = -0.01\;cos(\gamma)\;cos(2\pi f_Y \;t)\\ & ^r\delta^Z_t = 0.01\;sin(\gamma)\;cos(2\pi f_Z \;t)\\ & ^l\delta^X_t = 0 \\ & ^l\delta^Y_t = -0.01\;cos(\gamma)\;cos(2\pi f_Y \;t)\\ & ^l\delta^Z_t = 0.01\;sin(\gamma)\;cos(2\pi f_Z \;t)\text{.} \end{align} \end{subequations} \fi Such controls make the end-effectors oscillate on the Y-Z plane of the operational space. The maximum displacement is regulated by $A$, that we set to 0.01 meters. Parameter $\gamma$ can be interpreted as the inclination of $\boldsymbol{u}_1$ w.r.t. the horizontal, and it loosely defines a direction of the oscillation. $f_Y$ and $f_Z$ define the frequencies of the oscillations along Y and Z axes. If they are similar, the end-effectors move mostly along the direction defined by $\gamma$, if not, they swipe in a broader space. In order to obtain a heterogeneous set of trajectories for the composition of training and test sets, we collected several movements obtained by choosing in a random fashion the control parameters $\gamma$, $f_Y$ and $f_Z$. Angles $\gamma$ were uniformly sampled inside a variable range $[-\frac{R}{2},\frac{R}{2}]$ (deg); in the following, we indicate this range with the amplitude of its angular area, $R$ (deg). Instead, frequencies $f_Y$ and $f_Z$ were uniformly sampled inside the fixed interval [0.3, 0.6] (Hz). \begin{figure}[t] \centering \includegraphics[trim=0cm 1cm 0cm 0.5cm, width=0.75\linewidth]{Figure/angle_ranges_v4.png} \caption{Representation of the movement ranges within which control parameter $\gamma$ was sampled during data collection.} \label{fig: ranges} \end{figure} We considered four movement ranges of increasing size, namely $R\in\{30\text{°},60\text{°},90\text{°},120\text{°}\}$ (see Figure \ref{fig: ranges}), and collected a specific data-set $\mathcal{D}_R$ associated with each range. Every set contains 50 cloth trajectories obtained by applying control actions of the form \eqref{eq: oscillation control} with 50 different random choices for parameters $\gamma$, $f_Y$ and $f_Z$. From each $\mathcal{D}_R$, 10 trajectories were extracted and used as test sets $\mathcal{D}_R^{test}$ for the corresponding movement range, while several training sets $\mathcal{D}_R^{train}$ were built by randomly picking from the remaining sequences. \subsection{Model training}\label{sec:training_models} The objective of the experiment is to evaluate CGPDM prediction accuracy in different movement ranges, and for different amounts of training data. Also, we want to observe if the use of \textit{lowly-parameterized} or \textit{highly-parameterized} CGPDMs yield a substantial difference in terms of accuracy. Consequently, for each considered movement range $R$, we trained different \textit{highly-parameterized} CGPDMs employing an increasing number of sequences randomly picked from $\mathcal{D}_R^{train}$. Specifically, we used 10 different combinations of 5, 10, 15 and 20 sequences for each range. In this way, we were able to reduce the dependencies on the specific training trajectories employed, and to average prediction accuracy over different possible sets of training data. For each such model, a \textit{lowly-parameterized} CGPDM was trained on exactly the same data. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{Figure/plot_distances.pdf} \caption{Average distances (with 95\% C.I.) between true and predicted mesh points obtained by different CGPDM setups.} \label{fig: table} \end{figure} \subsection{Results}\label{sec: sim_exp_results} We used each learned CGPDM to predict the cloth movements when subject to the test control actions relative to the associated $\mathcal{D}_R^{test}$, for $R\in\{30\text{°},60\text{°},90\text{°},120\text{°}\}$. Let $\boldsymbol{y}_t^{(R,k)}$ and $\boldsymbol{u}_t^{(R,k)}$ denote the observation and control action, at time step $t$, of the $k$-th test trajectory in $\mathcal{D}_R^{test}$, with $k=1,\dots,10$. For every considered range $R$, one can follow the procedure described in Sec. \ref{sec: trajectory prediction} and employ the trained CGPDMs to predict the trajectories resulting from the application of control action sequences $\{\boldsymbol{u}_t^{(R,k)}\}_{t=1}^{N-1}$, for $k=1,\dots,10$. Let $\boldsymbol{x}_t^{*(R,k)}$ be the predicted latent state at time $t$, and $\boldsymbol{y}_t^{*(R,k)}$ the corresponding predicted observation. By visualization of the predicted movements\footnote[2]{\label{note1}Video of the experiments available at \url{https://youtu.be/vUO_3nYgMeg}.}, we can state that CGPDMs, trained with a sufficient amount of data (10, 15 and 20 sequences in this example), are able to capture the cloth dynamics of oscillations along axes Y and Z. Such models obtained satisfying results in a variety of movement ranges. In fact, for smaller movement ranges ($R=30$° or $R=60$°), the reconstructed trajectories of the mesh of points appear very similar to the true ones. On the other hand, for wider ranges ($R=90$° or $R=120$°), discrepancies between true and predicted points begin to be more evident, but the CGPDMs are still able to describe the overall movement of the cloth. In Figure \ref{fig: table}, we report, for all the movement ranges, the mean distances between true and predicted mesh points obtained in the test sets by the different CGPDM setups. Results are expressed in terms of mean and 95\% confidence intervals obtained by averaging over the different training sets adopted (as indicated in Section \ref{sec:training_models}, we repeated all the experiments 10 times, using a $\mathcal{D}_R^{train}$ of random composition every turn). \iffalse Denote with $P$ the total number of mesh points (in our case $P=64$) and let us indicate the Cartesian coordinates of the $p$-th mesh point at time step $t$ as $[x_t^p, y_t^p, z_t^p]$. Then, for each range $R$, it is possible to rewrite the true observation from the $k$-th test trajectory at time step $t$, as $\boldsymbol{y}_t^{(R,k)} = [x_t^1,\dots,x_t^P,y_t^1,\dots,y_t^P,z_t^1,\dots,z_t^P]^T $. Analogously, $\boldsymbol{y}_t^{*(R,k)}$ can be rewritten as $\boldsymbol{y}_t^{*(R,k)} = [x_t^{1*},\dots,x_t^{P*},y_t^{1*},\dots,y_t^{P*},z_t^{1*},\dots,z_t^{P*}]^T $. Following this notation, for each angular range $R\in\{30\text{°},60\text{°},90\text{°},120\text{°}\}$ and every test trajectory $k=1,\dots,10$, we can define the prediction error $e^{(R,k)}$ as the average distances between the true mesh points and the predicted ones, namely \begin{equation}\label{eq: error} e^{(R,k)} = \frac{1}{N} \sum_{t=1}^N \frac{1}{P} \frac{1}{P} \sum_{p=1}^P d^{(R,k)} \text{,} \end{equation} \begin{equation*} \text{with} \quad d^{(R,k)}=\sqrt{(x_t^p-x_t^{p*})^2 + (y_t^p-y_t^{p*})^2 + (z_t^p-z_t^{p*})^2} \end{equation*} In Figure \ref{fig: table}, we report, for all the movement ranges, the mean prediction errors \eqref{eq: error} obtained in the test sets by CGPDMs, averaging the results over the different training sets adopted (as indicated in Section \ref{sec:training_models}, we repeated all the experiments 10 times, using a $\mathcal{D}_R^{train}$ of random composition every turn). Results are indicated with mean and 95\% confidence interval. \fi As it was natural to expect, CGPDMs trained with only 5 sequences show higher errors than the models trained employing more data. But the resulting errors do not always diminish with the increase in the amount of training trajectories. In fact, in all the considered movement ranges, accuracy does not considerably change passing from 15 training sequences to 20. Moreover, the proposed \textit{highly-parameterized} CGPDM structure seems able to improve accuracy and consistency of the results in the majority of cases. This effect is clearer in a low-data regime, with models trained on 5 or 10 sequences. \section{Experiment with Real Cloth}\label{sec: real_experiment} Finally, we tested CGPDM on data collected in a real cloth manipulation experiment. For this purpose, we used a Barrett WAM Arm, whose end-effector consists of a coat rack that can firmly grip a piece of cloth from its corners. The overall setup is depicted in Fig. \ref{fig: real_setup}. The task considered is totally analogous to the one simulated in Sec. \ref{sec: experiment}, despite having here only a single robot involved. We controlled robot's end-effector in position, recording the resulting movement of the cloth through a motion capture system. We combined object detection, image and point cloud processing for segmenting cloth-like objects. The implementation\footnote[3]{Code: \url{https://github.com/MiguelARD/cloth_point_cloud_segmentation}} is based on \cite{bochkovskiy2020yolov4}, \cite{GrabCut} and \cite{colorSegmentation}. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{Figure/real_rollout.pdf} \caption{True and predicted corners for a real cloth movement.} \label{fig: real rollout} \end{figure} \subsection{Data Collection} As before, we captured the cloth as a 8$\times$8 mesh of points, whose coordinates constitute the observation vector $\boldsymbol{y}_t\in\mathbb{R}^D$ with $D=192$. While the mesh size can be changed, its sensitivity analysis is left out of the scope of this paper. As control actions, we considered the difference between consecutive position commands (with fixed orientation); hence $\boldsymbol{u}_t\in\mathbb{R}^E$ with $E=3$. Robot was controlled at 100 Hz, with commands chosen following \eqref{eq: oscillation control}. \begin{wrapfigure}{r}{0.58\linewidth} \centering \includegraphics[width=\linewidth]{Figure/robot_cloth_setup_3_crop.jpeg} \caption{\small \textit{Real experimental setup.}} \label{fig: real_setup} \end{wrapfigure} In this case, $f_Y$ and $f_Z$ have been uniformly sampled in [0.2, 0.5] (Hz) and A was reduced to 0.004 meters, due to the higher control frequency. On the other hand, the motion capture system could work only at lower rates, with no guarantees on the sampling interval. Thus, it was necessary to post-process the data to make them ready for modeling. Firstly, motion capture data were smoothed by a moving average filter. Then we interpolated the positions of both the end-effector and the cloth mesh, to obtain two synchronized sequences of observations and control actions, sampled at 20 Hz. We collected 20 different 3 second long trajectories for each of the two ranges, $R=30$° and $R=60$° (40 sequences in total). \subsection{Model training \& Results} We trained two CGPDMs model, one for $R=30$° and the other for $R=60$°. We adopted the \textit{highly-parameterized} structure, as it performed better in the simulated experiment. For each $R$, the CGPDM was trained using ten trajectories, while the others were set aside for testing the trained model. As before, we set the dimension of the latent space to $d=3$. We tested the two trained CGPDM following the same procedure that was adopted in Sec. \ref{sec: sim_exp_results}. The two models were used to predict the cloth movements obtained in response to the control actions of each test trajectory\footnoteref{note1}. The average distance between the real and the predicted mesh points in range $R=30$°, was $0.012 \pm 0.005$, while, in range $R=60$°, it was $0.015 \pm 0.006$. These results are slightly inferior to those obtained in the simulated experiment (Fig. \ref{fig: table}). Nevertheless, CGPDMs seem able to cope with the high noise that afflicts the real experimental setup and still capture the dynamics of the cloth. In Fig. \ref{fig: real rollout}, we provide a visual representation of the cloth movements, by representing the true and predicted trajectories of the four corners, for one of the considered test cases. \section{Conclusions}\label{sec: conclusions} We presented CGPDM, a modeling framework for high-dimensional dynamics governed by control actions. Essentially, this model projects observations into a latent space of low dimension, where dynamical relations are easier to infer. CGPDMs were applied to a robotic cloth manipulation task, where the observations are the coordinates of the cloth mesh. We tested CGPDMs on both simulated and real experiments. The first was used to compare two possible parameterizations of the model, while in the second we challenged CGPDM with noisy real data. In the future, CGPDM formulation could be extended through the introduction of back constraints \cite{lawrence2006local} to preserve local distances and obtain an explicit formulation of the mapping from the observation to latent space. Moreover, the models can be developed further in order to include contacts. \clearpage \bibliographystyle{IEEEtran}
{'timestamp': '2021-09-14T02:40:36', 'yymm': '2103', 'arxiv_id': '2103.06615', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06615'}
arxiv
\subsubsection*{References}} \usepackage{mathtools} \usepackage{booktabs} \usepackage{tikz} \usepackage{multirow} \usepackage{color} \usepackage{amsmath, amsfonts, mathtools} \usepackage{algorithm} \usepackage[noend]{algpseudocode} \def{\mathbf{x}}{{\mathbf{x}}} \def{\mathbf{p}}{{\mathbf{p}}} \def{\mathbf{c}}{{\mathbf{c}}} \def{\mathbf{r}}{{\mathbf{r}}} \def{\mathbf{z}}{{\mathbf{z}}} \def{\mathbf{w}}{{\mathbf{w}}} \def{\mathbf{a}}{{\mathbf{a}}} \def{\mathbf{y}}{{\mathbf{y}}} \def{\mathbf{y}}{{\mathbf{y}}} \def{\mathbf{Z}}{{\mathbf{Z}}} \def{\mathbf{X}}{{\mathbf{X}}} \def{\mathbf{W}}{{\mathbf{W}}} \def{\mathbf{B}}{{\mathbf{B}}} \def{\boldsymbol{\pi}}{{\boldsymbol{\pi}}} \def{\boldsymbol{\alpha}}{{\boldsymbol{\alpha}}} \def{\boldsymbol{\mu}}{{\boldsymbol{\mu}}} \def{\mathcal{N}}{{\mathcal{N}}} \def{\mathbb{E}}{{\mathbb{E}}} \def{\mathbb{R}}{{\mathbb{R}}} \newcommand{\textcolor{blue}}{\textcolor{blue}} \newcommand{\textcolor{red}}{\textcolor{red}} \newcommand{\marginpar{FIX}}{\marginpar{FIX}} \newcommand{\swap}[3][-]{#3#1#2} \title{{Inference for} Generative Capsule Models} \author[1]{\href{mailto:Alfredo Nazabal <[email protected]>?Subject=Generative Capsule Models}{Alfredo Nazabal}{}} \author[1,2]{Christopher K.I. Williams} \affil[1]{% The Alan Turing Institute, London, UK} \affil[2]{% School of Informatics, University of Edinburgh, UK } \begin{document} \maketitle \begin{abstract} Capsule networks (see e.g.~\citealp{hinton2018matrix}) aim to encode knowledge and reason about the relationship between an object and its parts. In this paper we focus on a clean version of this problem, where data is generated from multiple geometric objects (e.g. triangles, squares) at arbitrary translations, rotations and scales, and the observed datapoints (parts) come from the corners of all objects, without any labelling of the objects. We specify a generative model for this data, and derive a variational algorithm for inferring the transformation of each object and the assignments of points to parts of the objects. Recent work by~\cite{kosiorek2019stacked} has used amortized inference via stacked capsule autoencoders (SCA) to tackle this problem---our results show that we significantly outperform them. We also investigate inference for this problem using a RANSAC-type algorithm. \end{abstract} \section{Introduction} An attractive way to set up the problem of object recognition is \emph{hierarchically}, where an object is described in terms of its parts, and these parts are in turn composed of sub-parts, and so on. For example a face can be described in terms of the eyes, nose, mouth, hair, etc.; and a teapot can be described in terms of a body, handle, spout and lid parts. This approach has a long history in computer vision, see e.g.\ Recognition-by-Components by \citet{biederman-87}. Advantages of recognizing objects by first recognizing its constituent parts include tolerance to the occlusion of some parts, and that parts may vary less under a change of pose than the appearance of the whole object. One big advantage of a parts-based setup is that if the pose\footnote{i.e.\ the location and rotation of the object in 2D or 3D.} of the object changes, this can have very complicated effects on the pixel intensities in an image, but the geometric transformation between the object and the parts can be described by a simple linear transformation (as used in computer graphics). Convolutional neural networks can allow a recognition system handle 2D shifts of an object in the image plane, but attempts to generalize such equivariances across more general transformations lead to cumbersome constructions, and have not been very successful. Recent work by Hinton and collaborators~\citep{sabour2017dynamic,hinton2018matrix} has developed \emph{capsule networks}. The key idea here is that a part in a lower level can vote for the pose of an object in the higher level, and an object's presence is established by the agreement between votes for its pose. \citet[p.~1]{hinton2018matrix} use an iterative process called ``routing-by-agreement'' which ``updates the probability with which a part is assigned to a whole based on the proximity of the vote coming from that part to the votes coming from other parts that are assigned to that whole''. Subsequently~\citet{kosiorek2019stacked} framed inference for a capsule network in terms of an autoencoder, the Stacked Capsule Autoencoder (SCA). Here, instead of the iterative routing-by-agreement algorithm, a neural network $h^{\mathrm{caps}}$ takes as input the set of input parts and outputs predictions for the object capsules' instantiation parameters $\{{\mathbf{y}}_k \}_{k=1}^K$. Further networks $h_k^{\mathrm{part}}$ are then used to predict part candidates from each ${\mathbf{y}}_k$. The objective function used in~\citet{hinton2018matrix} (their eq.\ 4) is quite complex (involving four separate terms), and is not derived from first principles. In this paper we argue that the description in the paragraph above is backwards---it is more natural to describe the generative process \emph{by which an object gives rise to its parts}, and that the appropriate routing-by-agreement inference algorithm then falls out naturally from this principled formulation. Below we focus on a single-layer of part-object relations, as we need to show first that this is working properly; but the generative model should be readily extensible to deeper hierarchies. The contributions of this paper are to: \begin{itemize} \item Derive a variational inference algorithm for a generative model of object-part relationships, including a relaxation of the permutation-matrix formulation for matching object parts to observations; % \item {Obtain a principled routing-by-agreement algorithm from this formulation;} \item Evaluate the performance of our model vs.\ competitors (including a RANSAC-type algorithm, \citealt*{fischler1981random}) on the inference task in scenes consisting of 2D points. \end{itemize} \section{Overview} Our images consist of a set of objects in different poses. Examples include images of handwritten digits, faces, or geometric shapes in 2D or 3D. An object can be defined as an instantiation of a specific model object (or template) with a particular pose (or geometric transformation). Furthermore, objects, and thus templates, are decomposed in parts, which are the basic elements that comprise the objects. For example, a digit can be decomposed in different strokes, or a geometric shape can be decomposed into vertices. More formally, let $T = \{T_k\}_{k=1}^K$ be the set of $K$ templates that are used to generate a scene. Each template $T_k=\{{\mathbf{p}}_n\}_{n=1}^{N_k}$ is composed of $N_k$ parts ${\mathbf{p}}_n$. We assume that scenes can only be generated using the available templates. Furthermore, every scene can present a different configuration of objects, with some objects missing from some scenes. For example, in scenes that could potentially contain all digits from 0 to 9 once, if only the digits 2 and 5 are in the image, we consider that the other digits are missing. Each observed template in a scene is then transformed by an independent transformation ${\mathbf{y}}_k$, different for each template, generating a transformed object $X_k = \{{\mathbf{x}}_n\}_{n=1}^{N_k}$ \begin{equation} T_k \xrightarrow{{\mathbf{y}}_k} X_k . \end{equation} Assume that we are given a scene $X = \{{\mathbf{x}}_m\}_{m=1}^M$ composed of $M$ observed parts. The \emph{inference problem} for $X$ involves different tasks. We need to determine which objects from the set of templates were employed to generate the scene\footnote{We will only consider fully missing objects in this paper, but the methods described below are also applicable to partially occluded objects with some parts missing.}. Also, we need to infer what transformation ${\mathbf{y}}_k$ was applied to each template to generate the objects. This then allows us to infer the \emph{correspondences} between the template points and the scene points. If all the templates were employed in the scene, then the number of observed parts $M$ is equal to the sum of all the parts of all the templates $N = \sum_{k=1}^K N_k$. \begin{figure}[t] \centering \caption{Scenes composed of ${\mathbb{R}}^2$ points (upper figures) and their corresponding objects matching (lower figures).} \includegraphics[width=0.75\linewidth]{Figures/Constellations2.png} \label{fig:constellations} \end{figure} In this paper we particularly focus on a clean version of this problem involving "constellations", where the data consists of 2D points derived from the vertices of geometric shapes (e.g.\ squares and triangles), as used in \cite[\S 2.1]{kosiorek2019stacked}. The transformations ${\mathbf{y}}_k$ are restricted to linear similarity transformations that translate, rotate and scale the templates to generate the objects of the scene. In general parts can have appearance information that helps to distinguish them (e.g.\ for face parts), but the constellation data is particularly hard as the datapoints are just points in $\mathbb{R}^2$ with no appearance information. The extension of the model to cover appearance features is described in supp.\ mat.\ \ref{sec:appAppearance}. Figure~\ref{fig:constellations} shows several examples of shapes located at multiple positions with different rotations and scaling factors. Given a set of unlabelled points comprising a scene (upper figures), we seek to find the objects that were used to generate such scene (lower figures). \section{Generative model for capsules}\label{sec:generative} We propose a generative model to describe our problem. We will consider a Gaussian mixture model approach. Given a set of observations (points) $X$ that were generated by $K$ different components, we want to identify the points in $X$ that belong to each component. Each component is a different object with transformation ${\mathbf{y}}_k$, and the template model is used to generate the data. Every observation in $X$ is a part that belongs uniquely to one of the objects. In this work we only use translation, rotation and scaling in 2D as possible transformations for each object. Consider a template with parts ${\mathbf{p}}_n = (p_{nx}, p_{ny})$ for $n = 1, \ldots, N_k$ that we want to scale by a factor $s$, rotate through with a clockwise rotation angle $\theta$ and translate by $(t_x,t_y)$, to obtain a transformed object with parts ${\mathbf{x}}_n = (x_{nx},x_{ny})$. For each part in the template, the transformation works as follows: \begin{equation} \begin{pmatrix} x_{nx}\\ x_{ny} \end{pmatrix} = \begin{pmatrix} t_{x}\\ t_{y} \end{pmatrix} + \begin{pmatrix} s\cos{\theta} & s\sin{\theta}\\ -s\sin{\theta} & s\cos{\theta}\end{pmatrix} \begin{pmatrix} p_{nx}\\ p_{ny} \end{pmatrix} , \end{equation} which can also be expressed as \begin{equation}\label{eq:F_kn_y} \begin{pmatrix} x_{nx}\\ x_{ny} \end{pmatrix} = \begin{pmatrix} 1 & 0 & p_{nx} & p_{ny}\\ 0 & 1 & p_{ny} & -p_{nx} \end{pmatrix} \begin{pmatrix} t_x\\ t_y\\ s\cos{\theta}\\ s\sin{\theta} \end{pmatrix} \stackrel{def}{=} F_{kn}{\mathbf{y}}_k, \end{equation} {where ${\mathbf{y}}_k$ is the ${\mathbb{R}}^4$ column vector and $F_{kn} \in {\mathbb{R}}^{2\times 4}$ is the matrix to its left.} From~\eqref{eq:F_kn_y} we can completely characterize a template $T_k$ by a set of matrices $\{F_{kn}\}_{n=1}^{N_k}$ containing all the information of its parts. Also, the information about the transformation applied to template $T_k$ is fully contained in the ${\mathbb{R}}^4$ vector ${\mathbf{y}}_k$. Notice that we can recover each of the terms of the transformation from the elements of vector ${\mathbf{y}}_k$ \begin{eqnarray} t_x = y_{k1}, & t_y = y_{k2},\\ s = \sqrt{y_{k3}^2 + y_{k4}^2}, & \theta = \arctan{\frac{y_{k4}}{y_{k3}}} . \end{eqnarray} Now, let $z_{mnk} \in \{0,1\}$ indicate whether the point ${\mathbf{x}}_m$ belongs to the part $n$ of object $k$. Every point $m$ belongs uniquely to a tuple $(k,n)$, or in other words, a point ${\mathbf{x}}_m$ belongs uniquely to the part defined by ${\mathbf{y}}_k$ acting on the template matrix $F_{kn}$. Interestingly, the opposite is also partially true. Every tuple $(k,n)$ belongs uniquely to a point $m$ or it is unassigned if object $k$ is missing in the scene. The joint distribution of the variables in the model is given by \begin{equation} p(X,Y,Z) = p(X|Y,Z)p(Y)p(Z), \end{equation} where $p(X|Y,Z)$ is a Gaussian mixture model explaining how the points in a scene were generated from the templates \begin{equation}\label{eq:p_X} p(X|Y,Z) = \prod_{m=1}^M\prod_{k=1}^K\prod_{n=1}^{N_k} N\left({\mathbf{x}}_{m}|F_{kn}{\mathbf{y}}_{k},\lambda^{-1}I_2\right)^{z_{mnk}}, \end{equation} with $\lambda$ being the precision of the Gaussian distribution for each point and $I_2$ the identity matrix of dimension $2$. Note that such a model for a \emph{single object} was developed by~\citet{revow-williams-hinton-96}. The distribution over similarity transformations ${\mathbf{y}}_k$ is modelled with a ${\mathbb{R}}^4$ Gaussian distribution with mean ${\boldsymbol{\mu}}_0$ and precision matrix $\Lambda_0$: \begin{equation} \label{eq:p_Y} p(Y) = \prod_{k=1}^K N({\mathbf{y}}_{k}|{\boldsymbol{\mu}}_0,\Lambda_0^{-1}). \end{equation} Notice that modelling ${\mathbf{y}}_k$ with a Gaussian distribution implies that we are modelling the translation $(t_x,t_y)$ in ${\mathbb{R}}^2$ with a Gaussian distribution. If $\mu_0=\mathbf{0}$ and $\Lambda_0 = I_4$ then $s^2 = y^2_{k3} + y^2_{k4}$ has a $\chi^2_2$ distribution, and $\theta$ is uniformly distributed in its range $[-\pi,\pi]$ by symmetry. For more complex linear transformations (e.g.\ an affine transformation), we need only to increase the dimension of ${\mathbf{y}}_k$ and change the form of $F_{kn}$, but the generative model in~\eqref{eq:p_Y} would remain the same. In a standard Gaussian mixture model, the assignment matrix $Z$ is characterized by a Categorical distribution, where each point ${\mathbf{x}}_m$ is assigned to one part \begin{equation} \label{eq:p_Z} p(Z) = \prod_{m=1}^M \text{Cat}({\mathbf{z}}_{m}|{\boldsymbol{\pi}}), \end{equation} with ${\mathbf{z}}_m$ {being a 0/1 vector with only one 1,} and ${\boldsymbol{\pi}}$ being the probability vector for each tuple $(k,n)$. However, the optimal solution to our problem occurs when each part of a template belongs uniquely to one point in a scene. This means that $Z$ should be a permutation matrix, where each point $m$ is assigned to a tuple $(k,n)$ and vice versa. Notice that a permutation matrix is a square matrix, so if $M \leq N$, {we add dummy rows to $Z$, which are assigned to missing points in the scene.} {The set of permutation matrices of dimension $N$ is a discrete set containing $N!$ permutation matrices. They can be modelled with a discrete prior over permutation matrices, assigning each matrix $Z_i$ a probability $\pi_i$, such as: \begin{equation} \label{eq:p_Z_true} p_{perm}(Z) = \sum_{i=1}^{N!} \pi_i \; I[Z=Z_i] \end{equation} with $\sum_{i=1}^{N!} \pi_i = 1$ and $I[Z=Z_i]$ the indicator function, being equal to $1$ if $Z=Z_i$ and $0$ otherwise.} The number of possible permutation matrices increases as $N!$, {which makes exact inference over permutations intractable.} An interesting property of $p_{perm}(Z)$ is that its first moment ${\mathbb{E}}_{p_{perm}}[Z]$ is a doubly-stochastic (DS) matrix, a matrix of elements in $[0,1]$ whose rows and columns sum to 1. We propose to relax $p_{perm}(Z)$ to a distribution $p_{DS}(Z)$ that is characterized by the doubly-stochastic matrix $A$ with elements $a_{mnk}$, such that ${\mathbb{E}}_{p_{DS}}[Z]=A$: \begin{equation} \label{eq:p_Z_approx} p_{DS}(Z) = \prod_{m=1}^{N}\prod_{k=1}^{K}\prod_{n=1}^{N_k} a_{mnk}^{z_{mnk}}. \end{equation} {$A$ is fully characterized by $(N-1)^2$ elements. We will use a uniform prior over $Z$ with $a_{mnk}=\frac{1}{N}$. However, note that $p_{DS}$ can also represent a particular permutation matrix $Z_i$ by setting the appropriate entries of $A$ to 0 or 1, and indeed we would expect this to occur during variational inference (see sec.\ \ref{sec:VI}) when the model converges to a correct solution.} \subsection{Variational Inference}\label{sec:VI} Variational inference for the above model can be derived similarly to the Gaussian Mixture model case~\citep[Chapter 10]{bishop2006pattern}. The variational distribution under the mean field assumption is given by \begin{equation} q(Z,Y) = q(Z)q(Y), \end{equation} where the optimal solutions for $\log{q(Z)}$ and $\log{q(Y)}$ under the generative model can be expressed as \begin{eqnarray} \log{q(Z)} &\propto & {\mathbb{E}}_{q(Y)}[\log{p(X,Y,Z)}]\\ \log{q(Y)} &\propto & {\mathbb{E}}_{q(Z)}[\log{p(X,Y,Z)}] \end{eqnarray} For $q(Z)$ we obtain an expression with the same distribution model as the prior in~\eqref{eq:p_Z_approx} \begin{eqnarray} q(Z) \propto \prod_{m=1}^N\prod_{k=1}^K\prod_{n=1}^{N_k} \rho_{mnk}^{z_{mnk}},\label{eq:q_Z} \end{eqnarray} where $\rho_{mnk}$ represents the unnormalized probability of point $m$ being assigned to tuple $(k,n)$ and vice versa. These unnormalized probabilities have a different expression depending on whether we are considering a point that appears in the scene ($m \leq M$) \begin{align}\nonumber \log{\rho_{mnk}} &= \log{a_{mnk}} -\log{2\pi} + \log{\lambda} - \\ &\frac{\lambda}{2}{\mathbb{E}}_{{\mathbf{y}}_k}[({\mathbf{x}}_{m} - F_{kn}{\mathbf{y}}_{k})^T({\mathbf{x}}_{mt} - F_{kn}{\mathbf{y}}_{k})],\label{eq:log_rho} \end{align} or whether we are considering a dummy row of the prior ($m > M$), \begin{align} \log{\rho_{mnk}} &= \log{a_{mnk}}.\label{eq:log_rho_dummy} \end{align} When a point is part of the scene~\eqref{eq:log_rho}, and thus $m \leq M$ the update of $\rho_{mnk}$ is similar to the Gaussian mixture model case. However, if a point is not part of the scene~\eqref{eq:log_rho_dummy}, and thus $m > M$ then the matrix is not updated and the returned value is the prior $a_{mnk}$. This specific choice of distribution for both $p_{DS}(Z)$ and $q(Z)$ leads naturally to the addition of dummy rows that are employed to make the matrix $\rho$ square. {Now, the normalized distribution $q(Z)$ becomes: \begin{eqnarray} q(Z) = \prod_{m=1}^N\prod_{k=1}^K\prod_{n=1}^{N_k} r_{mnk}^{z_{mnk}},\label{eq:R_doubleStochastic} \end{eqnarray} where ${\mathbb{E}}_{q(Z)}[z_{mnk}] = r_{mnk}$. The elements $r_{mnk}$ of matrix $R$ represent the posterior probability of each point $m$ being uniquely assigned to the part-object tuple $(n,k)$ and vice-versa. This means that $R$ needs to be a DS matrix. {This can be achieved by employing the Sinkhorn-Knopp algorithm~\citep{sinkhorn1967concerning}, which updates a square non-negative matrix by normalizing the rows and columns alternately, until the resulting matrix becomes doubly stochastic (see supp.\ mat.\ \ref{sec:appVI} for more details). The use of the Sinkhorn-Knopp algorithm for approximating matching problems has also been described by \cite{powell2019computing} and \cite{mena2020sinkhorn}, but note that in our case we also need to alternate with inference for $q(Y)$.} } Furthermore, the optimal solution to the assignment problem occurs when $R$ is a permutation matrix itself. When this happens we exactly recover a discrete posterior (with the same form as~\eqref{eq:p_Z_true}) over permutation matrices where one of them has probability one, with the others being zero. The distribution for $q(Y)$ is a Gaussian with \begin{align} q(Y) &= \prod_{k=1}^K N({\mathbf{y}}_k|{\boldsymbol{\mu}}_k,\Lambda_k^{-1}), \\\label{eq:Lambda_k} \Lambda_{k} &= \Lambda_0 + \lambda \sum_{m=1}^{M}\sum_{n=1}^{N_k} r_{mnk} F_{kn}^TF_{kn}, \\\label{eq:mu_k} \mu_{k} &= \Lambda_{k}^{-1}(\Lambda_0{\boldsymbol{\mu}}_0 + \lambda \sum_{m=1}^{M}\sum_{n=1}^{N_k} r_{mnk}F_{kn}^T{\mathbf{x}}_{m}), \end{align} where the updates for both $\Lambda_k$ and ${\boldsymbol{\mu}}_k$ depend explicitly on the templates employed in the model through the transformation matrices $F_{kn}$ and the precision term $\lambda$. {Note that the prediction from datapoint $m$ to the mean of ${\mathbf{y}}_k$ is given by $\sum_n r_{mnk} F^T_{kn} {\mathbf{x}}_m$, i.e.\ a weighted sum of the predictions of each part $n$ with weights $r_{mnk}$.} These expressions remain the same when considering a Gaussian mixture prior such as~\eqref{eq:p_Z}. Finally, the expectation term in~\eqref{eq:log_rho} under this model becomes \begin{align} &{\mathbb{E}}_{{\mathbf{y}}_{k}}[({\mathbf{x}}_{m} - F_{kn}{\mathbf{y}}_{k})^T({\mathbf{x}}_{m} - F_{kn}{\mathbf{y}}_{k})] =\\\nonumber & ({\mathbf{x}}_{m} - F_{kn}{\boldsymbol{\mu}}_{k})^T({\mathbf{x}}_{m} - F_{kn}{\boldsymbol{\mu}}_{k}) + \text{trace}(F_{kn}^TF_{kn}\Lambda_{k}^{-1}) . \end{align} The evidence lower error bound (ELBO) $L(q)$ for this model is decomposed in three terms: \begin{align}\label{eq:ELBO} L(q) &={\mathbb{E}}_q[\log{p(X|Y,Z)}] \\\nonumber &- KL(q(Y)||p(Y)) - KL(q(Z)||p(Z)), \end{align} with $KL(q||p)$ being the Kullback-Leibler divergence between distributions $q$ and $p$. Expressions for these two terms are given in supp.\ mat.\ \ref{sec:appVI}. The first term indicates how well the generative model $p(X|Y,Z)$ fits the observations under our variational model $q(Y,Z)$: \begin{align}\label{eq:E_q_X} &{\mathbb{E}}_q[\log{p(X|Y,Z)}] = M \left(-\log{2\pi} + \log{\lambda} \right)\\\nonumber &-\frac{\lambda}{2} \sum_{m=1}^M\sum_{k=1}^K\sum_{n=1}^{N_k} r_{mnk} ({\mathbf{x}}_{m} - F_{kn}{\boldsymbol{\mu}}_{k})^T({\mathbf{x}}_{m} - F_{kn}{\boldsymbol{\mu}}_{k})\\\nonumber &-\frac{\lambda}{2} \sum_{m=1}^M\sum_{k=1}^K\sum_{n=1}^{N_k} r_{mnk} \text{trace}(F_{kn}^TF_{kn}\Lambda_{k}^{-1}) . \end{align} Finally, in Algorithm~\ref{alg:variational_inference} we present the inference procedure for this model. {The alternating updates of $q(Y)$ and $q(Z)$ carry out routing-by-agreement.} We describe how the annealing of $\lambda$ (line 10) is implemented in Section~\ref{sec:implementation}. \begin{algorithm}[t] \caption{Variational Inference} \label{alg:variational_inference} \begin{algorithmic}[1] \State Initialize $\lambda$, $\lambda_{max}$ and $R \sim U[0,1]^{N\times N}$, $\forall m,n,k$ \State $R = \text{SinkhornKnopp}(R)$ \While{not converged} \State Update $\Lambda_k$~\eqref{eq:Lambda_k}, $\forall k$ \State Update ${\boldsymbol{\mu}}_k$~\eqref{eq:mu_k}, $\forall k$ \State Update $\log{\rho_{mnk}}$~\eqref{eq:log_rho}\eqref{eq:log_rho_dummy}, $\forall m,n,k$ \State Update $R = \text{SinkhornKnopp}(\rho)$ \If{ELBO has converged} \If{$\lambda < \lambda_{max}$} \State Anneal $\lambda$ \Else \State converged = True \EndIf \EndIf \EndWhile \Return $R,\mu_k,\Lambda_k$ \end{algorithmic} \end{algorithm} \subsection{Comparison with other objective functions} {In \cite{hinton2018matrix} an objective function $cost^h_k$ is defined (their eq.\ 1) which considers inference for the pose of a higher-level capsule $k$ on pose dimension $h$. Translating to our notation, $cost^h_k$ combines the votes from each datapoint $m$ as $cost^h_k = \sum_m r_{mk} \ln P^h_{m|k}$, where $P^h_{m|k}$ is a Gaussian, and $r_{mk}$ is the ``routing softmax assignment'' between $m$ and $k$. It is interesting to compare this with our equation \eqref{eq:mu_k}. Firstly, note that the vote of ${\mathbf{x}}_m$ to part $n$ in object $k$ is given explicitly by $F^T_{kn} {\mathbf{x}}_m$, i.e.\ we do not require introduction of an independent voting mechanism, this falls out directly from the inference. Secondly, note that our $R$ must keep track not only of assignments to objects, but also to parts of the objects. In contrast to \citet{hinton2018matrix}, our inference scheme is derived from variational inference on the generative model, rather than introducing an \emph{ad hoc} objective function.} {The specialization of the SCA method of \citet{kosiorek2019stacked} to constellation data is called the ``constellation capsule autoencoder (CCAE)'' and discussed in their sec.\ 2.1. Under their equation 5, we have that \begin{align}\label{eq:CCAE_loss} p({\mathbf{x}}_{1:M}) = \prod_{m=1}^M\sum_{k=1}^K\sum_{n=1}^N \frac{a_ka_{k,n}}{\sum_i a_i \sum_j a_{ij}} N({\mathbf{x}}_m|\mu_{k,n},\lambda_{k,n}), \end{align} where $a_k \in [0,1]$ is the presence probability of capsule $k$, $a_{k,n} \in [0,1]$ is the conditional probability that a given candidate part $n$ exists, and $\mu_{k,n}$ is the predicted location of part $k,n$. The $a_k$s are predicted by the network $h^{\mathrm{caps}}$, while the $a_{k,n}$s and $\mu_{k,n}$s are produced by separate networks $h_k^{\mathrm{part}}$ for each part $k$.} {We note that \eqref{eq:CCAE_loss} provides an autoencoder style reconstructive likelihood for ${\mathbf{x}}_{1:M}$, as the $a$'s and $\mu$'s depend on the data. To handle the arbitrary number of datapoints $M$, the network $h^{\mathrm{caps}}$ employs a Set Transformer architecture~\citep{lee-lee-kosiorek-choi-teh-19}. In comparison to our iterative variational inference, the CCAE is a ``one shot'' inference mechanism. This may be seen as an advantage, but in scenes such as Figure~\ref{fig:constellations} with overlapping objects, humans may perform reasoning like ``if that point is one of the vertices of a square, then this other point needs to be explained by a different object'' etc, and it may be rather optimistic to believe this can be done in a simple forward pass. Also, CCAE cannot exploit prior knowledge of the geometry of the objects, as it relies on an opaque network $h^{\mathrm{caps}}$ which requires extensive training.} \subsection{Related work} Above we have discussed the work of \citet{sabour2017dynamic,hinton2018matrix} and \citet{kosiorek2019stacked}. There is some more recent work, for example \citet{li-zhu-naud-xi-20} present an undirected model, based on the capsule RBM of \citet{li-zhu-19}. Compared to our work, this is an undirected as opposed to directed generative model. Also \citet{smith-schut-gal-vanderwilk-21} propose a layered directed generative model, where the children of higher level capsules inherit its pose (but transformed). Both \citet{li-zhu-naud-xi-20} and \citet{smith-schut-gal-vanderwilk-21} consider tree-structured relationships between parents and children, similar to \citet{hinton-ghahramani-teh-00} and \citet{storkey-williams-03}. However, most importantly, these recent capsule models do not properly handle the fact that the input to a capsule should be a \emph{set} of parts; instead in their work the first layer capsules that interact with the input image model specific location-dependent features/templates in the image, {and their second layer capsules have interactions with the specific first layer capsules (e.g.\ the fixed affinity $\rho^k_{ij}$ of \citet{smith-schut-gal-vanderwilk-21} parent $i$ in layer $k$ for child $j$). But if we consider a second-layer capsule that is. for example, detecting the conjunction of the 3 strokes comprising a letter ``A'', then at different translations, scales and rotations of the A it will need to connect to different image level stroke features, so these connection affinities must depend on transformation variables of the parent. } \section{A RANSAC approach to inference} \label{sec:geometric_hashing} {A radical alternative to ``routing by agreement'' inference is to make use of a ``random sample consensus'' approach (RANSAC, \citealp*{fischler1981random}).} We can derive a RANSAC approach to the constellations problem that follows the same principles described in our generative model. {For any pair of points on one of the templates we can try matching these to every possible pair of $M(M-1)$ points in the scene. The key insight is that a pair of known points is sufficient to compute the 4-dimensional ${\mathbf{y}}_k$ vector in the case of similarity transformations. In general the minimal number of points needed is known as the size of the basis; for example a three-point basis would be required for a general affine transform in 2D. Using the transformation $\hat{{\mathbf{y}}}_k$, we can then \emph{predict} the location of the remaining parts of the template, and \emph{check} if these are actually present. If so, this provides evidence for the existence of $T_k$ and $\hat{{\mathbf{y}}}_k$. After considering the $M(M-1)$ subsets, it then combines the identified instantiations to give an overall explanation of the scene. A summary of the algorithm is given in Algorithm~\ref{alg:geometric_hashing}.} {In more detail, assume we have chosen parts $n_1$ and $n_2$ as the basis for object $k$, and that we have selected datapoints ${\mathbf{x}}_i$ and ${\mathbf{x}}_j$ as their hypothesized counterparts in the image. Let ${\mathbf{x}}_{ij}$ be the vector obtained by stacking ${\mathbf{x}}_i$ and ${\mathbf{x}}_j$, and $B_k$ be the $4\times 4$ square matrix obtained by stacking $F_{k n_1}$ and $F_{k n_2}$. Then $\hat{{\mathbf{y}}}_k = B_{k}^{-1}{\mathbf{x}}_{ij}$. Finally, $\text{SubsetMatch}(\hat{X}_k, X)$ selects those points in $X_k$ that are close to $X$ with a given tolerance and add them to the output. Among them, the solution is given by the one that minimizes $\sum_{n=1}^{N_k}(\hat{x}_{nk} - x_{nk})^2$. The above algorithm chooses a specific basis for each object, but one can consider all possible bases for each object. It is then efficient to use a hash table to store the predictions for each part, as used in Geometric Hashing~\citep{wolfson1997geometric}. Geometric Hashing is traditionally employed in computer vision to match geometric features against previously defined models of such features. This technique works well with partially occluded objects, and is computationally efficient if the basis dimension is low. \begin{algorithm}[t] \caption{RANSAC approach \label{alg:geometric_hashing}} \begin{algorithmic}[1] \State $T$: $K$ templates of the scene \State $B_k$: base matrix for template $T_k$ \State $X$: $M$ points of the scene \State $out = []$ \For{${\mathbf{x}}_i \in X$} \For{${\mathbf{x}}_j \in X \setminus x_i$} \State ${\mathbf{x}}_{ij} = \text{Vectorize}({\mathbf{x}}_i,{\mathbf{x}}_j)$ \For{$k = 1:K$} \State $\hat{{\mathbf{y}}}_k = B_k^{-1}{\mathbf{x}}_{ij}$ \State $T_k \xrightarrow{\hat{{\mathbf{y}}}_k} \hat{X}_k$ \If{ \text{SubsetMatch}($\hat{X}_k, X)$} \State Add $(T_k,\hat{{\mathbf{y}}}_k,\hat{X}_k)$ to $out$ \EndIf \EndFor \EndFor \EndFor \Return $out$ \end{algorithmic} \end{algorithm} \section{Evaluation}\label{sec:Evaluation} In order to allow fair comparisons, we use the same dataset generator for geometric shapes employed by~\cite{kosiorek2019stacked}. We create a dataset of scenes, where each scene consists of a set of 2D points, generated from different geometric shapes. The possible geometric shapes (templates) are a square and an isosceles triangle, with parts being represented by the 2D coordinates of the vertices. We use the same dimensions for the templates as used by~\cite{kosiorek2019stacked}, side 2 for the square, and base and height 2 for the triangle. All templates are centered at $(0,0)$. In every scene we can have at most two squares and one triangle. Each shape is transformed with a random transformation to create a scene of 2D points given by the object parts. To match the evaluation of \cite{kosiorek2019stacked}, all scenes are normalized so as the points lie in $[-1,1]$ on both dimensions. While creating the scene, we select randomly (with probability 0.5) whether an object is going to be present or not, but delete empty scenes. {A test set used for evaluation is comprised of 450-460 non-empty scenes, based on 512 draws.} Additionally, we study how the methods compare when objects are created from noisy templates. We consider that the original templates used for the creation of the images are corrupted with Gaussian noise with standard deviation $\sigma$. Once the templates are corrupted with noise, a random transformation ${\mathbf{y}}_k$ is applied to obtain the object $X_k$ of the scene. As with the noise-free data, the objects are normalized to lie in [-1,1] on both dimensions. \subsection{Evaluation Metrics}\label{sec:metrics} {Three metrics are used to evaluate the performance of the methods: variation of information, adjusted Rand index and segmentation accuracy. They are based on partitions of the datapoints into those associated with each object, and those that are missing. Compared to standard clustering evaluation metrics, some modifications need to be made to handle the missing objects.} {In a given scene $X$ there are $M$ points, but we know that there are $N \ge M$ possible points that can be produced from all of the templates. Assume that $K' \le K$ templates are active in this scene. Then the points in the scene are labelled with indices $1, \ldots, K'$, and we assign the missing points index $0$. Denote the ground truth partition as $V = \{ V_0, V_1, \ldots V_{K'} \}$. An alternative partition output by one of the algorithms is denoted by $\hat{V} = \{ \hat{V}_0, \hat{V}_1, \ldots \hat{V}_{\hat{K}'} \}$. The predicted partition $\hat{V}$ may instantiate objects or points that were in fact missing, thus it is important to handle the missing data properly.} In Information Theory, the \textbf{variation of information} (VI)~\citep{meilua2003comparing} is a measure of the distance between two partitions of elements (or clusterings). For a given set of elements, the variation of information between two partitions $V$ and $\hat{V}$, where $N = \sum_i |V_i| = \sum_j |\hat{V}_j|$ is defined as: \begin{equation} VI(V,\hat{V}) = -\sum_{i,j} r_{ij}\left[\log{\frac{r_{ij}}{p_i}} + \log{\frac{r_{ij}}{q_j}} \right] \end{equation} where $r_{ij} = \frac{|V_i \cap \hat{V}_j|}{N}$, $p_i = \frac{|V_i|}{N}$ and $q_j = \frac{|\hat{V}_j|}{N}$. In our experiments we report the average variation of information of the scenes in the dataset. The \textbf{Rand index}~\citep{rand1971objective} is another measure of similarity between two data clusterings. This metric takes pairs of elements and evaluates whether they do or do not belong to the same subsets in the partitions $V$ and $\hat{V}$ \begin{equation} RI = \frac{TP + TN}{TP +TN +FP +FN}, \end{equation} where TP are the true positives, TN the true negatives, FP the false positives and FN the false negatives. The Rand index takes on values between 0 and 1. We use instead the \textbf{adjusted Rand index} (ARI) \citep{hubert1985comparing}, the corrected-for-chance version of the Rand index. In our experiments, we compute the average adjusted Rand index of the scenes in our dataset. The \textbf{segmentation accuracy} (SA) is based on obtaining the maximum bipartite matching between $V$ and $\hat{V}$, and was used by \citet{kosiorek2019stacked} to evaluate the performance of CCAE. For each set $V_i$ in $V$ and set $\hat{V}_j$ in $\hat{V}$, there is an edge $w_{ij}$ with the weight being the number of common elements in both sets. Let $W(V,\hat{V})$ be the overall weight of the maximum matching between $V$ and $\hat{V}$. Then we define the average segmentation accuracy as: \begin{equation} SA = \sum_{i=1}^I \frac{W(V_i,\hat{V}_i)}{W(V_i,V_i)} = \frac{1}{N}\sum_{i=1}^I W(V_i,\hat{V}_i), \end{equation} where $I$ is the number of scenes. Notice that $W(V_i,V_i)$ represents a perfect assignment of the ground truth, both the observed and missing subsets, and thus $W(V_i,V_i) = N$. There are some differences on how we compute the SA metric compared to~\cite{kosiorek2019stacked}. First, they do not consider the missing points as part of their ground truth, but as we argued above this is necessary. They evaluate the segmentation accuracy in terms of the observed points in the ground truth, disregarding possible points that were missing in the ground truth but predicted as observed in $\hat{V}$. Second, they average the segmentation accuracy across scenes as \begin{equation} SA = \frac{\sum_{i=1}^I W(V_i,\hat{V}_i)}{\sum_{i=1}^I W(V_i,V_i)} . \end{equation} For them, $W(V_i,V_i) = M_i$, where $M_i$ is the number of points present in a scene. In our case, both averaging formulae are equivalent since our $W(V_i,V_i)$ is the same across scenes. \section{Experiments} \label{sec:implementation} CCAE is trained by creating random batches of 128 scenes as described in the previous section and optimizing the objective function in~\eqref{eq:CCAE_loss}. The authors run CCAE for $300K$ epochs, and when the parameters of the neural networks are trained, they use their model on the test dataset to generate an estimation of which points belong to which capsule, and where the estimated points are located in each scene. For the variational inference approach, $p(X|Y,Z)$ in~\eqref{eq:p_X} allows us to model scenes where the points are corrupted with some noise. The precision $\lambda$ controls the level of noise allowed in the model. We use an annealing strategy to fit $\lambda$, increasing it every time the ELBO has converged, up to a maximum value of $\lambda_{max}=10000$. We set the hyperparameters of the model to $\mu_0=\mathbf{0}$, $\Lambda_0 = I_4$ and $a_{mnk} = \frac{1}{N}$. {We run Algorithm~\ref{alg:variational_inference} with 5 different random initializations of $R$ and select the solution with the best ELBO. Similarly to~\citet{kosiorek2019stacked}, we incorporate a sparsity constraint in our model, that forces every object to explain at least two parts. Once our algorithm has converged, for a given $k$ if any $r_{mnk}>0.9$ and $\sum_m\sum_n r_{mnk} < 2$ it means that the model has converged to a solution where object $k$ is assigned to less than 2 parts. In these cases, we re-run Algorithm~\ref{alg:variational_inference} with a new initialization of $R$. Notice that this is also related to the minimum basis size necessary in the RANSAC approach for the types of transformations that we are considering.} The implementation of the RANSAC algorithm (Algorithm~\ref{alg:geometric_hashing}) considers all matches between the predicted and the scene points where the distance between them is less than $0.1$. Among them, it selects the matching with minimum distance between scene and predicted points. For both the variational inference algorithm and the RANSAC algorithm, a training dataset is not necessary. These algorithms are applied directly to each test scene and return a set of objects describing the points in the scene. Unfortunately we do not have access to the code employed by~\citet{hinton2018matrix}, so we have been unable to make comparisons with it. \subsection{Results}\label{sec:noise-free} \begin{figure*}[t] \centering \caption{Reconstruction examples from CCAE and GCM-DS. The upper figures show the ground truth of the test images. The middle figures show the reconstruction and the capsule assignments (by colours) of CCAE. The lower figures show the reconstruction and the parts assignment of GCM-DS. {Datapoints shown with a given colour are predicted to belong to the reconstructed object with the corresponding colour.}} \includegraphics[width=0.7\linewidth]{Figures/example_images.png} \label{fig:examples} \end{figure*} {In Table~\ref{t:main_results} we show a comparison between CCAE, the variational inference method with a Gaussian mixture prior~\eqref{eq:p_Z} (GCM-GMM), with a prior over permutation matrices~\eqref{eq:p_Z_true} (GCM-DS), and the RANSAC approach~\footnote{Code at: https://github.com/anazabal/GenerativeCapsules}. For GCM-GMM and GCM-DS we show the results where the initial $\lambda = 500$, relegating a comparison across different initializations of $\lambda$ to the supp.\ mat.\ \ref{sec:lambda_study}. We provide results for the metrics described above, and an average scene accuracy metric, where a scene is correct if the method returns the full original scene, and is incorrect otherwise.} Scenes without noise {and with noise levels of $\sigma = 0.1, \; 0.25$ are considered.} \begin{table}[h] \centering \caption{Comparison between the different methods. For SA, ARI and Scene Accuracy the higher the better. For VI the lower the better. Different levels of Gaussian noise with standard deviation $\sigma$ are considered.} \begin{tabular}{|c|c|c|c|c|} \hline Metric & Model & $\sigma$=0 & $\sigma$=0.1 & $\sigma$=0.25 \\ \hline \multirow{4}{*}{SA $\uparrow$} & CCAE & 0.828 & 0.754 & 0.623\\ & GCM-GMM & 0.753 & 0.757 & 0.744\\ & GCM-DS & 0.899 & 0.882 & 0.785\\ & RANSAC & 1 & 0.992 & 0.965\\\hline \multirow{4}{*}{ARI $\uparrow$} & CCAE & 0.599 & 0.484 & 0.248\\ & GCM-GMM & 0.586 & 0.572 & 0.447\\ & GCM-DS & 0.740 & 0.699 & 0.498\\ & RANSAC & 1 & 0.979 & 0.914\\\hline \multirow{4}{*}{VI $\downarrow$} & CCAE & 0.481 & 0.689 & 0.988\\ & GCM-GMM & 0.478 & 0.502 & 0.677\\ & GCM-DS & 0.299 & 0.359 & 0.659\\ & RANSAC & 0 & 0.034 & 0.135\\\hline & CCAE & 0.365 & 0.138 & 0.033\\ Scene & GCM-GMM & 0.179 & 0.173 & 0.132\\ {Acc $\uparrow$} & GCM-DS & 0.664 & 0.603 & 0.377\\ & RANSAC & 1 & 0.961 & 0.843\\\hline \end{tabular} \label{t:main_results} \end{table} We can see that GCM-DS improves over CCAE and GCM-GMM in all of the metrics, with GCM-GMM being comparable to CCAE. Interestingly, for the noise-free scenarios, the RANSAC method achieves a perfect score for all of the metrics. Since there is no noise on the observations and the method searches over all possible solutions of ${\mathbf{y}}_k$, it can find the correct solution for any configuration of geometric shapes in a scene. For the noisy scenarios, all the methods degrade as $\sigma$ increases. However, the relative performance between them remains the same, with RANSAC performing the best, followed by GCM-DS and then GCM-GMM. Note that the GCM models here assume that the template for each model is unperturbed; however, as per supp.\ mat.\ \ref{sec:appAppearance} one could allow a prior on the part locations which would take into account that they are now noisy. We have conducted paired t-tests between CCAE and GCM-GMM, GCM-DS and RANSAC on the three metrics. The differences between CCAE and GCM-DS are statistically significant with p-values less than $10^{-7}$, and between CCAE and RANSAC with p-values less than $10^{-28}$. For CCAE and GCM-GMM the differences are not statistically significant. Figure~\ref{fig:examples} shows some reconstruction examples from CCAE and GCM-DS for the noise-free scenario. We show additional examples for the noisy cases in the supp.\ mat.\ \ref{sec:noisy_examples}. In columns (a) and (b) we can see that CCAE recovers the correct parts assignments but the object reconstruction is amiss. In (a) one of the squares is reconstructed as a triangle, while in (b) the assignment between the reconstruction and the ground truth is not exact. For GCM-DS, if the parts are assigned to the ground truth properly, {and there is no noise}, then the reconstruction of the object is perfect. {In column (c) all methods work well.} {In column (d), CCAE fits the square correctly (green), but adds an additional red point. In this case GCM-DS actually overlays two squares on top of each other. Both methods fail badly on column (e). Note that CCAE is not guaranteed to reconstruct an existing object correctly (square or triangle in this case). In column (f) we can see that CCAE fits an irregular quadrilateral (blue) to the assigned points, {while GCM-DS obtains the correct fit.}} \section{Discussion} Above we have described a principled generative capsules model. It leads directly to a variational inference algorithm which can handle either a mixture formulation or incorporation of the DS matrix constraint. We have also shown that this formulation outperforms the CCAE of \citet{kosiorek2019stacked} on the constellation data generator that they used. In this paper we have not discussed the learning of the model (i.e.\ the $F_{kn}$ matrices), but in all such work, inference for $q(Z,Y)$ forms an inner loop, with model learning as an outer loop. Also, the interpretable nature of the model means that we can exploit the geometric knowledge where it is available; in contrast the CCAE's opaque inference networks do not allow this. One challenge for the future is to extend this work beyond purely geometric situations, e.g.\ to images with multiple digits as in \citet{kosiorek2019stacked}. The theory for this is presented in supp.\ material \ref{sec:appAppearance}. The other notable challenge is around generalizing RANSAC-style inference. For the geometric testbed, this is remarkably effective, and it leads to the question if similar techniques could work in a more general setting. \begin{acknowledgements} This work was supported in part by The Alan Turing Institute under EPSRC grant EP/N510129/1. \end{acknowledgements}
{'timestamp': '2021-03-12T02:24:21', 'yymm': '2103', 'arxiv_id': '2103.06676', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06676'}
arxiv
\section{Introduction and context} \noindent Software citation helps to make research software sustainable and attribute credit to its contributors. Citations provide references to software used in, and/or created as part of, research. Citations to research outputs are the primary impact-related metric in academia, and it is more practical to fit software into this system than to create a new one based on alternative metrics. It is frequently assumed that the number of citations correlates positively with the impact or importance of a research output. Because of this, citation metrics are used as a key factor in hiring, promotion and funding decisions. Software citation has at least two effects ($E$) on research software sustainability: \begin{enumerate*}[label=$E\arabic*$)] \item \emph{Citations to software as an impact metric} incentivize staff, projects, and institutions to make software sustainable. \item \emph{Citations to software as references} provide identification and traceability of software used in previous research, which enables reuse and adaption. \end{enumerate*} Software citation also supports reproducibility: to understand and reproduce research results, all parts of the research process including software must be uniquely identifiable, e.g., through citation. To fully realize reproducibility, the identified software itself must also be sustainable or at least archived, so that computations can be carried out to reproduce results. The principles of software citation are defined as \begin{enumerate*}[label=(P\arabic*)] \item Importance; \item credit and attribution; \item unique identification; \item persistence; \item accessibility; \item specificity~\cite{smithSoftwareCitationPrinciples2016}. \end{enumerate*} These principles touch upon effects of software citation on both software sustainability and reproducibility. Concerning $E1$, (P1) is the baseline premise for research software sustainability: that software is considered an important and integral part of research that is crucial to sustain, and to fund in the future. (P2) is required to create an attractive environment and career paths for developers and maintainers of research software. Concerning $E2$, (P3) is the baseline requirement for software identification which can lead to reuse and adaptation. (P4) is its own aspect of software sustainability: that the unique identifier (P3) for software, and ``metadata describing the software [\ldots] should persist --- even beyond the lifespan of the software they describe.'' (P5) is required to reuse and/or adapt software. Concerning reproducibility, (P6) is required to facilitate access to the specific software version that was used in a research process. \section{Software citation challenges} \noindent Useful and usable software citation faces the following challenges. Software citation is not yet a standard part of the research workflow for authors\label{challenge:authors} or software developers\label{challenge:developers}. Software also is still not always published in a way that enables citers to link to it in a citation.\label{challenge_publication} Furthermore, the curation and quality of citation-relevant metadata cannot yet be reliably ensured, while software citation is lacking adequate support from publishers, funders, and identifier and citation infrastructures.\label{challenge:stakeholder-support} Central to these challenges is the fact that software is not yet fully recognized as valuable research outcome, and the lack of realization that software work warrants credit through citation.\label{challenge:recognition} There is also no consensus on what contributions and roles are sufficient for credit, especially in larger, dynamic research software projects.\label{challenge:roles} These challenges need to be tackled at the policy, practice, and tooling levels, which is the subject of separate and future work. The FORCE11 Software Citation Implementation Working Group is pursuing the implementation of the software citation principles, and has identified further fundamental issues for software citation, and challenges for working with stakeholders~\cite{katzSoftwareCitationImplementation2019}. Some concern the different types and status of research software, and different means of identification for open or closed source software concepts as well as unpublished and published software. Others concern the scope, curation, format, and storage of software citation metadata, for all of which good working practices have not yet been found, decided upon, or established. A challenge for establishing software citation in the scholarly culture is to address relevant stakeholders: research domains mostly need guidance; publishers need policies, metadata schemas for software citation, and guidance for their own stakeholders; repositories need solutions for mixed software/data packages, and suitable metadata schemas and infrastructure to support software deposits; indexers need type systems for identifying software as such, and a concept and metrics for counting citations with respect to software versions and overarching concepts. Furthermore, research software that is not user-facing, such as dependencies, is often neglected in software citation, as researchers are not aware of their use of them.\label{challenge:transitive-credit} These challenges are both social and technical, and most challenges are interdependent: social challenges can best be overcome with the help of technical solutions, and technical solutions cannot be accomplished without a strong enough social mandate, which in turn requires a change in scholarly culture in the first place. \section{Existing solutions} \noindent Implementations and solutions that serve some of the software citation principles exist. (P1) and (P2) are served by ongoing arguments for the importance of software for research~\cite{anztEnvironmentSustainableResearch2020}, which find their way into policy~\cite{deutscheforschungsgemeinschaftGuidelinesSafeguardingGood2019}. (P3) and (P6) are served by existing platforms which publish software versions with a DOI~\cite{vandesandtPracticeMeetsPrinciple2019}. (P4) and (P5) are served by platforms and software registries that retain code, unique identifiers, and/or software metadata, and that publish software~\cite{vandesandtPracticeMeetsPrinciple2019,dicosmoSoftwareHeritageWhy2017}. Guidance exists for specific challenges, e.g., on software citation for (paper) authors~\cite{chuehongSoftwareCitationChecklist2019} and (software) developers~\cite{chuehongSoftwareCitationChecklist2019a}. Software papers are a more conservative, paper-like alternative to publication of software objects~\cite{smithJournalOpenSource2018}. Solutions to making dependencies visible and accessible for citation and credit are being developed, where users cite only the packages they use and those packages cite their dependencies~\cite{druskatSoftwareDependenciesResearch2020}~\cite[``Derived software'']{smithSoftwareCitationPrinciples2016}. Metadata schemas~\cite{jonesCodeMetaExchangeSchema2017} and formats~\cite{druskatCitationFileFormat2018}, as well as citation formats for software have been developed. And the FORCE11 Software Citation Implementation Working Group continues to work with stakeholders to establish good practices, and build a social mandate for the implementation of software citation. \subsection{Weaknesses} \noindent The ongoing implementation of and experience with solutions for software citation have exposed some weaknesses. Firstly, it is hard to create consensus about solutions across disciplines and stakeholders, implement them, and promote take-up. While the software citation needs of communities are known, the implementation of solutions is taking longer than has been hoped for. Some particular solutions also have their own weaknesses. For example, research software often does not have a final product that can be published; It is developed dynamically across many versions that each can be used and each may have their own correct set of (citation) metadata. This creates substantial overhead for developers and maintainers for the curation of software metadata. Simultaneously, unique identifiers cannot be assigned automatically to every revision and recorded in metadata before the revision is committed. This makes it hard to sync versions and metadata. This can partly be solved by archiving software with Software Heritage, which assigns unique identifiers to every revision/commit. With regard software citation metadata formats, there is no agreement which of the existing solutions~\cite{druskatCitationFileFormat2018,jonesCodeMetaExchangeSchema2017} should be used when and by which stakeholder group: While one aims to provide only citation-relevant metadata and targets mainly human users, the other is more generic and optimized for compatibility with web standards. This can be solved through compatibility, and existing conversion software \subsection{Strengths} Many solutions for software citation address real needs. Better software citation practice can close gaps in representing real world relations between research outputs, their impact, and the allocation of credit~\cite{druskatSoftwareDependenciesResearch2020}. This can lead to better career options for software developers and maintainers in academia, prevent brain drain towards industry, and thus sustain research software projects. Many solutions are developed by and for the community. For example, the FORCE11 Working Group is made up of software citation stakeholders and practitioners who know the needs of their communities and/or experience them first-hand. This will ideally lead to solutions that target the needs of communities. Finally, software citation can show and reward the impact of software on research, and incentivize the creation and maintenance of sustainable research software, which will enable replicability and reproducibility of research results. \bibliographystyle{IEEEtranDOI}
{'timestamp': '2021-03-12T02:24:37', 'yymm': '2103', 'arxiv_id': '2103.06681', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06681'}
arxiv
\section*{Appendix A. Proof} \label{Appendix:A} We now provide a complete proof of Theorem \ref{thm:sample_complexity}. The proof has four main components: a sub-optimality decomposition for error propagation across iterations, a Bellman error decomposition using a uniform convergence argument, a deviation analysis for least squares with deep ReLU networks using local Rademacher complexities and a localization argument, and a upper bound minimization step to obtain an optimal deep ReLU architecture. \subsubsection*{Step 1: A sub-optimality decomposition} The first step of the proof is a sub-optimality decomposition, stated in Lemma \ref{sub_opt_decompose}, that applies generally to any least-squares Q-iteration methods. \begin{lem}[\textit{A sub-optimality decomposition}] Under Assumption \ref{assumption:concentration_coefficient}, the sub-optimality of $V_K$ returned by Algorithm \ref{alg:LSVI} is bounded as \begin{align*} \text{SubOpt}(V_K) \leq \begin{cases} \frac{\sqrt{\kappa_{\mu}}}{1-\gamma} \displaystyle \max_{0 \leq k \leq K-1} \| Q_{k+1} - T^{\pi} Q_k \|_{\mu} + \frac{ \gamma^{K/2}}{(1-\gamma)^{1/2}} &\text{ for OPE}, \\ \frac{4 \gamma \sqrt{\kappa_{\mu}}}{(1-\gamma)^2} \displaystyle \max_{0 \leq k \leq K-1} \| Q_{k+1} - T^* Q_k \|_{\mu} + \frac{4 \gamma^{1 + K/2}}{(1-\gamma)^{3/2}} &\text{ for OPL}. \end{cases} \end{align*} where we denote $\|f\|_{\mu} := \sqrt{ \int \mu(ds da) f(s,a)^2 }, \forall f: \mathcal{S} \times \mathcal{A} \rightarrow \mathbb{R}$. \label{sub_opt_decompose} \end{lem} The lemma states that the sub-optimality decomposes into a statistical error (the first term) and an algorithmic error (the second term). While the algorithmic error enjoys the fast linear convergence rate, the statistical error arises from the distributional shift in the offline data and the estimation error of the target $Q$-value functions due to finite data. Crucially, the contraction of the (optimality) Bellman operators $T^{\pi}$ and $T^*$ allows the sup-optimality error at the final iteration $K$ to propagate across all iterations $k \in [0,K-1]$. Note that this result is agnostic to any function approximation form and does not require Assumption \ref{assumption:completeness}. The result uses a relatively standard argument that appears in a number of works on offline RL \citep{DBLP:journals/jmlr/MunosS08,DBLP:conf/icml/0002VY19}. \begin{proof}[Proof of Lemma \ref{sub_opt_decompose}] We will prove the sup-optimality decomposition for both settings: OPE and OPL. \noindent \textbf{(i) For OPE}. We denote the right-linear operator by $P^{\pi} \cdot : \{\mathcal{X} \rightarrow \mathbb{R} \} \rightarrow \{\mathcal{X} \rightarrow \mathbb{R} \}$ where \begin{align*} (P^{\pi}f)(s,a) := \int_{\mathcal{X}} f(s',a')\pi(da'|s') P(ds'|s,a), \end{align*} for any $f \in \{\mathcal{X} \rightarrow \mathbb{R} \}$. Denote Denote $\rho^{\pi}(ds da) = \rho(ds) \pi(da|s)$. Let $\epsilon_k := Q_{k+1} - T^{\pi} Q_k, \forall k \in [0,K-1]$ and $\epsilon_K = Q_0 - Q^{\pi}$. Since $Q^{\pi}$ is the (unique) fixed point of $T^{\pi}$, we have \begin{align*} Q_k - Q^{\pi} &= T^{\pi} Q_{k-1} - T^{\pi} Q^{\pi} + \epsilon_{k-1} = \gamma P^{\pi}(Q_{k-1} - Q^{\pi}) + \epsilon_{k-1}. \end{align*} By recursion, we have \begin{align*} Q_K - Q^{\pi} &= \sum_{k=0}^K (\gamma P^{\pi})^k \epsilon_k = \frac{1 - \gamma^{K+1}}{1 - \gamma} \sum_{k=0}^K \alpha_k A_k \epsilon_k \\ \end{align*} where $\alpha_k := \frac{(1-\gamma) \gamma^k}{1 - \gamma^{K+1}}, \forall k \in [K]$ and $A_k := (P^{\pi})^k, \forall k \in [K]$. Note that $\sum_{k=0}^K \alpha_k = 1$ and $A_k$'s are probability kernels. Denoting by $|f|$ the point-wise absolute value $|f(s,a)|$, we have that the following inequality holds point-wise: \begin{align*} |Q_K - Q^{\pi}| \leq \frac{1-\gamma^{K+1}}{1-\gamma} \sum_{k=0}^K \alpha_k A_k |\epsilon_k|. \end{align*} We have \begin{align*} \|Q_K - Q^{\pi}\|^2_{\rho^{\pi}} &\leq \frac{(1-\gamma^{K+1})^2}{(1-\gamma)^2} \int \rho(ds) \pi(da|s) \left( \sum_{k=0}^K \alpha_k A_k |\epsilon_k|(s,a)\right)^2 \\ &\overset{(a)}{\leq} \frac{(1-\gamma^{K+1})^2}{(1-\gamma)^2} \int \rho(ds) \pi(da|s) \sum_{k=0}^K \alpha_k A_k^2 \epsilon_k^2(s,a) \\ &\overset{(b)}{\leq} \frac{(1-\gamma^{K+1})^2}{(1-\gamma)^2} \int \rho(ds) \pi(da|s) \sum_{k=0}^K \alpha_k A_k \epsilon_k^2(s,a) \\ &\overset{(c)}{\leq} \frac{(1-\gamma^{K+1})^2}{(1-\gamma)^2} \left( \int \rho(ds) \pi(da|s) \sum_{k=0}^{K-1}\alpha_k A_k \epsilon_k^2(s,a) + \alpha_K \right) \\ &\overset{(d)}{\leq} \frac{(1-\gamma^{K+1})^2}{(1-\gamma)^2} \left( \int \mu(ds,da) \sum_{k=0}^{K-1} \alpha_k \kappa_{\mu} \epsilon_k^2(s,a) + \alpha_K \right) \\ &= \frac{(1-\gamma^{K+1})^2}{(1-\gamma)^2} \left(\sum_{k=0}^{K-1} \alpha_k \kappa_{\mu} \| \epsilon_k \|^2_{\mu} + \alpha_K \right) \\ & \leq \frac{\kappa_{\mu}}{(1 - \gamma)^2} \max_{0 \leq k \leq K-1} \| \epsilon_k \|_{\mu}^2 + \frac{\gamma^K}{(1 - \gamma)}. \end{align*} The inequalities $(a)$ and $(b)$ follow from Jensen's inequality, $(c)$ follows from $\|Q_0\|_{\infty}, \|Q^{\pi}\|_{\infty} \leq 1$, and $(d)$ follows from Assumption \ref{assumption:concentration_coefficient} that $\rho^{\pi} A_k = \rho^{\pi} (P^{\pi})^k \leq \kappa_{\mu} \mu$. Thus we have \begin{align*} \text{SubOpt}(V_K; \pi) &= |V_K - V^{\pi}| \nonumber \\ &= \bigg|\mathbb{E}_{\rho, \pi}[Q_K(s,a)] - \mathbb{E}_{\rho}[Q^{\pi}(s,a)] \bigg| \nonumber \\ &\leq \mathbb{E}_{\rho, \pi} \left[ |Q_K(s,a) - Q^{\pi}(s,a)| \right] \nonumber \\ &\leq \sqrt{ \mathbb{E}_{\rho, \pi} \left[ (Q_K(s,a) - Q^{\pi}(s,a))^2 \right] } \nonumber \\ &= \|Q_K - Q^{\pi}\|_{\rho^{\pi}} \nonumber \\ &\leq \frac{ \sqrt{\kappa_{\mu}} }{1-\gamma} \max_{0 \leq k \leq K-1} \| \epsilon_k \|_{\mu} + \frac{\gamma^{K/2}}{(1-\gamma)^{1/2}}. \end{align*} \noindent \textbf{(ii) For OPL}. The sup-optimality for the OPL setting is more complex than the OPE setting but the technical steps are relatively similar. In particular, let $\epsilon_{k-1} = T^* Q_{k-1} - Q_k, \forall k$ and $\pi^*(s) = \argmax_{a} Q^*(s,a), \forall s$, we have \begin{align} Q^* - Q_K &= T^{\pi^*} Q^* - T^{\pi^*} Q_{K-1} + \underbrace{T^{\pi^*} Q_{K-1} - T^* Q_{K-1}}_{\leq 0} + \epsilon_{K-1} \nonumber \\ &\leq \gamma P^{\pi^*} (Q^* - Q_{K-1}) + \epsilon_{K-1} \nonumber \\ &\leq \sum_{k=0}^{K-1} \gamma^{K-k-1} (P^{\pi^*})^{K-k-1} \epsilon_k + \gamma^{K} (P^{\pi^*})^K (Q^* - Q_0) (\text{by recursion}). \label{eq:upper_bound_Qstar_QK} \end{align} Now, let $\pi_k$ be the greedy policy w.r.t. $Q_k$, we have \begin{align} Q^* - Q_K &= \underbrace{T^{\pi^*} Q^*}_{\geq T^{\pi_{K-1}} Q^*} - T^{\pi_{K-1}} Q_{K-1} + \underbrace{T^{\pi_{K-1}} Q_{K-1} - T^* Q_{K-1}}_{\geq 0} + \epsilon_{K-1} \nonumber \\ &\geq \gamma P^{\pi_{K-1}}(Q^* - Q_{K-1}) + \epsilon_{K-1} \nonumber \\ &\geq \sum_{k=0}^{K-1} \gamma^{K - k -1} (P^{\pi_{K-1}} \ldots P^{\pi_{k+1}}) \epsilon_k + \gamma^K (P^{\pi_{K-1}} \ldots P^{\pi_0}) (Q^* - Q_0). \label{eq:lower_bound_Qstar_QK} \end{align} Now, we turn to decompose $Q^* - Q^{\pi_K}$ as \begin{align*} Q^* - Q^{\pi_K} &= (T^{\pi^*} Q^* - T^{\pi^*} Q_K) + \underbrace{(T^{\pi^*} Q_K - T^{\pi_K} Q_K)}_{\leq 0} + (T^{\pi_K} Q_K - T^{\pi_K} Q^{\pi_K}) \\ &\leq \gamma P^{\pi^*} (Q^* - Q_K) + \gamma P^{\pi_K}(Q_K - Q^* + Q^* - Q^{\pi_K}). \end{align*} Thus, we have \begin{align*} (I - \gamma P^{\pi_K}) (Q^* - Q^{\pi_K}) \leq \gamma (P^{\pi^*} - P^{\pi_K}) (Q^* - Q_K) . \end{align*} Note that the operator $(I - \gamma P^{\pi_K})^{-1} = \sum_{i=0}^{\infty} (\gamma P^{\pi_K})^i$ is monotone, thus \begin{align} Q^* - Q^{\pi_K} \leq \gamma (I - \gamma P^{\pi_K})^{-1} P^{\pi^*} (Q^* - Q_K) - \gamma (I - \gamma P^{\pi_K})^{-1} P^{\pi_K} (Q^* - Q_K). \label{eq:upper_bound_Qstar_QpiK} \end{align} Combining Equation (\ref{eq:upper_bound_Qstar_QpiK}) with Equations (\ref{eq:upper_bound_Qstar_QK}) and (\ref{eq:lower_bound_Qstar_QK}), we have \begin{align*} Q^* - Q^{\pi_K} &\leq (I - \gamma P^{\pi_K})^{-1} \left( \sum_{k=0}^{K-1} \gamma^{K-k} (P^{\pi^*})^{K-k} \epsilon_k + \gamma^{K+1} (P^{\pi^*})^{K+1} (Q^* - Q_0) \right) - \\ & (I - \gamma P^{\pi_K})^{-1} \left( \sum_{k=0}^{K-1} \gamma^{K - k} (P^{\pi_{K}} \ldots P^{\pi_{k+1}}) \epsilon_k + \gamma^{K+1} (P^{\pi_{K}} \ldots P^{\pi_0}) (Q^* - Q_0) \right). \end{align*} Using the triangle inequality, the above inequality becomes \begin{align*} Q^* - Q^{\pi_K} \leq \frac{2 \gamma (1 - \gamma^{K+1})}{(1 - \gamma)^2} \left( \sum_{k=0}^{K-1} \alpha_k A_k |\epsilon_k| + \alpha_K A_K |Q^* - Q_0| \right), \end{align*} where \begin{align*} A_k &= \frac{1-\gamma}{2} (I - \gamma P^{\pi_K})^{-1} \left( (P^{\pi^*})^{K-k} + P^{\pi_{K}} \ldots P^{\pi_{k+1}} \right), \forall k < K, \\ A_K &= \frac{1-\gamma}{2} (I - \gamma P^{\pi_K})^{-1} \left( (P^{\pi^*})^{K + 1} + P^{\pi_{K}} \ldots P^{\pi_0} \right), \\ \alpha_k &= \gamma^{K-k-1} (1- \gamma) / (1-\gamma^{K+1}), \forall k < K, \\ \alpha_K &= \gamma^K (1 - \gamma) / ( 1- \gamma^{K+1}). \end{align*} Note that $A_k$ is a probability kernel for all $k$ and $\sum_k \alpha_k = 1$. Thus, similar to the steps in the OPE setting, for any policy $\pi$, we have \begin{align*} \| Q^* - Q^{\pi_K} \|_{\rho^{\pi}}^2 &\leq \left[ \frac{2 \gamma (1 - \gamma^{K+1})}{(1 - \gamma)^2} \right]^2 \left( \int \rho(ds) \pi(da|s) \sum_{k=0}^{K-1}\alpha_k A_k \epsilon_k^2(s,a) + \alpha_K \right) \\ &\leq \left[ \frac{2 \gamma (1 - \gamma^{K+1})}{(1 - \gamma)^2} \right]^2 \left( \int \mu(ds,da) \sum_{k=0}^{K-1} \alpha_k \kappa_{\mu} \epsilon_k^2(s,a) + \alpha_K \right) \\ &= \left[ \frac{2 \gamma (1 - \gamma^{K+1})}{(1 - \gamma)^2} \right]^2 \left(\sum_{k=0}^{K-1} \alpha_k \kappa_{\mu} \| \epsilon_k \|^2_{\mu} + \alpha_K \right) \\ & \leq \frac{4 \gamma^2 \kappa_{\mu}}{(1 - \gamma)^4} \max_{0 \leq k \leq K-1} \| \epsilon_k \|_{\mu}^2 + \frac{ 4 \gamma^{K+2}}{(1 - \gamma)^3}. \end{align*} Thus, we have \begin{align*} \| Q^* - Q^{\pi_K} \|_{\rho^{\pi}} \leq \frac{2 \gamma \sqrt{\kappa_{\mu}}}{(1 - \gamma)^2} \max_{0 \leq k \leq K-1} \| \epsilon_k \|_{\mu} + \frac{ 2 \gamma^{K/2+1}}{(1 - \gamma)^{3/2}}. \end{align*} Finally, we have \begin{align*} \text{SubOpt}(\pi_K) &= \mathbb{E}_{\rho} \left[ Q^*(s, \pi^*(s)) - Q^*(s, \pi_K(s)) \right] \\ &\leq \mathbb{E}_{\rho} \left[ Q^*(s, \pi^*(s)) - Q^{\pi_K}(s, \pi^*(s)) + Q^{\pi_K}(s, \pi_K(s)) - Q^*(s, \pi_K(s)) \right] \\ &\leq \| Q^* - Q^{\pi_K} \|_{\rho^{\pi^*}} + \| Q^* - Q^{\pi_K} \|_{\rho^{\pi_K}} \\ &\leq \frac{4 \gamma \sqrt{\kappa_{\mu}}}{(1 - \gamma)^2} \max_{0 \leq k \leq K-1} \| \epsilon_k \|_{\mu} + \frac{ 4 \gamma^{K/2+1}}{(1 - \gamma)^{3/2}}. \end{align*} \end{proof} \subsubsection*{Step 2: A Bellman error decomposition} The next step of the proof is to decompose the Bellman errors $\| Q_{k+1} - T^{\pi} Q_k \|_{\mu}$ for OPE and $\| Q_{k+1} - T^* Q_k \|_{\mu}$ for OPL. Since these errors can be decomposed and bounded similarly, we only focus on OPL here. The difficulty in controlling the estimation error $\| Q_{k+1} - T^* Q_k \|_{2,\mu}$ is that $Q_k$ itself is a random variable that depends on the offline data $\mathcal{D}$. In particular, at any fixed $k$ with Bellman targets $\{y_i\}_{i=1}^n$ where $y_i = r_i + \gamma \max_{a'} Q_k(s_i', a')$, it is not immediate that $\mathbb{E}\left[ [T^* Q_k](x_i) - y_i | x_i \right] = 0$ for each covariate $x_i := (s_i, a_i)$ as $Q_k$ itself depends on $x_i$ (thus the tower law cannot apply here). A naive and simple approach to break such data dependency of $Q_k$ is to split the original data $\mathcal{D}$ into $K$ disjoint subsets and estimate each $Q_k$ using a separate subset. This naive approach is equivalent to the setting in \citep{DBLP:journals/corr/abs-1901-00137} where a fresh batch of data is generated for different iterations. This approach is however not efficient as it uses only $n/K$ samples to estimate each $Q_k$. This is problematic in high-dimensional offline RL when the number of iterations $K$ can be very large as it is often the case in practical settings. We instead prefer to use all $n$ samples to estimate each $Q_k$. This requires a different approach to handle the complicated data dependency of each $Q_k$. To circumvent this issue, we leverage a uniform convergence argument by introducing a deterministic covering of $T^* \mathcal{F}_{NN}$. Each element of the deterministic covering induces a different regression target $\{r_i + \gamma \max_{a'} \tilde{Q}(s'_i, a')\}_{i=1}^n$ where $\tilde{Q}$ is a deterministic function from the covering which ensures that $\mathbb{E}\left[ r_i + \gamma \max_{a'} \tilde{Q}(s'_i, a') - [T^* \tilde{Q}](x_i) | x_i\right] = 0$. In particular, we denote \begin{align*} y_i^{Q_k} = r_i + \gamma \max_{a'} Q_k(s'_i, a'), \forall i \text{ and } \hat{f}^{Q_k} := Q_{k+1} = \arginf_{f \in \mathcal{F}_{NN}} \sum_{i=1}^n l(f(x_i), y_i^{Q_k}), \text{ and } f_*^{Q_k} = T^* Q_k, \end{align*} where $l(x,y) = (x-y)^2$ is the squared loss function. Note that for any deterministic $Q \in \mathcal{F}_{NN}$, we have $f_*^Q(x_1) = \mathbb{E}[y_1^Q|x_1], \forall x_1$, thus \begin{align} \mathbb{E}(l_f - l_{f_*^Q}) = \| f - f_*^Q \|_{\mu}^2, \forall f, \label{eq:loss_to_norm} \end{align} where $l_f$ denotes the random variable $(f(x_1) - y_1^Q)^2$. Now letting $f_{\perp}^Q := \arginf_{f \in \mathcal{F}_{NN}} \|f - f_*^Q \|_{2, \mu}$ be the projection of $f_*^Q$ onto the function class $\mathcal{F}_{NN}$, we have \begin{align} \max_{k} \| Q_{k+1} - T^*Q_k \|_{\mu}^2 &= \max_{k} \| \hat{f}^{Q_{k}} - f_*^{Q_{k}} \|_{\mu}^2 \nonumber \overset{(a)}{\leq} \sup_{Q \in \mathcal{F}_{NN}} \| \hat{f}^{Q} - f_*^{Q} \|_{\mu}^2 \overset{(b)}{=} \sup_{Q \in \mathcal{F}_{NN}} \mathbb{E}(l_{\hat{f}^Q} - l_{f_*^Q}) \nonumber\\ &\overset{(c)}{\leq} \sup_{Q \in \mathcal{F}_{NN}} \left\{ \mathbb{E}(l_{\hat{f}^Q} - l_{f_*^Q}) + \mathbb{E}_n(l_{f_{\perp}^Q} - l_{\hat{f}^Q}) \right\} \nonumber \\ &= \sup_{Q \in \mathcal{F}_{NN}} \left\{ (\mathbb{E} - \mathbb{E}_n)(l_{\hat{f}^{Q}} - l_{f_*^{Q}}) + \mathbb{E}_n(l_{f_{\perp}^{Q}} - l_{f_*^{Q}}) \right \} \nonumber \\ &\leq \underbrace{\sup_{Q \in \mathcal{F}_{NN}} (\mathbb{E} - \mathbb{E}_n)(l_{\hat{f}^Q} - l_{f_*^Q})}_{I_1, \text{empirical process term}} + \underbrace{\sup_{Q \in \mathcal{F}_{NN}} \mathbb{E}_n(l_{f_{\perp}^Q} - l_{f_*^Q})}_{I_2, \text{bias term}}, \label{eq:decomposition} \end{align} where (a) follows from that $Q_{k} \in \mathcal{F}_{NN}$, (b) follows from Equation (\ref{eq:loss_to_norm}), and (c) follows from that $\mathbb{E}_n [l_{\hat{f}^Q}] \leq \mathbb{E}_n [l_{f^Q}], \forall f, Q \in \mathcal{F}_{NN}$. That is, the error is decomposed into two terms: the first term $I_1$ resembles the empirical process in statistical learning theory and the second term $I_2$ specifies the bias caused by the regression target $f_*^{Q}$ not being in the function space $\mathcal{F}_{NN}$. \subsubsection*{Step 3: A deviation analysis} The next step is to bound the empirical process term and the bias term via an intricate concentration, local Rademacher complexities and a localization argument. First, the bias term in Equation (\ref{eq:decomposition}) is taken uniformly over the function space, thus standard concentration arguments such as Bernstein's inequality and Pollard's inequality used in \citep{DBLP:journals/jmlr/MunosS08,DBLP:conf/icml/0002VY19} do not apply here. Second, local Rademacher complexities \citep{bartlett2005} are data-dependent complexity measures that exploit the fact that only a small subset of the function class will be used. Leveraging a localization argument for local Rademacher complexities \citep{farrell2018deep}, we localize an empirical Rademacher ball into smaller balls by which we can handle their complexities more effectively. Moreover, we explicitly use the sub-root function argument to derive our bound and extend the technique to the uniform convergence case. That is, reasoning over the sub-root function argument makes our proof more modular and easier to incorporate the uniform convergence argument. Localization is particularly useful to handle the complicated approximation errors induced by deep ReLU network function approximation. \subsubsection*{Step 3.a: Bounding the bias term via a uniform convergence concentration inequality} Before delving into our proof, we introduce relevant notations. Let $\mathcal{F} - \mathcal{G} := \{f - g: f \in \mathcal{F}, g \in \mathcal{G}\}$, let $N(\epsilon, \mathcal{F}, \| \cdot \|)$ be the $\epsilon$-covering number of $\mathcal{F}$ w.r.t. $\| \cdot \|$ norm, $H(\epsilon, \mathcal{F}, \| \cdot \|) := \log N(\epsilon, \mathcal{F}, \| \cdot \|)$ be the entropic number, let $N_{[]}(\epsilon, \mathcal{F}, \|\cdot\|)$ be the bracketing number of $\mathcal{F}$, i.e., the minimum number of brackets of $\|\cdot\|$-size less than or equal to $\epsilon$, necessary to cover $\mathcal{F}$, let $H_{[]}(\epsilon, \mathcal{F}, \|\cdot\|) = \log N_{[]}(\epsilon, \mathcal{F}, \|\cdot\|)$ be the $\|\cdot\|$-bracketing metric entropy of $\mathcal{F}$,let $\mathcal{F} | \{x_i\}_{i=1}^n = \{(f(x_1), ..., f(x_n)) \in \mathbb{R}^n | f \in \mathcal{F}\}$, and let $T^* \mathcal{F} = \{T^* f: f \in \mathcal{F}\}$. Finally, for sample set $\{x_i\}_{i=1}^n$, we define the empirical norm $\|f\|_n := \sqrt{\frac{1}{n}\sum_{i=1}^n f(x_i)^2}$. We define the inherent Bellman error as $d_{\mathcal{F}_{NN}} := \sup_{Q \in \mathcal{F}_{NN}} \inf_{f \in \mathcal{F}_{NN}} \| f - T^* Q\|_{\mu}$. This implies that \begin{align} d_{\mathcal{F}_{NN}}^2 := \sup_{Q \in \mathcal{F}_{NN}} \inf_{f \in \mathcal{F}_{NN}} \| f - T^* Q\|_{\mu}^2 = \sup_{Q \in \mathcal{F}_{NN}} \mathbb{E}(l_{f_{\perp}^Q} - l_{f_*^Q}). \end{align} We have \begin{align*} |l_f - l_g| \leq 4 |f-g| \text{ and } |l_f - l_g| \leq 8 . \end{align*} We have \begin{align*} &H(\epsilon, \{l_{f_{\perp}^Q} - l_{f_*^Q}: Q \in \mathcal{F}_{NN}\}| \{x_i, y_i\}_{i=1}^n, n^{-1} \| \cdot \|_1 ) \\ &\leq H(\frac{\epsilon}{4}, \{f_{\perp}^Q - f_*^Q: Q \in \mathcal{F}_{NN}\}| \{x_i\}_{i=1}^n, n^{-1} \| \cdot \|_1 ) \\ &\leq H(\frac{\epsilon}{4 }, (\mathcal{F} - T^* \mathcal{F}_{NN})| \{x_i \}_{i=1}^n, n^{-1} \| \cdot \|_1 ) \\ &\leq H(\frac{\epsilon}{8 }, \mathcal{F}_{NN}| \{x_i\}_{i=1}^n, n^{-1} \| \cdot \|_1) + H(\frac{\epsilon}{8 }, T^* \mathcal{F}_{NN}| \{x_i\}_{i=1}^n, n^{-1} \| \cdot \|_1 ) \\ &\leq H(\frac{\epsilon}{8 }, \mathcal{F}_{NN}| \{x_i\}_{i=1}^n, \| \cdot \|_{\infty}) + H(\frac{\epsilon}{8 }, T^* \mathcal{F}_{NN}, \| \cdot \|_{\infty}) \end{align*} For any $\epsilon' > 0$ and $\delta' \in (0,1)$, it follows from Lemma \ref{lemma:sup_concentration} with $\epsilon = 1/2$ and $\alpha = \epsilon'^2$, with probability at least $1 - \delta'$, for any $Q \in \mathcal{F}_{NN}$, we have \begin{align} \mathbb{E}_n(l_{f_{\perp}^Q} - l_{f_*^Q}) \leq 3 \mathbb{E}(l_{f_{\perp}^Q} - l_{f_*^Q}) + \epsilon'^2 \leq 3 d_{\mathcal{F}_{NN}}^{2} + \epsilon'^2, \label{eq:bound_E_minus_En_lf_minus_lfstar} \end{align} given that \begin{align*} n \approx \frac{1}{\epsilon'^2}\left( \log(4/\delta') + \log \mathbb{E} N(\frac{\epsilon'^2}{40 }, (\mathcal{F}_{NN} - T^* \mathcal{F}_{NN})| \{x_i\}_{i=1}^n, n^{-1} \| \cdot \|_1) \right) . \end{align*} Note that if we use Pollard's inequality \citep{DBLP:journals/jmlr/MunosS08} in the place of Lemma \ref{lemma:sup_concentration}, the RHS of Equation (\ref{eq:bound_E_minus_En_lf_minus_lfstar}) is bounded by $\epsilon'$ instead of $\epsilon'^2$(i.e., $n$ scales with $O(1/\epsilon'^4)$ instead of $O(1/\epsilon'^2)$). In addition, unlike \citep{DBLP:conf/icml/0002VY19}, the uniform convergence argument hinders the application of Bernstein's inequality. We remark that \citealt{DBLP:conf/icml/0002VY19} makes a mistake in their proof by ignoring the data-dependent structure in the algorithm (i.e., they wrongly assume that $Q^k$ in Algorithm \ref{alg:LSVI} is fixed and independent of $\{s_i, a_i\}_{i=1}^n$). Thus, the uniform convergence argument in our proof is necessary. \subsubsection*{Step 3.b: Bounding the empirical process term via local Rademacher complexities} For any $Q \in \mathcal{F}_{NN}$, we have \begin{align*} |l_{f_{\perp}^Q} - l_{f_*^Q}| &\leq 2 |f_{\perp}^Q - f_*^Q| \leq 2, \\ \mathbb{V}[l_{f_{\perp}^Q} - l_{f_*^Q}] &\leq \mathbb{E}[(l_{f_{\perp}^Q} - l_{f_*^Q})^2] \leq 4 \mathbb{E} (f_{\perp}^Q - f_*^Q)^2. \end{align*} Thus, it follows from Lemma \ref{lemma:local_rademacher_complexity_basics_first_part} (with $\alpha = 1/2$) that with any $r > 0, \delta \in (0,1)$, with probability at least $1 - \delta$, we have \begin{align*} &\sup \{(\mathbb{E} - \mathbb{E}_n)(l_{\hat{f}^Q} - l_{f_*^Q}): Q \in \mathcal{F}_{NN}, \|\hat{f}^Q - f_*^Q\|^2_{\mu} \leq r \} \\ &\leq \sup \{(\mathbb{E} - \mathbb{E}_n)(l_f - l_g): f \in \mathcal{F}_{NN}, g \in T^{*} \mathcal{F}, \|f - g\|^2_{\mu} \leq r \} \\ &\leq 3 \mathbb{E} R_n \left\{l_f - l_g: f \in \mathcal{F}_{NN}, g \in T^{*} \mathcal{F}_{NN}, \|f - g \|_{\mu}^2 \leq r \right \} + 2 \sqrt{ \frac{2 r \log(1/\delta) }{n} } + \frac{28 \log(1/\delta)}{3n} \nonumber \\ &\leq 6 \mathbb{E} R_n \left\{f - g: f \in \mathcal{F}_{NN}, g \in T^{*} \mathcal{F}_{NN}, \|f - g \|_{\mu}^2 \leq r \right \} + 2 \sqrt{ \frac{2 r \log(1/\delta) }{n} } + \frac{28 \log(1/\delta)}{3n}. \end{align*} \subsubsection*{Step 3.c: Bounding $\|Q_{k+1} - T^* Q_k\|_{\mu}$ using localization argument via sub-root functions} We bound $\|Q_{k+1} - T^* Q_k \|_{\mu}$ using the localization argument, breaking down the Rademacher complexities into local balls and then build up the original function space from the local balls. Let $\psi$ be a sub-root function \citep[Definition~3.1]{bartlett2005} with the fixed point $r_*$ and assume that for any $ r \geq r_*$, we have \begin{align} \psi(r) \geq 3 \mathbb{E} R_n \left\{f - g: f \in \mathcal{F}_{NN}, g \in T^{*} \mathcal{F}_{NN}, \|f - g \|_{\mu}^2 \leq r \right \}. \label{eq:sub_root_function_bounding_empirical_Rademacher} \end{align} We recall that a function $\psi: [0, \infty) \rightarrow [0, \infty)$ is \textit{sub-root} if it is non-negative, non-decreasing and $r \mapsto \psi(r) / \sqrt{r}$ is non-increasing for $r > 0$. Consequently, a sub-root function $\psi$ has a unique fixed point $r_*$ where $r_* = \psi(r_*)$. In addition, $\psi(r) \leq \sqrt{r r_*}, \forall r \geq r_*$. In the next step, we will find a sub-root function $\psi$ that satisfies the inequality above, but for this step we just assume that we have such $\psi$ at hand. Combining Equations (\ref{eq:decomposition}), (\ref{eq:bound_E_minus_En_lf_minus_lfstar}), and (\ref{eq:sub_root_function_bounding_empirical_Rademacher}), we have: for any $r \geq r_*$ and any $\delta \in (0,1)$, if $\| \hat{f}^{Q_{k-1}} - f_*^{Q_{k-1}} \|_{2,\mu}^2 \leq r$, with probability at least $1 - \delta$, \begin{align*} \| \hat{f}^{Q_{k-1}} - f_*^{Q_{k-1}} \|_{2,\mu}^2 &\leq 2\psi(r) + 2 \sqrt{ \frac{2 r \log(2/\delta) }{n} } + \frac{28 \log(2/\delta)}{3n} + 3 d^2_{\mathcal{F}} + \epsilon'^2 \\ &\leq \sqrt{r r_*} + 2 \sqrt{ \frac{2 r \log(2/\delta)}{n} } + \frac{28 \log(2/\delta)}{3n} + (\sqrt{3} d_{\mathcal{F}} + \epsilon' )^2, \end{align*} where \begin{align*} n \approx \frac{1}{4\epsilon'^2}\left( \log(8/\delta) + \log \mathbb{E} N(\frac{\epsilon'^2}{20}, (\mathcal{F}_{NN} - T^* \mathcal{F}_{NN})| \{x_i\}_{i=1}^n, n^{-1}\| \cdot \|_1) \right). \end{align*} Consider $r_0 \geq r_*$ (to be chosen later) and denote the events \begin{align*} B_k := \{ \| \hat{f}^{Q_{k-1}} - f_*^{Q_{k-1}} \|^2_{2,\mu} \leq 2^k r_0 \}, \forall k \in \{0,1,...,l\}, \end{align*} where $l = \log_2(\frac{1}{r_0}) \leq \log_2( \frac{1}{r_*} )$. We have $B_0 \subseteq B_1 \subseteq ... \subseteq B_l$ and since $\|f - g\|_{\mu}^2 \leq 1, \forall |f|_{\infty}, |g|_{\infty} \leq 1$, we have $P(B_l) = 1$. If $\|\hat{f}^{Q_{k-1}} - f_*^{Q_{k-1}} \|^2_{\mu} \leq 2^i r_0$ for some $i \leq l$, then with probability at least $1 - \delta$, we have \begin{align*} \| \hat{f}^{Q_{k-1}} - f_*^{Q_{k-1}} \|_{2,\mu}^2 &\leq \sqrt{2^i r_0 r_*} + 2 \sqrt{ \frac{2^{i+1} r_0 \log(2/\delta)}{n} } + \frac{28 \log(2/\delta)}{3n} + (\sqrt{3} d_{\mathcal{F}_{NN}} + \epsilon' )^2 \\ &\leq 2^{i-1} r_0, \end{align*} if the following inequalities hold \begin{align*} \sqrt{ 2^i r_*} + 2\sqrt{ \frac{2^{i+1} \log(2/\delta)}{n} } &\leq \frac{1}{2} 2^{i-1} \sqrt{r_0}, \\ \frac{28 \log(2/\delta)}{3n} + (\sqrt{3} d_{\mathcal{F}_{NN}} + \epsilon' )^2 &\leq \frac{1}{2} 2^{i-1} r_0. \end{align*} We choose $r_0 \geq r_*$ such that the inequalities above hold for all $0 \leq i \leq l$. This can be done by simply setting \begin{align*} \sqrt{r_0} &= \frac{2}{2^{i-1}} \left( \sqrt{ 2^i r_*} + 2\sqrt{ \frac{2^{i+1} \log(2/\delta) }{n} } \right) \bigg |_{i=0} + \sqrt{ \frac{2}{2^{i-1}} \left( \frac{28 \log(2/\delta)}{3n} + (\sqrt{3} d_{\mathcal{F}_{NN}} + \epsilon' )^2 \right) } \bigg |_{i=0} \\ &\lesssim d_{\mathcal{F}_{NN}} + \epsilon' + \sqrt{\frac{\log(2/\delta)}{n}} + \sqrt{r_*}. \end{align*} Since $\{B_i\}$ is a sequence of increasing events, we have \begin{align*} P(B_0) &= P(B_1) - P(B_1 \cap B_0^c ) = P(B_2) - P(B_2 \cap B_1^c) - P(B_1 \cap B_0^c) \\ &=P(B_l) - \sum_{i=0}^{l-1} P(B_{i+1} \cap B_i^c) \geq 1 - l \delta. \end{align*} Thus, with probability at least $1 - \delta$, we have \begin{equation} \| \hat{f}^{Q_{k-1}} - f_*^{Q_{k-1}} \|_{\mu} \lesssim d_{\mathcal{F}_{NN}} + \epsilon' + \sqrt{\frac{\log(2l/\delta)}{n}} + \sqrt{r_*} \label{eq:general_bounding} \end{equation} where \begin{align*} n \approx \frac{1}{4\epsilon'^2}\left( \log(8l/\delta) + \log \mathbb{E} N(\frac{\epsilon'^2}{20}, (\mathcal{F}_{NN} - T^* \mathcal{F}_{NN})| \{x_i\}_{i=1}^n, n^{-1}\| \cdot \|_1)) \right) . \end{align*} \subsubsection*{Step 3.d: Finding a sub-root function and its fixed point} It remains to find a sub-root function $\psi(r)$ that satisfies Equation (\ref{eq:sub_root_function_bounding_empirical_Rademacher}) and thus its fixed point. The main idea is to bound the RHS, the local Rademacher complexity, of Equation (\ref{eq:sub_root_function_bounding_empirical_Rademacher}) by its empirical counterpart as the latter can then be further bounded by a sub-root function represented by a measure of compactness of the function spaces $\mathcal{F}_{NN}$ and $T^{*}\mathcal{F}_{NN}$. For any $\epsilon > 0$, we have the following inequalities for entropic numbers: \begin{align} H(\epsilon, \mathcal{F}_{NN} - T^* \mathcal{F}_{NN}, \| \cdot \|_{n}) &\leq H(\epsilon/2, \mathcal{F}_{NN}, \| \cdot \|_{n}) + H(\epsilon/2, T^* \mathcal{F}_{NN}, \| \cdot \|_{n}), \nonumber \\ H(\epsilon, \mathcal{F}_{NN}, \|\cdot\|_{n}) &\leq H(\epsilon, \mathcal{F}_{NN}| \{x_i\}_{i=1}^n, \| \cdot \|_{\infty}) \overset{(a)}{\lesssim} N[ (\log N)^2 + \log(1/\epsilon)], \\ H(\epsilon, T^* \mathcal{F}_{NN}, \|\cdot \|_{n}) &\leq H(\epsilon, T^* \mathcal{F}_{NN}, \| \cdot \|_{\infty}) \leq H_{[]}(2 \epsilon, T^*\mathcal{F}_{NN}, \| \cdot \|_{\infty}) \nonumber \\ &\overset{(b)}{\leq} H_{[]}(2\epsilon, \bar{B}^{\alpha}_{p,q}(\mathcal{X}), \| \cdot \|_{\infty}) \overset{(c)}{\lesssim} (2\epsilon)^{-d/\alpha}, \end{align} where $N$ is a hyperparameter of the deep ReLU network described in Lemma \ref{lemma:approximation_power_for_Besov}, (a) follows from Lemma \ref{lemma:approximation_power_for_Besov}, and (b) follows from Assumption \ref{assumption:completeness}, and (c) follows from Lemma \ref{lemma:entropic_number_of_Besov}. Let $\mathcal{H} := \mathcal{F}_{NN} - T^{*} \mathcal{F}_{NN}$, it follows from Lemma \ref{lemma:refined_entropy_integral} with $\{\xi_k := \epsilon / 2^k\}_{k \in \mathbb{N}}$ for any $\epsilon > 0$ that \begin{align*} &\mathbb{E}_{\sigma} R_n \{ h \in \mathcal{H} - \mathcal{H}: \|h\|_{n} \leq \epsilon \} \leq 4 \sum_{k=1}^{\infty} \frac{\epsilon}{2^{k-1}} \sqrt{ \frac{H(\epsilon/2^{k-1}, \mathcal{H}, \| \cdot \|_{n})}{n} } \nonumber \\ &\leq 4 \sum_{k=1}^{\infty} \frac{\epsilon}{2^{k-1}} \sqrt{ \frac{H(\epsilon/2^{k}, \mathcal{F}_{NN}, \| \cdot \|_{\infty})}{n} } + 4 \sum_{k=1}^{\infty} \frac{\epsilon}{2^{k-1}} \sqrt{ \frac{H(\epsilon/2^{k}, T^{\pi} \mathcal{F}_{NN}, \| \cdot \|_{\infty})}{n} } \\ &\leq \frac{4 \epsilon}{\sqrt{n}} \sum_{k=1}^{\infty} 2^{-(k-1)} \sqrt{N \left( (\log N)^2 + \log(2^k/\epsilon) \right)} + \frac{4 \epsilon}{\sqrt{n}} \sum_{k=1}^{\infty} 2^{-(k-1)} \sqrt{\left(\frac{\epsilon}{2^{k-1}} \right)^{-d/\alpha}} \\ &\lesssim \frac{\epsilon}{\sqrt{n}} \sqrt{N ((\log N)^2 + \log(1/\epsilon))} + \frac{\epsilon^{1 - \frac{d}{2 \alpha}}}{\sqrt{n}}, \end{align*} where we use $\sqrt{a + b} \leq \sqrt{a} + \sqrt{b}, \forall a,b \geq 0$, $\sum_{k=1}^{\infty} \frac{\sqrt{k}}{2^{k-1}} < \infty$, and $\sum_{k=1}^{\infty} \left( \frac{1}{2^{1 - \frac{d}{2 \alpha}}} \right)^{k-1} < \infty$. It now follows from Lemma \ref{lemma:local_empirical_rademacher_bounded_by_covering_number_with_empirical_norm} that \begin{align*} &\mathbb{E}_{\sigma} R_n \{f \in \mathcal{F}, g \in T^{*} \mathcal{F}: \| f -g \|_{n}^2 \leq r \} \\ &\leq \inf_{\epsilon > 0} \bigg[ \mathbb{E}_{\sigma} R_n \{ h \in \mathcal{H} - \mathcal{H}: \| h \|_{\mu} \leq \epsilon \} + \sqrt{ \frac{2r H(\epsilon/2, \mathcal{H}, \|\cdot \|_{n}) }{n} } \bigg] \\ &\lesssim \bigg[ \frac{\epsilon}{\sqrt{n}} \sqrt{N ((\log N)^2 + \log(1/\epsilon))} + \frac{\epsilon^{1 - \frac{d}{2 \alpha}}}{\sqrt{n}} + \sqrt{\frac{2r}{n}} \sqrt{N((\log N)^2 + \log(4 /\epsilon))} + \sqrt{\frac{2r}{n}}(\epsilon/2)^{\frac{-d}{2 \alpha}} \bigg] \bigg |_{\epsilon = n^{-\beta}}\\ &\asymp n^{-\beta -1/2} \sqrt{N (\log^2 N + \log n )} + n^{-\beta(1 - \frac{d}{2 \alpha}) - 1/2} + \sqrt{\frac{r}{n}} \sqrt{N (\log^2 N + \log n )} + \sqrt{r} n^{-\frac{1}{2}(1 - \frac{\beta d}{\alpha})} =: \psi_1(r), \end{align*} where $\beta \in (0, \frac{\alpha}{d})$ is an absolute constant to be chosen later. Note that $\mathbb{V}[(f-g)^2] \leq \mathbb{E}[(f-g)^4] \leq \mathbb{E}[(f-g)^2]$ for any $f \in \mathcal{F}_{NN}, g \in T^* \mathcal{F}_{NN}$. Thus, for any $r \geq r_*$, it follows from Lemma \ref{lemma:local_rademacher_complexity_basics} that with probability at least $1 - \frac{1}{n}$, we have the following inequality for any $f \in \mathcal{F}_{NN}, g \in T^* \mathcal{F}_{NN}$ such that $\|f - g\|^2_{\mu} \leq r$, \begin{align*} &\|f - g\|_{n}^2 \\ &\leq \|f - g \|^2_{\mu} + 3 \mathbb{E} R_n \{(f-g)^2: f \in \mathcal{F}_{NN}, g \in T^* \mathcal{F}_{NN}, \| f - g \|^2_{\mu} \leq r\} + \sqrt{ \frac{2r \log n}{n} } + \frac{56}{3} \frac{\log n}{n} \\ &\leq \|f - g \|^2_{\mu} + 3 \mathbb{E} R_n \{f-g: f \in \mathcal{F}_{NN}, g \in T^* \mathcal{F}_{NN}, \| f - g \|^2_{\mu} \leq r\} + \sqrt{ \frac{2r \log n }{n} } + \frac{56}{3} \frac{\log n}{n} \\ &\leq r + \psi(r) + r + r \leq 4r, \end{align*} if $r \geq r_* \lor \frac{2 log n}{n} \lor \frac{56 log n}{3 n}$. For such $r$, denote $E_r = \{ \| f - g \|_{n}^2 \leq 4r \} \cap \{\|f - f_*\|_{\mu}^2 \leq r \}$, we have $P(E_r) \geq 1 - 1/n$ and \begin{align*} &3 \mathbb{E} R_n \{f - g: f \in \mathcal{F}_{NN}, g \in T^* \mathcal{F}_{NN}, \|f - g\|^2_{\mu} \leq r \} \\ &= 3 \mathbb{E} \mathbb{E}_{\sigma} R_n \{f - g: f \in \mathcal{F}_{NN}, g \in T^{*} \mathcal{F}_{NN}, \|f - g\|^2_{\mu} \leq r \} \\ &\leq 3 \mathbb{E} \bigg[ 1_{E_r} \mathbb{E}_{\sigma} R_n \{f - g: f \in \mathcal{F}_{NN}, g \in T^* \mathcal{F}_{NN}, \|f - g\|^2_{\mu} \leq r \} + (1 - 1_{E_r}) \bigg] \\ &\leq 3 \mathbb{E} \bigg[ \mathbb{E}_{\sigma} R_n \{f - g: f \in \mathcal{F}_{NN}, g \in T^* \mathcal{F}_{NN}, \|f - g\|^2_{n} \leq 4r \} + (1 - 1_{E_r}) \bigg] \\ &\leq 3( \psi_1(4r) + \frac{1}{n}) \\ &\lesssim n^{-\beta -1/2} \sqrt{N (\log^2 N + \log n )} + n^{-\beta(1 - \frac{d}{2 \alpha}) - 1/2} + \sqrt{\frac{r}{n}} \sqrt{N (\log^2 N + \log n )} \\ &+ \sqrt{r} n^{-\frac{1}{2}(1 - \frac{\beta d}{\alpha})} + n^{-1} =: \psi(r) \end{align*} It is easy to verify that $\psi(r)$ defined above is a sub-root function. The fixed point $r_*$ of $\psi(r)$ can be solved analytically via the simple quadratic equation $r_* = \psi(r_*)$. In particular, we have \begin{align} \sqrt{r_*} &\lesssim n^{-1/2} \sqrt{N (\log^2 N + \log n )} + n^{-\frac{1}{2}(1 - \frac{\beta d}{\alpha})} + n^{-\frac{\beta}{2} - \frac{1}{4}} [N (\log^2 N + \log n )]^{1/4} \nonumber \\ &+ n^{-\frac{\beta}{2}(1 - \frac{d}{2 \alpha}) - \frac{1}{2}} + n^{-1/2} \nonumber \\ &\lesssim n^{-\frac{1}{4} ( (2\beta) \land 1) + 1)} \sqrt{N (\log^2 N + \log n )} + n^{-\frac{1}{2}(1 - \frac{\beta d}{\alpha})} + n^{-\frac{\beta}{2}(1 - \frac{d}{2 \alpha}) - \frac{1}{2}} + n^{-1/2} \label{eq:sandwich_fixed_point} \end{align} It follows from Equation (\ref{eq:general_bounding}) (where $l \lesssim \log(1/r_*)$), the definition of $d_{\mathcal{F}_{NN}}$, Lemma \ref{lemma:approximation_power_for_Besov}, and Equation (\ref{eq:sandwich_fixed_point}) that for any $\epsilon' >0$ and $\delta \in (0,1)$, with probability at least $1 - \delta$, we have \begin{align} \max_{k} \|Q_{k+1} - T^* Q_k \|_{\mu} &\lesssim N^{-\alpha / d} + \epsilon' + n^{-\frac{1}{4} ( (2\beta) \land 1) + 1)} \sqrt{N (\log^2 N + \log n )} + n^{-\frac{1}{2}(1 - \frac{\beta d}{\alpha})} \nonumber \\ &+ n^{-\frac{\beta}{2}(1 - \frac{d}{2 \alpha}) - \frac{1}{2}} + n^{-1/2}\sqrt{\log(1/\delta) + \log \log n } \label{eq:final_parametric_upper_bound} \end{align} where \begin{align} n &\gtrsim \frac{1}{4\epsilon'^2}\bigg( \log(1/\delta) + \log \log n + \log \mathbb{E} N(\frac{\epsilon'^2}{20}, (\mathcal{F}_{NN} - T^* \mathcal{F}_{NN})| \{x_i\}_{i=1}^n, n^{-1} \cdot \| \cdot \|_1)) \bigg) . \label{eq:sample_complexity_n} \end{align} \subsubsection*{Step 4: Minimizing the upper bound} The final step for the proof is to minimize the upper error bound obtained in the previous steps w.r.t. two free parameters $\beta \in (0, \frac{\alpha}{d})$ and $N \in \mathbb{N}$. Note that $N$ parameterizes the deep ReLU architecture $\Phi(L,m,S,B)$ given Lemma \ref{lemma:approximation_power_for_Besov}. In particular, we optimize over $\beta \in (0, \frac{\alpha}{d})$ and $N \in \mathbb{N}$ to minimize the upper bound in the RHS of Equation (\ref{eq:final_parametric_upper_bound}). The RHS of Equation (\ref{eq:final_parametric_upper_bound}) is minimized (up to $\log n$-factor) by choosing \begin{align} N \asymp n^{\frac{1}{2}((2 \beta \land 1) + 1) \frac{d}{2\alpha + d}} \text{ and } \beta = \left(2 + \frac{d^2}{\alpha (\alpha + d)} \right)^{-1}, \label{eq:optimal_value_N_beta} \end{align} which results in $N \asymp n^{\frac{1}{2}(2 \beta + 1) \frac{d}{2\alpha + d}}$. At these optimal values, Equation (\ref{eq:final_parametric_upper_bound}) becomes \begin{align} \max_{k} \|Q_{k+1} - T^* Q_k\|_{\mu} &\lesssim \epsilon' + n^{-\frac{1}{2}\left( \frac{2 \alpha}{2 \alpha + d} + \frac{d}{ \alpha} \right)^{-1}} \log n + n^{-1/2}\sqrt{\log(1/\delta) + \log \log n }, \label{eq:final_upper_bound} \end{align} where we use inequalities $n^{-\frac{\beta}{2}(1 - \frac{d}{2 \alpha}) - \frac{1}{2}} \leq n^{-\frac{1}{2}(1 - \frac{\beta d}{\alpha})} \asymp N^{-\alpha /d} = n^{-\frac{1}{2}\left( \frac{2 \alpha}{2 \alpha + d} + \frac{d}{ \alpha} \right)^{-1}} $. Now, for any $\epsilon > 0$, we set $\epsilon' = \epsilon/3$ and let \begin{align*} n^{-\frac{1}{2}\left( \frac{2 \alpha}{2 \alpha + d} + \frac{d}{ \alpha} \right)^{-1}} \log n \lesssim \epsilon / 3 \text{ and } n^{-1/2}\sqrt{\log(1/\delta) + \log \log n } \lesssim \epsilon / 3. \end{align*} It then follows from Equation (\ref{eq:final_upper_bound}) that with probability at least $1 - \delta$, we have $\max_{k} \| Q_{k+1} - T^* Q_k \|_{\mu} \leq \epsilon$ if $n$ simultaneously satisfies Equation (\ref{eq:sample_complexity_n}) with $\epsilon' = \epsilon/3$ and \begin{align} n \gtrsim \left(\frac{1}{\epsilon^2} \right)^{ \frac{2 \alpha}{ 2 \alpha + d} + \frac{d}{\alpha}} (\log^2 n)^{ \frac{2 \alpha}{ 2 \alpha + d}+ \frac{d}{\alpha}} \text{ and } n \gtrsim \frac{1}{\epsilon^2} \left( \log(1/\delta) + \log \log n \right). \label{eq:explicit_n_1} \end{align} Next, we derive an explicit formula of the sample complexity satisfying Equation (\ref{eq:sample_complexity_n}). Using Equations (\ref{eq:final_parametric_upper_bound}), (\ref{eq:explicit_n_1}), and (\ref{eq:optimal_value_N_beta}), we have that $n$ satisfies Equation (\ref{eq:sample_complexity_n}) if \begin{align} \begin{cases} n &\gtrsim \frac{1}{\epsilon^2} \left[ n^{\frac{2\beta + 1}{2} \frac{d}{2 \alpha + d}} (\log^2 n + \log(1/\epsilon))\right], \\ n &\gtrsim \left( \frac{1}{\epsilon^2} \right)^{1 + \frac{d}{\alpha}}, \\ n &\gtrsim \frac{1}{\epsilon^2} \left( \log(1/\delta) + \log \log n \right). \end{cases} \label{eq:explicit_n_2} \end{align} Note that $\beta \leq 1/2$ and $\frac{d}{\alpha} \leq 2$; thus, we have \begin{align*} \left(1 - \frac{2\beta + 1}{2} \frac{d}{2 \alpha + d} \right)^{-1} \leq 1 + \frac{d}{\alpha} \leq 3. \end{align*} Hence, $n$ satisfies Equations (\ref{eq:explicit_n_1}) and (\ref{eq:explicit_n_2}) if \begin{align*} n \gtrsim \left(\frac{1}{\epsilon^2} \right)^{1 + \frac{d}{\alpha}} \log^6 n + \frac{1}{\epsilon^2}(\log(1/\delta) + \log \log n). \end{align*} \section*{Appendix B. Technical Lemmas} \label{appendix:B} \begin{lem}[\citet{bartlett2005}] Let $r > 0$ and let \begin{align*} \mathcal{F} \subseteq \{f: \mathcal{X} \rightarrow [a,b] : \mathbb{V}[f(X_1)] \leq r\}. \end{align*} \begin{enumerate} \item For any $\lambda > 0$, we have with probability at least $1 - e^{-\lambda}$, \begin{align*} \sup_{f \in \mathcal{F}} \left(\mathbb{E}f - \mathbb{E}_n f \right) \leq \inf_{\alpha >0 } \left( 2(1+\alpha) \mathbb{E} \left[R_n \mathcal{F} \right] + \sqrt{ \frac{2 r \lambda}{ n}} + (b-a)\left(\frac{1}{3} + \frac{1}{\alpha} \right)\frac{\lambda}{n} \right). \end{align*} \label{lemma:local_rademacher_complexity_basics_first_part} \item With probability at least $1 - 2 e^{-\lambda}$, \begin{align*} \sup_{f \in \mathcal{F}} \left(\mathbb{E}f - \mathbb{E}_n f \right) \leq \inf_{\alpha \in (0,1) } \left( \frac{2(1+\alpha)}{(1 - \alpha)} \mathbb{E}_{\sigma} \left[R_n \mathcal{F} \right] + \sqrt{ \frac{2 r \lambda}{ n}} + (b-a)\left(\frac{1}{3} + \frac{1}{\alpha} + \frac{1 + \alpha}{2 \alpha (1 - \alpha)} \right)\frac{\lambda}{n} \right). \end{align*} \end{enumerate} Moreover, the same results hold for $\sup_{f \in \mathcal{F}} \left( \mathbb{E}_n f - \mathbb{E}f\right) $. \label{lemma:local_rademacher_complexity_basics} \end{lem} \begin{lem}[{\citet[Theorem~11.6]{DBLP:books/daglib/0035701}}] Let $B \geq 1$ and $\mathcal{F}$ be a set of functions $f: \mathbb{R}^d \rightarrow [0,B]$. Let $Z_1, ..., Z_n$ be i.i.d. $\mathbb{R}^d$-valued random variables. For any $\alpha > 0$, $0 < \epsilon < 1$, and $ n \geq 1$, we have \begin{align*} P \left\{ \sup_{f \in \mathcal{F}} \frac{\frac{1}{n}\sum_{i=1}^n f(Z_i) - \mathbb{E}[f(Z)]}{\alpha + \frac{1}{n} \sum_{i=1}^n f(Z_i) + \mathbb{E}[f(Z)]} > \epsilon \right\} \leq 4 \mathbb{E} N(\frac{\alpha \epsilon}{5}, \mathcal{F}|Z_1^n, n^{-1} \| \cdot \|_1) \exp \left( \frac{-3 \epsilon^2 \alpha n}{40 B} \right). \end{align*} \label{lemma:sup_concentration} \end{lem} \begin{lem}[\textit{Contraction property} \citep{afol_lecture2}] Let $\phi: \mathbb{R} \rightarrow \mathbb{R}$ be a $L$-Lipschitz, then \begin{align*} \mathbb{E}_{\sigma} R_n \left( \phi \circ \mathcal{F} \right) \leq L \mathbb{E}_{\sigma} R_n \mathcal{F}. \end{align*} \end{lem} \begin{lem}[{\citet[Lemma~1]{DBLP:journals/ijon/LeiDB16}}] Let $\mathcal{F}$ be a function class and $P_n$ be the empirical measure supported on $X_1, ..., X_n \sim \mu$, then for any $r >0$ (which can be stochastic w.r.t $X_i$), we have \begin{align*} \mathbb{E}_{\sigma} R_n \{f \in \mathcal{F}: \| f \|_{n}^2 \leq r \} \leq \inf_{\epsilon > 0} \bigg[ \mathbb{E}_{\sigma} R_n \{ f \in \mathcal{F} - \mathcal{F}: \|f \|_{\mu} \leq \epsilon \} + \sqrt{ \frac{2r \log N(\epsilon/2, \mathcal{F},\|\cdot \|_{n}) }{n} } \bigg]. \end{align*} \label{lemma:local_empirical_rademacher_bounded_by_covering_number_with_empirical_norm} \end{lem} \begin{lem}[ {\citet[modification]{DBLP:journals/ijon/LeiDB16}}] Let $X_1, ..., X_n$ be a sequence of samples and $P_n$ be the associated empirical measure. For any function class $\mathcal{F}$ and any monotone sequence $\{\xi_k\}_{k=0}^{\infty}$ decreasing to $0$, we have the following inequality for any non-negative integer $N$ \begin{align*} \mathbb{E}_{\sigma} R_n \{f \in \mathcal{F}: \|f \|_n \leq \xi_0 \} \leq 4 \sum_{k=1}^N \xi_{k-1} \sqrt{ \frac{\log \mathcal{N}(\xi_k, \mathcal{F}, \| \cdot \|_{n})}{n} } + \xi_N. \end{align*} \label{lemma:refined_entropy_integral} \end{lem} \begin{lem}[\textit{Pollard's inequality}] Let $\mathcal{F}$ be a set of measurable functions $f: \mathcal{X} \rightarrow [0,K]$ and let $\epsilon >0, N$ arbitrary. If $\{X_i\}_{i=1}^N$ is an i.i.d. sequence of random variables taking values in $\mathcal{X}$, then \begin{align*} P \left( \sup_{f \in \mathcal{F}} \bigg| \frac{1}{N} \sum_{i=1}^N f(X_i) - \mathbb{E}[f(X_1)] \bigg| > \epsilon \right) \leq 8 \mathbb{E} \left[ N(\epsilon/8, \mathcal{F}|_{X_{1:N}}) \right] e^{\frac{-N \epsilon^2}{ 128 K^2}}. \end{align*} \end{lem} \begin{lem}[\textit{Properties of (bracketing) entropic numbers}] Let $\epsilon \in (0, \infty)$. We have \begin{enumerate} \item $H(\epsilon, \mathcal{F}, \|\cdot \|) \leq H_{[]}(2 \epsilon, \mathcal{F}, \|\cdot \|)$; \item $H( \epsilon, \mathcal{F}|\{x_i\}_{i=1}^n, n^{-1/p} \cdot\| \cdot \|_p ) = H( \epsilon, \mathcal{F}, \| \cdot \|_{p,n} ) \leq H(\epsilon, \mathcal{F}| \{x_i\}_{i=1}^n, \| \cdot \|_{\infty}) \leq H(\epsilon, \mathcal{F}, \| \cdot \|_{\infty})$ for all $\{x_i\}_{i=1}^n \subset dom(\mathcal{F})$. \item $H(\epsilon, \mathcal{F} - \mathcal{F}, \| \cdot \|) \leq 2 H (\epsilon/2, \mathcal{F}, \| \cdot \|))$, where $\mathcal{F} - \mathcal{F} := \{f - g: f, g \in \mathcal{F}\}$. \end{enumerate} \end{lem} \begin{lem}[\textit{Entropic number of bounded Besov spaces} {\citep[Corollary~2.2]{Nickl2007BracketingME}}] For $1 \leq p,q \leq \infty$ and $\alpha > d/p$, we have \begin{align*} H_{[]}(\epsilon, \bar{B}^{\alpha}_{p,q}(\mathcal{X}), \| \cdot \|_{\infty}) \lesssim \epsilon^{-d/\alpha}. \end{align*} \label{lemma:entropic_number_of_Besov} \end{lem} \begin{lem}[\textit{Approximation power of deep ReLU networks for Besov spaces} \citep{suzuki2018adaptivity}] Let $1 \leq p,q \leq \infty$ and $\alpha \in (\frac{d}{p \land 2}, \infty)$. For sufficiently large $N \in \mathbb{N}$, there exists a neural network architecture $\Phi(L, m,S,B)$ with \begin{align*} L \asymp \log N, m \asymp N \log N, S \asymp N, \text{ and } B \asymp N^{d^{-1} + \nu^{-1}}, \label{parameterize_net} \end{align*} where $\nu := \frac{\alpha - \delta}{2 \delta}$ and $\delta := d(p^{-1} - (1 + \floor{\alpha})^{-1})_{+}$ such that \begin{align*} \sup_{f_* \in \bar{B}^{\alpha}_{p,q}(\mathcal{X})} \inf_{f \in \Phi(L,W,S,B)} \|f - f_*\|_{\infty} \lesssim N^{-\alpha/d}. \end{align*} \label{lemma:approximation_power_for_Besov} \end{lem} \section*{Checklist} The checklist follows the references. Please read the checklist guidelines carefully for information on how to answer these questions. For each question, change the default \answerTODO{} to \answerYes{}, \answerNo{}, or \answerNA{}. You are strongly encouraged to include a {\bf justification to your answer}, either by referencing the appropriate section of your paper or providing a brief inline description. For example: \begin{itemize} \item Did you include the license to the code and datasets? \answerYes{See Section~\ref{gen_inst}.} \item Did you include the license to the code and datasets? \answerNo{The code and the data are proprietary.} \item Did you include the license to the code and datasets? \answerNA{} \end{itemize} Please do not modify the questions and only use the provided macros for your answers. Note that the Checklist section does not count towards the page limit. In your paper, please delete this instructions block and only keep the Checklist section heading above along with the questions/answers below. \begin{enumerate} \item For all authors... \begin{enumerate} \item Do the main claims made in the abstract and introduction accurately reflect the paper's contributions and scope? \answerYes{} \item Did you describe the limitations of your work? \answerYes{See Section~\ref{section:discussion}} \item Did you discuss any potential negative societal impacts of your work? \answerNA{} \item Have you read the ethics review guidelines and ensured that your paper conforms to them? \answerYes{} \end{enumerate} \item If you are including theoretical results... \begin{enumerate} \item Did you state the full set of assumptions of all theoretical results? \answerYes{See Section~\ref{section:preliminaries}} \item Did you include complete proofs of all theoretical results? \answerYes{See the supplementary} \end{enumerate} \item If you ran experiments... \begin{enumerate} \item Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)? \answerNA{} \item Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? \answerNA{} \item Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? \answerNA{} \item Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)? \answerNA{} \end{enumerate} \item If you are using existing assets (e.g., code, data, models) or curating/releasing new assets... \begin{enumerate} \item If your work uses existing assets, did you cite the creators? \answerNA{} \item Did you mention the license of the assets? \answerNA{} \item Did you include any new assets either in the supplemental material or as a URL? \answerNA{} \item Did you discuss whether and how consent was obtained from people whose data you're using/curating? \answerNA{} \item Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content? \answerNA{} \end{enumerate} \item If you used crowdsourcing or conducted research with human subjects... \begin{enumerate} \item Did you include the full text of instructions given to participants and screenshots, if applicable? \answerNA{} \item Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? \answerNA{} \item Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation? \answerNA{} \end{enumerate} \end{enumerate} \section{Conclusion and Discussion} \label{section:discussion} This paper presents the sample complexity of offline RL with deep ReLU network function approximation. We prove that the FQI-type algorithm with the data-dependent structure obtains an improved sample complexity of $\tilde{\mathcal{O}}\left( \kappa^{1 + d/\alpha} \cdot \epsilon^{-2 - 2d/\alpha} \right)$ under a standard condition of distributional shift and a new dynamic condition namely Besov dynamic closure which encompasses the dynamic conditions considered in the prior results. Established under the data-dependent structure and the general Besov dynamic closure, our sample complexity is the most general result for offline RL with deep ReLU network function approximation. We close with some open problems. First, although the finite concentration coefficient is a uniform data coverage assumption that is relatively standard in offline RL, can we develop a weaker, non-uniform assumption that can still accommodate offline RL with non-linear function approximation? While such a weaker data coverage assumptions do exist for offline RL in tabular settings \citep{rashidinejad2021bridging}, it seems difficult to generalize this condition to function approximation. Another important direction is to investigate the sample complexity of \textit{pessimism} principle \citep{buckman2020importance} in offline RL with non-linear function approximation, which is currently studied only in tabular and linear settings \citep{rashidinejad2021bridging,jin2020pessimism}. \section{Introduction} Offline reinforcement learning \citep{levine2020offline} is a practical paradigm of reinforcement learning (RL) where logged experiences are abundant but a new interaction with the environment is limited or even prohibited. The fundamental offline RL problems are how well previous experiences could be used to evaluate a new target policy, known as off-policy evaluation (OPE) problem, or to learn the optimal policy, known as off-policy learning (OPL) problem. We study these offline RL problems with infinitely large state spaces, where the agent must use function approximation such as deep neural networks to generalize across states from an offline dataset without any further exploration. Such problems form the core of modern RL in practical settings, but relatively few work provide a comprehensive and adequate analysis of the statistical efficiency for the problems. On the theoretical side, predominant sample efficiency results in offline RL focus on tabular environments with small finite state spaces \citep{DBLP:conf/aistats/YinW20,DBLP:conf/aistats/YinBW21,yin2021characterizing}, but as these methods scale with the number of states, they are infeasible for infinitely large state space settings. While this tabular setting has been extended to large state spaces via {linear} environments \citep{DBLP:journals/corr/abs-2002-09516}, the linearity assumption often does not hold for many RL problems in practice. More relevant theoretical progress has been achieved for more complex environments with general and deep neural network function approximations, but these results are either inadequate or relatively disconnected from practical settings \citep{DBLP:journals/jmlr/MunosS08,DBLP:journals/corr/abs-1901-00137,DBLP:conf/icml/0002VY19}. In particular, their finite-sample results either (i) depend on a so-called inherent Bellman error \citep{DBLP:journals/jmlr/MunosS08,DBLP:conf/icml/0002VY19}, which could be arbitrarily large or uncontrollable in practice, (ii) avoid the data-dependent structure in their algorithms at the cost of losing sample efficiency \citep{DBLP:journals/corr/abs-1901-00137} or improperly ignore it in their analysis \citep{DBLP:conf/icml/0002VY19}, or (iii) rely on relatively strong dynamics assumption \citep{DBLP:journals/corr/abs-1901-00137}. In this paper, we study a variation of fitted-Q iteration (FQI) \citep{bertsekas1995dynamic,introRL} for the offline RL problems where we approximate the target $Q$-function from an offline data using a deep ReLU network. The algorithm is appealingly simple: it iteratively estimates the target $Q$-function via regression on the offline data and the previous estimate. This procedure, which intuitively does the best it could with the available offline data, forms the core of many current offline RL methods. With linear function approximation, \cite{DBLP:journals/corr/abs-2002-09516} showed that this procedure yields a minimax-optimal sample efficient algorithm, provided the environment dynamics satisfy certain linear properties. While their assumptions generalize the tabular settings, they are restrictive for more complex environment dynamics where non-linear function approximation is required. Moreover, as they highly exploit the linearity structure, it is unclear how their analysis can accommodate non-linear function approximation such as deep ReLU networks. In this paper, we provide the statistical theory of a FQI-type algorithm for both OPE and OPL problems with deep ReLU networks. In particular, we provide the first comprehensive analysis for offline RL under deep ReLU network function approximation. We achieve this generality in our result via two novel considerations. First, we introduce \textit{Besov dynamic closure} which is, to our knowledge, the most general assumption that encompasses the previous dynamic assumptions in offline RL. In particular, our Besov dynamic closure reduces into H\"older smoothness and Sobolev smoothness conditions as special cases. Moreover, the MDP under the Besov dynamic closure needs not be continuous, differentiable or spatially homogeneous in smoothness. Second, as each value estimate in a regression-based offline RL algorithm depends on the previous estimates and the entire offline dataset, a complicated data-dependent structure is induced. This data-dependent structure plays a central role in the statistical efficiency of the algorithm. While prior results ignore the data-dependent structure, either in their algorithm or their analysis, resulting a loss of sample efficiency or improper analysis, respectively, we consider it in a FQI-type algorithm and effectively handle it in our analysis (this is discussed further in Section \ref{section:background_and_related_literature} and \ref{section:main_results}). Under these considerations, we establish the sample complexity of offline RL with deep ReLU network function approximation that is both more general and more sample-efficient than the prior results, as summarized in Table \ref{tab:compare_literature} which will be discussed in details in Subsection \ref{subsect:main_result}. Moreover, as our technical proof combining a uniform-convergence analysis and local Rademacher complexities with a localization argument is sufficiently general and effective in handling complex function approximations, our proof could be of independent interest for other offline RL methods with non-linear function approximation. \section{Preliminaries} \label{section:preliminaries} We consider reinforcement learning in an infinite-horizon discounted Markov decision process (MDP) with possibly infinitely large state space $\mathcal{S}$, continuous action space $\mathcal{A}$, initial state distribution $\rho \in \mathcal{P}(\mathcal{S})$, transition operator $P: \mathcal{S} \times \mathcal{A} \rightarrow \mathcal{P}(\mathcal{S})$, reward distribution $R: \mathcal{S} \times \mathcal{A} \rightarrow \mathcal{P}([0,1])$, and a discount factor $\gamma \in [0,1)$. Here we denote by $\mathcal{P}(\Omega)$ the set of probability measures supported in domain $\Omega$. For notational simplicity, we assume that $\mathcal{X} := \mathcal{S} \times \mathcal{A} \subseteq [0,1]^d$ but our main conclusions do not change when $\mathcal{A}$ is finite. A policy $\pi: \mathcal{S} \rightarrow \mathcal{P}(\mathcal{A})$ induces a distribution over the action space conditioned on states. The $Q$-value function for policy $\pi$ at state-action pair $(s,a)$, denoted by $Q^{\pi}(s,a) \in [0,1]$, is the expected discounted total reward the policy collects if it initially starts in the state-action pair, \begin{align*} Q^{\pi}(s,a) &:= \mathbb{E}_{\pi} \left[ \sum_{t=0}^{\infty} \gamma^t r_t | s_0 = s, a_0 = a \right], \end{align*} where $r_t \sim R(s_t, a_t), a_t \sim \pi(\cdot|s_t)$, and $s_t \sim P(\cdot|s_{t-1}, a_{t-1})$. The value for a policy $\pi$ is simply $V^{\pi} = \mathbb{E}_{s \sim \rho, a \sim \pi(\cdot|s)} \left[Q^{\pi}(s,a) \right]$, and the optimal value is $V^* = \max_{\pi} V^{\pi}$ where the maximization is taken over all stationary policies. Alternatively, the optimal value $V^*$ can be obtained via the optimal $Q$-function $Q^* = \max_{\pi} Q^{\pi}$ as $V^* = \mathbb{E}_{s \sim \rho} \left[ \max_{a} Q^*(s,a) \right]$. Denote by $T^{\pi}$ and $T^*$ the Bellman operator and the optimality Bellman operator, i.e., for any $f: \mathcal{S}\times \mathcal{A} \rightarrow \mathbb{R}$ \begin{align*} [T^{\pi} f](s,a) &= \mathbb{E}_{r \sim R(s,a)}[r] + \gamma \mathbb{E}_{s' \sim P(\cdot|s,a), a' \sim \pi(\cdot|s')} \left[ f(s',a') \right] \\ [T^* f](s,a) &= \mathbb{E}_{r \sim R(s,a)}[r] + \gamma \mathbb{E}_{s' \sim P(\cdot|s,a)} \left[ \max_{a'} f(s',a') \right], \end{align*} we have $T^{\pi} Q^{\pi} = Q^{\pi}$ and $T^* Q^* = Q^*$. We consider the offline RL setting where the agent cannot explore further the environment but has access to a fixed logged data $\mathcal{D} = \{(s_i, a_i, s'_i, r_i)\}_{i=1}^n$ collected a priori by certain behaviour policy $\eta$ where $(s_i, a_i) \overset{i.i.d.}{\sim} \mu(\cdot, \cdot) := \frac{1}{1 - \gamma} \sum_{t=0}^{\infty} \gamma^t P(s_t = \cdot, a_t = \cdot| \rho, \eta), s'_i \sim P(\cdot| s_i, a_i)$ and $r_i \sim R(s_i, a_i)$. Here $\mu$ is the (sampling) state-action visitation distribution. The goal of OPE and OPL are to estimate $V^{\pi}$ and $V^*$, respectively from $\mathcal{D}$, and in this paper we measure performance by sub-optimality gaps. \noindent \textbf{For OPE}. Given a fixed target policy $\pi$, for any value estimate $\hat{V}$ computed from the offline data $\mathcal{D}$, the sub-optimality of OPE is defined as \begin{align*} \text{SubOpt}(\hat{V}; \pi) = |V^{\pi} - \hat{V}|. \end{align*} \noindent \textbf{For OPL}. For any estimate $\hat{\pi}$ of the optimal policy $\pi^*$ that is learned from the offline data $\mathcal{D}$, we define the sup-optimality of OPL as \begin{align*} \text{SubOpt}(\hat{\pi}) = \mathbb{E}_{\rho} \left[ V^*(s) - Q^*(s, \hat{\pi}(s)) \right], \end{align*} where $\mathbb{E}_{\rho}$ is the expectation with respect to (w.r.t.) $s \sim \rho$. \subsection{Deep ReLU Networks as Function Approximation} \label{subsection:deep_relu_net} In practice, the state space is often very large and complex, and thus function approximation is required to ensure generalization across different states. Deep networks with the ReLU activation offer a rich class of parameterized functions with differentiable parameters. Deep ReLU networks are state-of-the-art in many applications, e.g., \citep{krizhevsky2012imagenet,mnih2015human}, including offline RL with deep ReLU networks that can yield superior empirical performance \citep{voloshin2019empirical}. In this section, we describe the architecture of deep ReLU networks and the associated function space which we directly work on. A $L$-height, $m$-width ReLU network on $\mathbb{R}^d$ takes the form of \begin{align*} f_{\theta}^{L,m}(x) = W^{(L)} \sigma \left( W^{(L-1)} \sigma \left( \hdots \sigma \left(W^{(1)} \sigma(x) + b^{(1)} \right) \hdots \right) + b^{(L-1)} \right) + b^{(L)}, \end{align*} where $W^{(L)} \in \mathbb{R}^{1 \times m}, b^{(L)} \in \mathbb{R}, W^{(1)} \in \mathbb{R}^{m \times d}, b^{(1)} \in \mathbb{R}^m$, $W^{(l)} \in \mathbb{R}^{m \times m}, b^{(l)} \in \mathbb{R}^m, \forall 1 < l < L$, $\theta = \{W^{(l)}, b^{(l)}\}_{1 \leq l \leq L}$, and $\sigma(x) = \max\{x, 0\}$ is the (element-wise) ReLU activation. We define $\Phi(L, m, S,B)$ as the space of $L$-height, $m$-width ReLU functions $f_{\theta}^{L,m}(x)$ with sparsity constraint $S$, and norm constraint $B$, i.e., $\sum_{l=1}^L (\|W^{(l)}\|_0 + \| b^{(l)} \|_0) \leq S, \max_{1 \leq l \leq L} \|W^{(l)} \|_{\infty} \lor \|b^{(l)} \|_{\infty} \leq B$ where $\|\cdot\|_0$ is the $0$-norm, i.e., the number of non-zero elements, and $a \lor b = \max\{a,b\}$. Finally, for some $L,m \in \mathbb{N}$ and $S,B \in (0,\infty)$, we define the unit ball of ReLU network function space $\mathcal{F}_{NN}$ as \begin{align*} \mathcal{F}_{NN} := \bigg\{ f \in \Phi(L,m,S,B): \| f \|_{\infty} \leq 1 \bigg\}. \end{align*} We further write $\mathcal{F}_{NN}(\mathcal{X})$ to emphasize the domain $\mathcal{X}$ of deep ReLU functions in $\mathcal{F}_{NN}$ but often use $\mathcal{F}_{NN}$ when the domain context is clear. The main benefit of deep ReLU networks is that in standard non-parametric regression, they outperform any non-adaptive linear estimator due to their higher adaptivity to spatial inhomogeneity \citep{suzuki2018adaptivity}. Later, we show that this adaptivity benefit of deep ReLU networks transfers to the value regression problem in offline RL even though the value regression is much more complex than the standard non-parametric regression. \subsection{Regularity} In this section, we define a function space for the target functions for which we study offline RL. Note that a regularity assumption on the target function is necessary to obtain a nontrivial rate of convergence \citep{DBLP:books/daglib/0035701}. A common way to measure regularity of a function is through the $L^p$-norm of its local oscillations (e.g., of its derivatives if they exist). This regularity notion encompasses the classical Lipschitz, H\"older and Sobolev spaces. In particular in this work, we consider Besov spaces. Besov spaces allow \textit{fractional} smoothness that describes the regularity of a function more precisely and generalizes the previous smoothness notions. There are several ways to characterize the smoothness in Besov spaces. Here, we pursue a characterization via moduli of smoothness as it is more intuitive, following \citep{gine2016mathematical}. \begin{defn}[\textit{Moduli of smoothness}] For a function $f \in L^p(\mathcal{X})$ for some $p \in [1, \infty]$, we define its $r$-th modulus of smoothness as \begin{align*} \omega_r^{t,p}(f) := \sup_{0 \leq h \leq t} \| \Delta_h^r(f) \|_p, t > 0, r \in \mathbb{N}, \end{align*} where the $r$-th order translation-difference operator $\Delta_h^r = \Delta_h \circ \Delta_h^{r-1}$ is recursively defined as \begin{align*} \Delta_h^r(f)(\cdot) &:= (f(\cdot + h) - f(\cdot))^r = \sum_{k=0}^r {{r}\choose{k}} (-1)^{r-k} f(\cdot + k\cdot h). \end{align*} \end{defn} \begin{rem} The quantity $\Delta_h^r(f)$ captures the local oscillation of function $f$ which is not necessarily differentiable. In the case the $r$-th order weak derivative $D^r f$ exists and is locally integrable, we have \begin{align*} \lim_{ h \rightarrow 0} \frac{\Delta^r_h(f)(x)}{h^r} = D^r f(x), \frac{\omega^{t,p}_r(f)}{t^r} \leq \| D^r f \|_p \text{ and } \frac{\omega^{t,p}_{r+r'}(f)}{t^r} \leq \omega^{t,p}_{r'}(D^r f). \end{align*} \end{rem} \begin{defn}[\textit{Besov spac}e $B^{\alpha}_{p,q}(\mathcal{X})$] For $1 \leq p,q \leq \infty$ and $\alpha > 0$, we define the norm $\|\cdot\|_{B^{\alpha}_{p,q}}$ of the Besov space $B^{\alpha}_{p,q}(\mathcal{X})$ as $\|f\|_{B^{\alpha}_{p,q}} := \|f\|_p + |f |_{B^{\alpha}_{p,q}}$ where \begin{align*} |f |_{B^{\alpha}_{p,q}} := \begin{cases} \left( \int_{0}^{\infty} (\frac{\omega_{\floor{\alpha} + 1}^{t,p}(f)}{t^{\alpha}})^q \frac{dt}{t} \right)^{1/q}, & 1 \leq q < \infty, \\ \sup_{t > 0} \frac{\omega_{\floor{\alpha} + 1}^{t,p}(f)}{t^{\alpha}}, & q = \infty, \end{cases} \end{align*} is the Besov seminorm. Then, $B^{\alpha}_{p,q} := \{ f \in L^p(\mathcal{X}) : \|f \|_{B^{\alpha}_{p,q}} < \infty \}$. \end{defn} Intuitively, the Besov seminorm $|f |_{B^{\alpha}_{p,q}}$ roughly describes the $L^q$-norm of the $l^p$-norm of the $\alpha$-order smoothness of $f$. Having defined Besov spaces, a natural question is what properties Besov spaces have and how these spaces are related to other function spaces considered in the current literature of offline RL? It turns out that Besov spaces are considerably general that encompass H\"older spaces and Sobolev spaces as well as functions with spatially inhomogeneous smoothness \citep{Triebel1983TheoryOF,besovbook,suzuki2018adaptivity,primer_besov,Nickl2007BracketingME}. Before presenting the main properties of Besov spaces, we introduce necessary notations. Let $L^p(\mathcal{X}, \mu) = \{f: \mathcal{X} \rightarrow \mathbb{R} \text{ }|\text{ } \|f\|_{p, \mu} := (\int_{\mathcal{X}} |f|^p d\mu)^{1/p} < \infty \}$ be the space of measurable functions for which the $p$-th power of the absolute value is $\mu$-measurable, $C^0(\mathcal{X}) = \{f: \mathcal{X} \rightarrow \mathbb{R} \text{ }|\text{ } f \text{ is continuous and } \|f\|_{\infty} < \infty \}$ be the space of bounded continuous functions, $C^{\alpha}(\mathcal{X})$ be the H\"older space with smoothness parameter $\alpha \in (0, \infty) \backslash \mathbb{N}$, $W^{m}_p(\mathcal{X})$ be the Sobolev space with regularity $m \in \mathbb{N}$ and parameter $p \in [1,\infty]$, and $X \hookrightarrow Y$ be \textit{continuous embedding} from a metric space $X$ to a metric space $Y$. For simplicity, we use $\|\cdot\|_{\mu}$ for $\| \cdot\|_{p,\mu}$ when $p=2$. We summarize the key intriguing characteristics of Besov spaces and their relation with other spaces: \begin{itemize} \item (Monotonicity in $q$) For $1 \leq p \leq \infty, 1 \leq q_1 \leq q_2 \leq \infty$ and $\alpha \in \mathbb{R}$, $B^{\alpha}_{p,q_1}(\mathcal{X}) \hookrightarrow B^{\alpha}_{p,q_2}(\mathcal{X})$; \item (With $L^p$ spaces) $L^2(\mathcal{X}) \hookrightarrow B^0_{2,2}(\mathcal{X})$, $B^0_{p,1}(\mathcal{X}) \hookrightarrow L^p(\mathcal{X}) \hookrightarrow B^0_{p,\infty}(\mathcal{X})$ for $1 \leq p \leq \infty$, and $B^{\alpha}_{p,q}(\mathcal{X}) \hookrightarrow L^r(\mathcal{X})$ for $\alpha > d(1/p - 1/r)_{+}$ where $r = \floor{\alpha}+1$; \item (With $C^0(\mathcal{X})$) $B^{\alpha}_{p,q}(\mathcal{X}) \hookrightarrow C^0(\mathcal{X})$ for $1 \leq p,q \leq \infty, \alpha > d/p$; \item (With Sobolev spaces) $B^m_{2,2}(\mathcal{X}) = W^m_2(\mathcal{X})$ for $m \in \mathbb{N}$; \item (With H\"older spaces) $B^{\alpha}_{\infty, \infty}(\mathcal{X}) = C^{\alpha}(\mathcal{X})$ for $\alpha = (0, \infty) \backslash \mathbb{N}$. \end{itemize} In particular, the Besov space $B^{\alpha}_{p,q}$ reduces into the H\"older space $C^{\alpha}$ when $p=q=\infty$ and $\alpha$ is positive and non-integer while it reduces into the Sobolev space $W^{\alpha}_2$ when $p=q=2$ and $\alpha$ is a positive integer. We further consider the unit ball of $B^{\alpha}_{p,q}(\mathcal{X})$: \begin{align*} \bar{B}^{\alpha}_{p,q}(\mathcal{X}) := \{g \in B^{\alpha}_{p,q}: \|g \|_{B^{\alpha}_{p,q}} \leq 1 \text{ and } \|g\|_{\infty} \leq 1\}. \end{align*} To obtain a non-trivial guarantee, certain assumptions on the distribution shift and the MDP regularity are necessary. Here, we introduce such assumptions. The first assumption is a common restriction that handles distribution shift in offline RL. \begin{assumption}[\textit{Concentration coefficient}] \label{assumption:concentration_coefficient} There exists $\kappa_{\mu} < \infty$ such that $ \| \frac{d\nu}{d\mu} \|_{\infty} \leq \kappa_{\mu}$ for any \textit{realizable} distribution $\nu$. \end{assumption} Here, a distribution $\nu$ is said to be realizable if there exists $t \geq 0$ and policy $\pi_1$ such that $\nu(s,a) = \mathbb{P}(s_t = s, a_t=a|s_1 \sim \rho, \pi_1), \forall s,a$. Intuitively, the finite $\kappa_{\mu}$ in Assumption \ref{assumption:concentration_coefficient} asserts that the sampling distribution $\mu$ is not too far away from any realizable distribution uniformly over the state-action space. $\kappa_{\mu}$ is finite for a reasonably large class of MDPs, e.g., for any finite MDP, any MDP with bounded transition kernel density, and equivalently any MDP whose top-Lyapunov exponent is negative \citep{DBLP:journals/jmlr/MunosS08}. \citet{DBLP:conf/icml/ChenJ19} further provided natural problems with rich observations generated from hidden states that has low concentration coefficients. These suggest that low concentration coefficients can be found in fairly many interesting problems in practice. \begin{assumption}[\textit{Besov dynamic closure}] $\forall f \in \mathcal{F}_{NN}(\mathcal{X}), \forall \pi, T^{\pi}f \in \bar{B}^{\alpha}_{p,q}(\mathcal{X})$ for some $ p,q \in [1, \infty]$ and $\alpha > \frac{d}{p \land 2}$. \label{assumption:completeness} \end{assumption} The assumption signifies that for any policy $\pi$, the Bellman operator $T^{\pi}$ applied on any ReLU network function in $\mathcal{F}_{NN}(\mathcal{X})$ results in a Besov function in $\bar{B}^{\alpha}_{p,q}(\mathcal{X})$. Moreover, as $T^{\pi_f} f = T^* f$ where $\pi_f$ is the greedy policy w.r.t. $f$, Assumption \ref{assumption:completeness} also implies that $T^*f \in \bar{B}^{\alpha}_{p,q}(\mathcal{X})$ if $f \in \mathcal{F}_{NN}(\mathcal{X})$. This kind of assumption is relatively standard and common in the offline RL literature \citep{DBLP:conf/icml/ChenJ19}. A natural example for this assumption to hold is when both the expected reward function $r(s,a)$ and the transition density $P(s'|s,a)$ for each fixed $s'$ are Besov functions. This specific example posits a general smoothness to the considered MDP which can be considered a way to impose restrictions in MDPs. We remark again that restrictions in MDPs are necessary to obtain non-trivial convergence rates. Importantly, as Besov spaces are more general than H\"older and Sobolev spaces, our Besov dynamic closure assumption is considerably general that encompasses the dynamic conditions considered in prior results \citep{DBLP:journals/corr/abs-1901-00137}. In particular, as remarked earlier, the Besov space $B^{\alpha}_{p,q}$ reduces into the H\"older space $C^{\alpha}$ and Sobolev space $W^{\alpha}_2$ at $p=q=\infty,\alpha \in (0, \infty) \backslash \mathbb{N}$, and at $p=q=2, \alpha \in \mathbb{N}$, respectively. Moreover, our dynamic assumption only requires the boundedness of a very general notion of local oscillations of the underlying MDP. In particular, the underlying MDP can be discontinuous or non-differentiable (e.g., when $\alpha \leq 1/2$ and $p=2$), or even have spatially inhomogeneous smoothness (e.g., when $p < 2$). These generality properties were not possible to be considered in the prior results. The condition $\alpha > \frac{d}{p \land 2}$ guarantees a finite bound for the compactness and the (local) Rademacher complexity of the considered Besov space. When $p < 2$ (thus the condition above becomes $\alpha > d/p$), a function in the corresponding Besov space contains both spiky parts and smooth parts, i.e., the Besov space has \textit{inhomogeneous} smoothness \citep{suzuki2018adaptivity}. In particular, when $\alpha > d/p$, each \textit{equivalence} class $[f]_{\lambda}, f \in B^{\alpha}_{p,q}(\mathbb{R}^d)$, i.e., modulo equality $\lambda$-almost everywhere, contains a unique continuous representative. In addition, this representative has partial derivatives of order at least $\alpha - d/p$; thus $\alpha - d/p$ is called the \textit{differential dimension} of the Besov space. \section{Related Work} \label{section:background_and_related_literature} The majority of the theoretical results for offline RL focus on tabular settings and mostly on OPE task where the state space is finite and an importance sampling -related approach is possible \citep{first_is,dudik2011doubly,jiang2015doubly,thomas2016data,farajtabar2018more,kallus2019double}. The main drawback of the importance sampling -based approach is that it suffers high variance in long horizon problems. The high variance problem is later mitigated by the idea of formulating the OPE problem as a density ratio estimation problem \citep{DBLP:conf/nips/LiuLTZ18,nachum2019dualdice,Zhang2020GenDICEGO,Zhang2020GradientDICERG,Nachum2019AlgaeDICEPG} but these results do not provide sample complexity guarantees. The sample efficiency guarantees for offline RL are obtained in tabular settings in \citep{xie2019optimal,DBLP:conf/aistats/YinW20,DBLP:conf/aistats/YinBW21,yin2021characterizing}. A lower bound for tabular offline RL is obtained in \citep{DBLP:conf/icml/JiangL16} which in particular show a Cramer-Rao lower bound for discrete-tree MDPs. For the function approximation setting, as the state space of MDPs is often infinite or continuous, some form of function approximation is deployed in approximate dynamic programming such as fitted Q-iteration, least squared policy iteration \citep{bertsekas1995neuro,DBLP:conf/atal/JongS07,DBLP:journals/jmlr/LagoudakisP03,DBLP:conf/icml/GrunewalderLBPG12,DBLP:conf/icml/Munos03,DBLP:journals/jmlr/MunosS08,10.1007/s10994-007-5038-2,DBLP:conf/icml/TosattoPDR17}, and fitted Q-evaluation (FQE) \citep{DBLP:conf/icml/0002VY19}. A recent line of work studies offline RL in non-linear function approximation (e.g, general function approximation and deep neural network function approximation) \citep{DBLP:conf/icml/0002VY19,DBLP:journals/corr/abs-1901-00137}. In particular, \citet{DBLP:conf/icml/0002VY19} provide an error bound of OPE and OPL with general function approximation but they ignore the data-dependent structure in the FQI-type algorithm, resulting in an improper analysis. Moreover, their error bounds depend on the inherent Bellman error that can be large and controllable in practical settings. More closely related to our work is \citep{DBLP:journals/corr/abs-1901-00137} which also considers deep neural network approximation. In particular, \citet{DBLP:journals/corr/abs-1901-00137} focused on analyzing deep Q-learning using a fresh batch of data for each iteration. Such approach is considerably sample-inefficient in offline RL as it undesirably does not leverage the past data. As a result, their sample complexity scales with the number of iterations $K$ which is very large in practice. In addition, they rely on a relatively restricted smoothness assumption of the underlying MDPs that hinders their results from being widely applicable in more practical settings. We summarize the key differences between our work and the prior results in Table \ref{tab:compare_literature} which will be elaborated further in Subsection \ref{subsect:main_result}. Since the initial version of this paper appeared, a concurrent work studies offline RL with general function approximation via local Rademacher complexities \citep{duan2021risk}. While both papers independently have the same idea of using local Rademacher complexities as a tool to study sample complexities in offline RL, our work differs from \citep{duan2021risk} in three main aspects. First, we focus on infinite-horizon MDPs while \citep{duan2021risk} work in finite-horizon MDPs. Second, we focus on a practical setting of deep neural network function approximation with an explicit sample complexity while the sample complexity in \citep{duan2021risk} depends on the critical radius of local Rademacher complexity. Bounding the critical radius for a complex model under the data-dependent structure is highly non-trivial. \citet{duan2021risk} provided the specialized sample complexity for finite classes, linear classes, kernel spaces and sparse linear spaces but it is unclear how their result applies to more complex models such as a deep ReLU network. Importantly, we propose a new Besov dynamic closure and a uniform-convergence argument which appear absent in \citet{duan2021risk}. \section{Algorithm and Main Result} \label{section:main_results} \subsection{Algorithm} Now we turn to the main algorithm and the main result. We study least-squares value iteration (LSVI) for both OPE and OPL with the pseudo-code presented in Algorithm \ref{alg:LSVI} where we denote $\rho^{\pi}(s,a) = \rho(s) \pi(a|s)$. The algorithm is nearly identical to \citep{DBLP:journals/corr/abs-2002-09516} but with deep neural network function approximation instead of linear models. As such, it can be considered as a generalization. \begin{algorithm}[h] \caption{Least-squares value iteration (LSVI)} \label{alg:LSVI} \begin{algorithmic}[1] \State Initialize $Q_0 \in \mathcal{F}_{NN}$. \For{$k=1$ {\bfseries to} $K$} \State If \textbf{OPE} (for a fixed policy $\pi$): $y_i \leftarrow r_i + \gamma \int_{\mathcal{A}} Q_{k-1}(s'_i, a) \pi(da|s'_i), \forall i$ \label{lsvi:ope} \State If \textbf{OPL}: $y_i \leftarrow r_i + \gamma \max_{a' \in \mathcal{A}} Q_{k-1}(s'_i, a'), \forall i $ \label{lsvi:learning} \State $Q_k \leftarrow \argmin_{f \in \mathcal{F}_{NN}} \frac{1}{n} \sum_{i=1}^n (f(s_i, a_i) - y_i)^2 $ \label{lsvi:opt} \EndFor \State If \textbf{OPE}, return $$V_K = \|Q_K \|_{ \rho^{\pi}} = \sqrt{ \mathbb{E}_{\rho(s) \pi(a|s)} \left[ Q_K(s,a)^2 \right]}$$ \State If \textbf{OPL}, return the greedy policy $\pi_K$ w.r.t. $Q_K$. \end{algorithmic} \end{algorithm} The idea of LSVI is to do the best it could with all the offline data using least-squares regression over a function space. The algorithm arbitrarily initializes $Q_0 \in \mathcal{F}_{NN}$ and iteratively computes $Q_k$ as follows: at each iteration $k$, the algorithm constructs a new regression data $\{(x_i, y_i)\}_{i=1}^n$ where the covariates $x_i$ are $(s_i, a_i)$ and the Bellman targets $y_i$ are computed following dynamic programming style. In particular, depending on whether this is an OPE or OPL problem, $y_i$ are computed according to line \ref{lsvi:ope} and line \ref{lsvi:learning} of Algorithm \ref{alg:LSVI}, respectively. It then fits the function class $\mathcal{F}_{NN}$ to the constructed regression data by minimizing the mean squared error at line \ref{lsvi:opt}. This type of algorithm belongs to the fitted Q-iteration family \citep{DBLP:journals/jmlr/MunosS08,DBLP:conf/icml/0002VY19} that iteratively uses least-squares (value) regression to estimate the value functions. The main difference in the algorithm is here we use deep neural networks as function approximation for generalization to unseen states and actions in a complex MDP. On the computational side, solving the non-convex optimization at line \ref{lsvi:opt} of Algorithm \ref{alg:LSVI} can be highly involved and stochastic gradient descent is a dominant optimization method for such a task in deep learning. In particular, GD is guaranteed to converge to a global minimum under certain structural assumptions \citep{nguyen2021proof}. Here, as we focus on the statistical properties of LSVI, not on the optimization problem, we assume that the minimizer at line \ref{lsvi:opt} is attainable. Such a oracle assumption is common when analyzing the statistical properties of an RL algorithm with non-linear function approximation \citep{DBLP:journals/corr/abs-1901-00137,DBLP:conf/icml/ChenJ19,duan2021risk,DBLP:journals/corr/abs-1912-04136,DBLP:journals/corr/abs-2005-10804,DBLP:journals/corr/abs-2102-00815}. For the optimization problem of deep neural networks, we refer the readers to its vast body of literature \citep[see e.g.][and references therein]{sun2019optimization}. \subsection{Data-dependent Structure} We remark the {data-dependent structure} in Algorithm \ref{alg:LSVI}. The target variable $y_i$ computed at line \ref{lsvi:ope} and line \ref{lsvi:learning} of the algorithm depends on the previous estimate $Q_{k-1}$ which in turn depends on the covariate $x_i := (s_i, a_i)$. This induces a complex data-dependent structure across all iterations where the current estimate depends on all the previous estimates and the past data. In particular, one of the main difficulties caused by such data-dependent structure is that conditioned on each $x_i$, the target variable $y_i$ is no longer centered at $[T^*Q_{k-1}](x_i)$ for OPL (or at $[T^{\pi}Q_{k-1}](x_i)$ for OPE, respectively), i.e., $\mathbb{E} \left[ [T^*Q_{k-1}](x_i) - y_i | x_i \right] \neq 0$. This data-dependent structure hinders the use of any standard non-parametric regression analysis and concentration phenomenon typically used in supervised learning. Prior results either improperly ignore the data-dependent structure in their analysis \citep{DBLP:conf/icml/0002VY19} or directly avoid it by estimating each $Q_k$ on a separate subset of the original data \citep{DBLP:journals/corr/abs-1901-00137}. While the latter removes the data-dependent structure, it pays the undesirable cost of scaling the sample complexity with the number of iterations $K$ in the algorithm as it requires splitting the original data into $K$ disjoint subsets. In our work, we consider the data-dependent structure in LSVI and effectively handle it via a uniform-convergence argument and local Rademacher complexities. While our uniform-convergence argument overcomes the data-dependent structure by considering \textit{deterministic} coverings of the target function space $T^* \mathcal{F}_{NN}$ without the need for breaking the original data into $K$ disjoint subsets, local Rademacher complexities localize an original function space into local data-dependent balls which can then be gracefully integrated with the uniform-convergence argument and the complicated deep ReLU function approximation. The technical details for our handling method of the data-dependent structure are presented in the proof of our main theorem (in Subsection \ref{subsect:main_result}) in the supplementary material. \subsection{Main Result} \label{subsect:main_result} Our main result is a sup-optimality bound for LSVI in both OPE and OPL settings under Assumption \ref{assumption:concentration_coefficient} and Assumption \ref{assumption:completeness}. Before stating the main result, we introduce the necessary notations of asymptotic relations. For any two real-valued functions $f$ and $g$, we write $f(\epsilon, n) \lesssim g(\epsilon,n)$ if there is an absolute constant $c$ such that $f(\epsilon, n) \leq c \cdot g(\epsilon, n), \forall \epsilon > 0, n \in \mathbb{N}$. We write $f(\epsilon, n) \asymp g(\epsilon, n)$ if $f(\epsilon, n) \lesssim g(\epsilon, n)$ and $g(\epsilon, n) \lesssim f(\epsilon, n)$. We write $f(\epsilon, n) \simeq g(\epsilon, n)$ if there exists an absolute constant $c$ such that $f(\epsilon, n) = c \cdot g(\epsilon, n), \forall \epsilon, n$. \begin{thm} Under Assumption \ref{assumption:concentration_coefficient} and Assumption \ref{assumption:completeness}, for any $\epsilon > 0, \delta \in (0,1], K > 0$, and for $n \gtrsim \left(\frac{1}{\epsilon^2} \right)^{1 + \frac{d}{\alpha}} \log^6 n + \frac{1}{\epsilon^2}(\log(1/\delta) + \log \log n)$, with probability at least $1 - \delta$, the sup-optimality of Algorithm \ref{alg:LSVI} is \begin{align*} \begin{cases} \text{SubOpt}(V_K; \pi) \leq \frac{ \sqrt{ \kappa_{\mu}}}{1-\gamma} \epsilon + \frac{ \gamma^{K/2}}{(1-\gamma)^{1/2}} &\text{ for OPE}, \\ \text{SubOpt}(\pi_K) \leq \frac{4 \gamma \sqrt{ \kappa_{\mu}}}{(1-\gamma)^2} \epsilon + \frac{4 \gamma^{1 + K/2}}{(1-\gamma)^{3/2}} &\text{ for OPL.} \end{cases} \end{align*} In addition, the optimal deep ReLU network $\Phi(L,m,S,B)$ that obtains such sample complexity (for both OPE and OPL) satisfies \begin{align*} L \asymp \log N, m \asymp N \log N, S \asymp N, \text{ and } B \asymp N^{1/d + (2 \iota)/ (\alpha - \iota) }, \end{align*} where $\iota := d(p^{-1} - (1 + \floor{\alpha})^{-1})_{+}, N \asymp n^{\frac{(\beta + 1/2)d}{2 \alpha + d}}$, and $\beta = (2 + \frac{d^2}{\alpha(\alpha + d)})^{-1}$. \label{thm:sample_complexity} \end{thm} The result states that LSVI incurs a sub-optimality which consists of the statistical error (the first term) and the algorithmic error (the second term). While the algorithmic error enjoys the fast linear convergence to $0$, the statistical error reflects the fundamental difficulty of the problems. The statistical errors for both OPE and OPL cases are bounded by the distributional shift $\kappa_{\mu}$, the effective horizon $1/(1-\gamma)$, and the user-specified precision $\epsilon$ for $n$ satisfying the inequality given in Theorem \ref{thm:sample_complexity}. In particular, the sample complexity does not depend on the number of states as in tabular MDPs \citep{DBLP:conf/aistats/YinW20,DBLP:conf/aistats/YinBW21,yin2021characterizing} or the inherent Bellman error as in the general function approximation \citep{DBLP:journals/jmlr/MunosS08,DBLP:conf/icml/0002VY19}. Instead, it explicitly scales with the (possible fractional) smoothness $\alpha$ of the underlying MDP and the dimension $d$ of the input space. Importantly, this guarantee is established under the data-dependent structure of the algorithm and the Besov dynamic closure encompassing the dynamic conditions of the prior results. Thus, Theorem \ref{thm:sample_complexity} is the most comprehensive result we are aware of for offline RL with deep neural network function approximation. Moreover, to develop further intuition on our sample complexity, we compare it with the prior results. Regarding the tightness of our result, our sample complexity $ \epsilon^{-2 - 2d/\alpha}$ (ignoring the log factor and the factor pertaining to $\kappa_{\mu}$ and effective horizon) nearly matches the nonparametric regression's minimax-optimal sample complexity $\epsilon^{-2 - d/\alpha}$ \citep{kerkyacharian1992density,gine2016mathematical} even though in our case we deal with a more complicated data-dependent structure in a value iteration problem instead of a standard non-parametric regression problem. This gap is necessary and expected due to the data-dependent structure in the algorithm. We remark that it is possible to retain the rate $\epsilon^{-2 - d/\alpha}$ if we split the offline data $\mathcal{D}$ into $K$ (given in Algorithm \ref{alg:LSVI}) disjoint subsets and estimate each $Q_k$ in Algorithm \ref{alg:LSVI} using a separate disjoint subsets. This however comes at the cost that the overall sample complexity scales with $K$ which could be arbitrarily large in practice. \begin{table*} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{l|l|l|l|l|l} \textbf{Work} & \textbf{Functions} & \textbf{Regularity} & \textbf{Tasks} & \textbf{Sample complexity} & \textbf{Remark}\\ \hline \hline \citet{DBLP:conf/aistats/YinW20} & Tabular & Tabular & OPE & $\tilde{\mathcal{O}}\left( \frac{\kappa}{\epsilon^2} \cdot |\mathcal{S}|^2 \cdot |\mathcal{A}| ^2 \right)$ & minimax-optimal \\ \hline \citet{DBLP:journals/corr/abs-2002-09516} & Linear & Linear & OPE & $\tilde{\mathcal{O}}\left( \frac{\kappa}{\epsilon^2} \cdot d \right) $ & minimax-optimal\\ \hline \citet{DBLP:conf/icml/0002VY19} & General & General & OPE/OPL & N/A & improper analysis\\ \hline \citet{DBLP:journals/corr/abs-1901-00137} & ReLU nets & H\"older & OPL & $ \tilde{\mathcal{O}}\left( K \cdot \kappa^{2 + \frac{d}{\alpha}} \cdot \epsilon^{-2 - \frac{d}{\alpha} } \right)$ & no data reuse \\ \hline \textbf{Ours} & \textbf{ReLU nets} & \textbf{Besov} & \textbf{OPE/OPL} & $\tilde{\mathcal{O}}\left( \kappa^{1 + \frac{d}{\alpha}} \cdot \epsilon^{-2 - 2\frac{d}{\alpha}} \right)$ & \textbf{data reuse} \end{tabular} } \caption{Recent advances in the sample complexity of offline RL with various function approximations. Here, $|\mathcal{S}|$ and $|\mathcal{A}|$ are the cardinalities of the state and action space when they are finite, $\kappa$ is a measure of distribution shift, $\epsilon$ is the user-specified precision, $d$ is the dimension of the input space, $\alpha$ is the smoothness parameter of the underlying MDP, and $K$ is the algorithmic iteration number.} \label{tab:compare_literature} \end{table*} To show the significance of our sample complexity, we summarize our result and compare it with the prior results in Table \ref{tab:compare_literature}. From the leftmost column to the rightmost one, the table describes the related works, the function approximations being employed, the regularity conditions considered to establish theoretical guarantees, the offline RL tasks considered, the sample complexity obtained, and the important remarks or features of each work. Specifically, the ``data reuse'' in Table \ref{tab:compare_literature} means that an algorithm reuses the data across all iterations instead of splitting the original offline data into disjoint subsets for each iteration and the regularity column specifies the regularity assumption on the underlying MDP. Based on this comparison, we make the following observations. First, with simpler models such as tabular and linear MDPs, it requires less samples to achieve the same sub-optimality precision $\epsilon$ than more complex environments such as H\"older and Besov MDPs. This should not come as a surprise as the simpler regularities are much easier to learn but they are too strong as a condition to hold in practice. Second, as remarked earlier that Besov smoothness is more general than H\"older smoothness considered in \citep{DBLP:journals/corr/abs-1901-00137}, our setting is more practical and comprehensive as it covers more scenarios of the regularity of the underlying MDPs than the prior results. Third, our result obtains an improved sample complexity as compared to that in \citep{DBLP:journals/corr/abs-1901-00137} where we are able to get rid of the dependence on the algorithmic iteration number $K$ which can be arbitrarily large in practice. On the technical side, we provide a unifying analysis that allows us to account for the complicated data-dependent structure in the algorithm and handle the complex deep ReLU network function approximation. This can also be considered as a substantial technical improvement over \citep{DBLP:conf/icml/0002VY19} as \citet{DBLP:conf/icml/0002VY19} improperly ignores the data-dependent structure in their analysis. In addition, the result in \citep{DBLP:conf/icml/0002VY19} does not provide an explicit sample complexity as it depends on an unknown inherent Bellman error. Thus, our sample complexity is the most general result in a practical and comprehensive setting with an improved performance. Finally, we provide a detailed proof for Theorem \ref{thm:sample_complexity} in the \textbf{supplementary}. The proof has four main components: a sub-optimality decomposition for error propagation across iterations, a Bellman error decomposition using a uniform convergence argument, a deviation analysis for least-squares value regression with deep ReLU networks using local Rademacher complexities via a localization argument, and an upper bound minimization step to obtain an optimal deep ReLU architecture. \section*{Acknowledgement} The first author would like to thank Richard Nickl (Prof. at the University of Cambridge) for the clarification on the bracketing entropic number of Besov spaces. \bibliographystyle{plainnat}
{'timestamp': '2021-07-13T02:23:26', 'yymm': '2103', 'arxiv_id': '2103.06671', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06671'}
arxiv
\section{Introduction} \label{sec:intro} Modern systems offer a tremendous amount of computing resources by assembling a very large number of cores. However, when they are deployed in data-centers, it is very challenging to fully exploit such computing capability due to their shared memory resources. The challenge is that on one hand, there is a need to co-locate a large number of workloads to maximize the system utilization (\& thus minimizing the overall cost), and on the other hand, this workload co-location causes processes to interfere with each other by competing for shared cache resources. This problem is further exacerbated by the fact that modern machine learning \& graph analytics workloads exhibit \textit{diverse resource demands} throughout their execution. In particular, the resource requirements of processes vary not only across applications, but also within a single application across its various regions/phases as it executes \cite{fried2020caladan, iorgulescu2018perfiso}. Prior works on resource management \& utilization \cite{chen2019parties, ebrahimi2010fairness, paragon, bubbleflux, priyanka:socc14,javadi2019scavenger} do not account for the dynamic phase behaviour in modern workloads and use feedback-driven reactive approaches instead. These include approaches that rely on resource usage history or current resource contention (monitored using hardware performance counters) and then \textit{reacting} to contention by invoking suitable scheduling mechanisms. However, majority of modern workloads are input data dependent and do not exhibit highly regular or repetitive behavior across different input sets. Thus, neither history-based methods nor feedback directed methods provide sufficiently accurate predictions for such workloads. Furthermore, these reactive approaches detect a resource-intense execution phase only after it already occurred, and this leads to two more related drawbacks. First, by the time the phase is detected, it may be too late to act, especially if the detection lag is significant or phase duration is short (a phase might be end by the time it is detected). Second, as a result of this detection lag, the application state might have already bloated in terms of its resource consumption; the damage to other co-executing processes' cache state might be already done, and it might be prohibitively expensive to mitigate the offending process because of the large state and its cache affinity can be lost by migrating or pausing. In addition, these approaches cannot predict the duration of the phase, nor the sensitivity of its forthcoming resource usage, thus significantly limiting the chances of further optimizations to co-location of processes. To efficiently co-locate processes and maximize system throughput, we propose \textbf{Beacons Framework} to predict the resource requirement of applications based on a combination of compiler analysis and machine learning techniques that enables pro-active scheduling decisions. This framework consists of \textbf{Beacons Compilation Component}, that leverages the compiler to analyze programs and predict the resource requirements, \& \textbf{Beacons Runtime Component}, which includes the pro-active \textit{Beacons Scheduler}, that uses these analysis to undertake superior scheduling decisions. The beacons scheduler relies on the compiler to insert ``beacons''(specialized markers) in the application at strategic program points to periodically produce and/or update details of anticipated (forthcoming) resource-heavy program region(s). The beacons framework classifies loops in programs based on cache usage and predictability of their execution time and inserts different types of beacons at their entry/exit points. Moreover, the beacons scheduler augments imprecise information through the use of performance counters to throttle higher concurrency when needed. The novelty of this scheme is that through the use of \textit{loop timing}, \textit{memory footprint}, and \textit{reuse information} provided via compiler analysis combined with machine learning mechanisms, the scheduler is able to precisely yet aggressively maximize co-location or concurrency without incurring cache degradation. We evaulated \textbf{Beacons Framework} on a Amazon Graviton2~\cite{graviton2} machine on consolidated benchmark suites from \textit{Machine Learning Workloads} \cite{huang2017densely,hinton2012improving,deng2009imagenet,he2016deep}, \textit{PolyBench}~\cite{yuki2015polybench}, a numerical computational benchmark, and \textit{Rodinia}~\cite{che2009rodinia}, a heterogeneous compute-based kernel based on diverse domains. Our experiments demonstrate that the end result of such a high throughput oriented framework is that it effectively schedules a large number of jobs and improves throughput over CFS (Completely Fair Scheduler, a production scheduler bundled with Linux distributions) by \textbf{76.78\%} on average (geometric mean) and up to \textbf{3.29x} (\S\ref{sec:eval}). Overall, the main contributions of our work can be summarized as follows: \begin{itemize} \item We present a compiler-directed predictive analysis framework that determines resource requirements of dynamic modern workloads in order to aid dynamic resource management. \item We show that an application's resource requirement can be determined by its \textit{loop-timings} (\S\ref{bec:timing}) which in turn depend upon the prediction of expected loop iterations (\S\ref{bec:iter}), \textit{memory footprints} (\S\ref{sec:memfp}) and \textit{data-reuse behaviour} (\S\ref{bec:reuse}). We show how these attributes can be estimated by combining compiler analysis with machine learning techniques in Beacons Compilation Component (\S\ref{beacons:compiler}). \item To predict precise loop timing for proactive scheduling decisions, we develop a detailed loop classification scheme that covers all possible types of loops in modern workloads. Based on this scheme, we develop a framework that analyzes such loops by capturing both the data-flow and control-flow aspects (\S\ref{bec:iter}). \item We design and implement a lightweight \textit{Beacons Runtime Component} (\S\ref{beacons_sch}), which includes the proactive throughput-oriented Beacons Scheduler (\S\ref{bec:sch}), that aggregates the information generated by multiple processes and allocate resources to the processes and enables communication between the application and the scheduler. \end{itemize} \section{Beacons Compilation Component} \label{beacons:compiler} The Beacons Compilation Component (Fig. ~\ref{fig:system}) is responsible for instrumenting beacons in an application in order to guide a scheduler through upcoming regions. The regions in code are analyzed at the granularity of loop nests. During the compilation phase, the applications are first profiled to generate sample loop timings through a compiler pass called the \textit{beacons loop analysis pass}. This pass runs the program on a subset of application inputs, which form the training input set. These timings are then used for training a linear regression equation which establishes the loop timing as a function of the total iterations of the loop (\textbf{trip-count}). Such an approach directly handles simple loops whose trip-counts can be predicted statically from its loop bounds. However, to enable analysis of loops whose trip-counts are unknown at compile time, we develop a loop categorization framework that unifies both data and control flow of the loop bounds and its predicates variables. We then predict the trip counts for such loops by using decision tree classifier and rule-based mechanisms, which is futher integrated with the loop timings to enhance its accuracy. The timing regression equation is then embedded before the loop, along with two other pieces: the memory footprint equation and the classification of the loop as either ``reuse'' or ``streaming'', based on its memory reference patterns. The memory footprints are estimated by polyhedral compiler analysis \cite{grosser2011polly}, while the reuse classification is done with the help of static reuse distance (SRD) analysis. The beacons are inserted before the outermost loops and then hoisted inter-procedurally. To rectify potential scheduling errors arising from timing and memory footprint inaccuracies, the beacon-based scheduler is augmented with performance counters which are used in cases of loop bounds which can not be estimated even by machine learning; in addition a completion beacon is inserted at loop exit points to signal the end of the loop region. We now describe each of these above aspects in detail in the following subsections. \subsection{Loop Timing Analysis \& Categorization} \label{bec:timing} In order to predict the timing of a loop (nest) present in the application, we establish it as a function of its total iterations (trip-count). Our goal is to obtain a linear relationship of form $y = ax_1 + bx_2 + .. + kx_n$, where $x_1, x_2, ..., x_k$ are trip-counts of individual loops in a loop nest and $y$ is the execution time of the loop nest. The core-idea here is that the constants $a,b,..,k$ can then be learnt using linear-regression and this closed-form equation can be directly utilized to generate the loop-timing dynamically during runtime. \subsubsection{General Loop Modelling} \label{bec:genloopmodel}For a given loop with various instructions, the loop time depends on the number of loop iterations, i.e. \textbf{loop time} ($T$) is directly proportional to \textbf{loop iterations} ($N$). Therefore, $T \propto N \Rightarrow T = \alpha * N$, where proportionality constant $\alpha$ which represents the average execution time of the loop body. In a nested loop, the execution duration depends on the number of iterations encountered at each nesting level. Consider a loop nest consisting of $n$ individual loops with total iterations $N_1, N_2,...,N_n$ respectively. We observe that the loop nest duration ($T$) is a function of these loop iterations, i.e $ T = f(N_1, N_2,...,N_n)$. As far as the loop body is concerned, each instruction in the loop nest contributes to the loop time by the factor of the number of times the instruction is executed. Thus, a loop can be analyzed by determining the nesting level of each of the basic blocks in its body and then multiplying the timing of that basic block with its execution frequency determined by the trip counts of surrounding loops. Thus, timing equation can be represented as: $T \propto g_1(N_1)+g_2(N_1*N_2)+...+ g_n(N_1*N_2*...*N_n)$, where $g_1(N_1)$ is the function of time contributed by outermost loop or the basic block belonging to the outermost loop with $N_1$ iterations, $g_2(N_1*N_2)$ is the function of time contributed by the second loop at the nesting level 2 and so on. Removing the proportionality sign, this equation can be rewritten as: \begin{equation}\label{equation:lm} T = c_0 + c_1*N_1 + c_2*(N_1*N_2)+...+ c_n*(N_1*N_2...N_n) \end{equation} where $c_0$ is the constant term. Eq. \ref{equation:lm} is a linear equation in terms of each loop iteration $N_k$. Therefore, we use linear regression to learn the coefficients for each of the loop iterations in the loop nest to predict the loop timings. \subsubsection{Estimating Precise Loop Iterations}:\label{bec:iter} The loop timing model described above depends on the compile time knowledge of the exact loop iterations, i.e the \textit{trip-count} associated with the loop. For certain kinds of regular loops, it's simple to statically determine the total number of iterations for loops with regular bounds (Fig. \ref{fig:loopex}{\color{red}a}). Such loops can be normalized using the loop-simplify pass in the LLVM \cite{Lattner:2004:LCF:977395.977673} compiler. Loop normalization converts a loop to the form with lower bound set to zero and step increment by one to reach an upper bound. The upper bound of the loop is now equal to the number of loop iterations and can be easily extracted from the loop and plugged into Eq. \ref{equation:lm} for timing prediction. In practice, however, loops need not adhere to this template. Real-world workloads have loops with irregular bounds (Fig. \ref{fig:loopex}{\color{red}b}) and non-uniform trip count that are often input-dependent, which makes it harder to analyze their trip count statically. This also extends to loop nests (either with affine or non-affine bounds), having control flow statements that break out iterations transferring the control out of the loop body (Fig. \ref{fig:loopex}{\color{red}c}). Therefore, to estimate precise loop iterations we need to develop a framework that captures both input data flow characteristics and control flow behaviour of the entire loop nest. \begin{figure} [!ht] \centering\includegraphics[width=1.0\columnwidth]{figs/bes_loopex.jpg} \caption{Examples of different instances of loop for predicting trip counts. Each of these instances can be generalized to nested loops as well.} \label{fig:loopex} \end{figure} \textbf{Loop Classification Scheme} In order to obtain trip counts for various loop-nests, we first categorize the loops by developing a classification scheme that takes into account both the data-flow \& control-flow characteristics of a loop. The data-flow characteristics of a loop can be determined by the loop bounds, while the control flow aspect can be captured by the nature of loop termination. Thus, each individual loops can either be \textit{Normal-bounded}/\textit{Irregularly-bounded} loops (data flow aspect) or \textit{Normal-Exit}/\textit{Multi-Exit} (control flow aspect) loops. Unifying the data-flow \& control-flow characterization results in a comprehensive framework that covers all possible loops types in real workloads (Fig. \ref{fig:looptax}) The resultant four classes of loops are \textit{Normally Bounded Normal Exit} (\textbf{NBNE}) loops, \textit{Normally Bounded Multi Exit} (\textbf{NBME}) loops, \textit{Irregularly Bounded Normal Exit} (\textbf{IBNE}) loops \& \textit{Irregularly Bounded Multi Exit} (\textbf{IBME}) loops. \begin{figure} [!ht] \centering\includegraphics[width=1.0\columnwidth]{figs/loop_taxonomy.jpg} \caption{Loop Classification Scheme with 4 classes of loop: NBNE, NBME, IBNE \& IBME} \label{fig:looptax} \end{figure} Based on this classification scheme, we develop a \textbf{Loop Categorization Algorithm} (Algo. \ref{algo:LCA}) that detects loops for each categories and invokes specialized trip count estimation mechanisms for each case. This algorithm first checks the bounds of the given loop. If the bound is entirely composed of numerical entities (integer, float, double, etc.), which allows a static estimation of symbolic upper bound the loop is classified as \textit{Normal-Bounded}. Alternatively, loops for which bounds contain non-numerical entities (pointer references, function calls, etc.) are considered as \textit{Irregularly-Bounded} Loops. To handle such cases, we propose \textbf{Upwards Exposed Control Backslicing} (UECB) Algorithm (Algo. \ref{algo:UECB}), which is a general framework that predicts trip counts based on the `upward-exposed' values of variables that decide the control flow in the loop, using learning mechanisms. It returns a learning model that estimates the loop trip counts based on a loop's critical variables. \begin{algorithm}[htb] \footnotesize \SetAlgoLined \textbf{Input:} Function F\\ \KwResult{Determine the precise trip count (in terms of expression or linear model) for all the loops} \For{each loop $L \in$ Function $F$} { $regular,normal \leftarrow true$\\ $exit\_points,critical\_bounds,critical\_predicates \leftarrow \phi$\\ $bounds \leftarrow L.getBounds()$\\ \For{each argument $arg \in bounds$} { \If{type(arg) != num} {$regular \leftarrow false$\\ $critical\_bounds.push\_back(arg)$}} \For{each basicblock $bb \in L$} { \If{(bb.successor $\notin L$) and (bb != L.header) } {$normal \leftarrow false$\\ exit\_points.push\_back(bb)\\ \For{each point $P \in exit\_points$} {\For{each variable $v \in P$}{critical\_predicates.push\_back(v)}}} } \If{regular and normal} {$tripCount \leftarrow (bound.upper() - bound.lower())$} \If{regular and not normal} {$Prediction Model \leftarrow UECB (critical\_predicates)$\\} \If{not regular and normal} {$Prediction Model \leftarrow UECB (critical\_bounds)$\\} \If{not regular and not normal} {$Prediction Model \leftarrow UECB (critical\_bounds \cup critical\_predicates)$\\} } \caption{Loop Categorization Algorithm} \label{algo:LCA} \end{algorithm} After the detection of expected trip counts based on loop bounds, the loop bodies are analyzed for control-flow statements. If there are no statements in the loop body that exit out of the loop for \textit{Normal-Bounded} case, the loop is categorized as \textit{Normal-Exit} and the expected trip count is equal to symbolic trip count. Next, if the loop is \textit{Irregularly-Bounded}, its expected bound is learnt using UECB algorithm described below. The cases of multiple exits in the body are classified as \textit{Multi-Exit} and the critical variables present in the predicates are extracted and passed on to the UECB algorithm to generate the respective model. \textbf{UECB Algorithm}: The first step in UECB is to identify \textit{critical} variables that dictate a loop's trip count, i.e variable that decides whether the control flow will go to the loop body or loop exit. These variables can be either irregular loop bounds, or part of predicates that break out of loop. The core idea here is to use a learning model that can be trained on these variables to estimate the loop's trip count. The trained model can then be embedded in the beacon associated with the loop nest. However, since the inserted beacon exists at the entrance of loop nests, the trip count prediction must be done only with the variables \& their definitions that are live at that point. Such variables are called \textit{Out-of-loop} variables, i.e these variables are live at outermost loop header and their definitions that come from outside the loop body. Therefore, it is essential to back-propagate the \textit{critical} variables in order to express them in terms of \textit{Out-of-loop} variables. UECB achieves this back-propagation by following a stack-based approach that involves analyzing the \textit{critical} variables and the upwards-exposed definitions on which they depend in terms of their backward slice. When the program is run on representative inputs, these \textit{out-of-loop} variables are logged to generate the training data for the learning model. \begin{algorithm} \footnotesize \SetAlgoLined \textbf{Input:} Set of Critical Variables C \\ \KwResult{Classifier Model M that estimates precise trip count based on unseen values of critical variables} $model\_parameters, worklist = \{\}$\\ \For{each variable $v_c \in C$} {$def\_set \leftarrow getallDefinitions(v_c)$\\ \For{each definition $d \in def\_set$} {worklist.push\_back(d)} } \While{worklist is not empty} { $d \leftarrow$ remove a definition from the worklist\\ \For{each operand $op \in d$ } { \eIf{op is out-of-loop variable} {model\_parameters.push\_back(op)} {$def\_set \leftarrow getallDefinitions(op)$\\ \For{each definition $d \in def\_set$} {worklist.push\_back(op)} } } } Generate Training \& Testing data for $model\_parameters$\\ \eIf{Total Data Points $>$ Threshold} {Train Decision-Tree Classifier $M (model\_parameters)$} {Obtain Rule-based Prediction Model $M (model\_parameters)$} \caption{Upwards Exposed Control Backslicing (UECB) Algorithm} \label{algo:UECB} \end{algorithm} The learning model used to predict loop trip counts based on \textit{critical} variables is the decision tree classifier. The input set for the entire program is divided into two parts for training \& testing respectively. This model is then embedded in the beacon associated with the outer-loop and is used to predict the precise loop trip count when it's invoked. \textbf{Loops not suitable for machine learning}: UECB Algorithm generates training data by logging the values of critical variables upon various loop invocations. However, if the loop is invoked only small number of times ($<10$), then it's impractical to train decision trees for predicting trip-counts of such loops. This is because machine learning models require the training and testing dataset to be sufficiently large in order to provide meaningful predictions. Thus, for predicting trip-counts of loops that are not invoked enough times to train a classifier model, we use \textbf{Rule-Based} Trip Count Prediction. The core idea here is that \textit{expected trip-count} is within the one standard deviation of the mean trip-count of all the rules. The rule-based mechanism is preferred over classifier model, when the number of data-points are lesser than hyper-parameter \textit{threshold} value ($\sim 5$). After the expected trip count for various classes of loop are obtained, either by simple analysis (NBNE) or by classifier models (NBME/IBNE/IBME) from the Loop Categorization algorithm (Algo. \ref{algo:LCA}), they are integrated with timing equation (Eq. \ref{equation:lm}) to enhance the loop-timing predictions through normal regression models. \subsection{Memory Footprint Analysis} \label{sec:memfp} The footprint indicates the amount of cache that will be occupied by a loop. Memory footprint analysis consists of two parts - (a) calculating the memory footprint of the loop, and (b) classifying a loop as a \textit{reuse-oriented} loop or a \textit{streaming} (which exhibits little or no reuse) loop. \subsubsection{Calculating Memory Footprint} For a given loop, its memory footprint is estimated based on polyhedral analysis, which is a static program analysis performed on LLVM intermediate representation (IR). For each memory access statement in the loop, a polyhedral access relation is constructed to describe the accessed data points of the statement across loop iterations. An access relation describes a map from the loop iteration to the data point accessed in that iteration. It contains three pieces of information: 1) parameters, which are compile-time unknown constants, 2) a map from the iteration to array index(es); and 3) a Presburger formula~\cite{verdoolaege2016presburger} describing the conditions when memory access is performed. Generally, parameters contain all loop-invariant variables that are involved in either array index(es) or the Presburger formula, and the Presburger formula contains loop conditions. We currently ignore if-conditions enclosing memory access statements; we thus get an upper bound in terms of estimation of the memory footprints. For illustration, list~\ref{code:mfa} shows a loop with three memory accesses, with two of them accessing the same array but different elements. A polyhedral access relation is built for each of them. The polyhedral access relation for $d[2*i]$ is: $[N] \rightarrow \{ [i] \rightarrow [2*i]: 0 <= i <= N \}$, where $[N]$ specifies the upper-bound of the normalized loop. It is a compile-time unknown loop invariant since its value is not updated across loop iterations. $[i] \rightarrow [2*i]$ is a map from the loop iteration to the accessed data point (simply array indexes). $0 <= i <= N $ is the Presburger formula with constraints about when the access relation is valid. \begin{lstlisting}[xleftmargin=0.05\textwidth,caption={Memory Footprint Estimation Example},label=code:mfa] for ( int i = 0 ; i <= N; ++ i ) { ... = a[i+3]; d[2*i] = ...; d[3*i] = ...; } \end{lstlisting} Based on the polyhedral access relations constructed for every memory access in the loop, the whole memory footprint for the loop can be computed leveraging polyhedral arithmetic. It simply counts the number of data elements in each polyhedral access relation set, and then adds them together. Instead of a constant number, the result of polyhedral arithmetic is an expression of parameters. For $d[2*i]$, its counting expression generated using polyhedral arithmetic is: $[N] \rightarrow \{ (1 + N) : N >= 0 \}$. Therefore, as long as the value of $N$ is available, the memory footprints of the loop can be estimated by evaluating the expressions. In our framework, the value of $N$ is given by the expected trip count (through one of the five cases: NBNE or by classifier models (NBME/IBNE/IBME) or rule-based system as described in the last section). For statements that access the same arrays, e.g. $d[2*i]$ and $d[3*i]$, a union operation will first be performed to calculate the actual number of accessed elements as a function of compile-time unknown loop iterations and instrumented in the program. It is evaluated at runtime to get the expected memory footprint. \subsubsection{Classifying Reuse and Streaming Loops}\label{bec:reuse} A loop that reuses memory locations over a large number of iterations (large reuse distance) needs enough cache space to hold its working memory and might be sensitive to the misses caused, and a loop that streams data which is reused in next few iterations require almost no cache space at all and might be insensitive due to a small fixed reuse distance. For efficient utilization of cache, the scheduler must know this classification. We classify the loops using \textbf{Static Reuse Distance (SRD)}, defined as the number of possible instructions between two accesses of a memory location. For example, in Fig. \ref{fig:loopSRD} the $SRD$ between statements ($S_1$, $S_2$) is in the order of $m*3$ because an access in instruction $S_1$ has to wait for $m$ instructions within the inner loop to cover the distance of three outer iterations between successive access of the same memory location. The $SRD$ between statements ($S_5$, $S_6$) is in the order of two, because the same memory is accessed after two iterations. \begin{figure}[!ht] \centering\includegraphics[width=1.0\columnwidth]{figs/bes_srd4.jpg} \caption{\small SRD Estimation for two loop nests. Loop Nest 1 is classified as reuse, while Loop Nest 2 is streaming.} \label{fig:loopSRD} \end{figure} Any loops with a constant SRD, that is the distance between the accesses is covered within a few iterations of the same loop (e.g. the one between statements ($S_5$, $S_6$), ($S_5$, $S_7$) and ($S_6$, $S_7$) in Fig. \ref{fig:loopSRD}{\color{red}b}), can be classified as \textit{streaming}, because the memory locations must be in the cache for only a few (constant) iterations of the loop during which it is highly unlikely to be thrashed. More specifically, an SRD that involves an inner loop (e.g. the one between statements ($S_1$, $S_2$) in Fig. \ref{fig:loopSRD}{\color{red}a}) or outer loop (e.g. between statements ($S_3$, $S_4$) in Fig. \ref{fig:loopSRD}{\color{red}a}) where a cache entry must wait in the cache over the duration of the entire loop that it is dependent on -- such loops are classified as \textit{reuse}. For example, array B must be in cache for the duration of the entire outer loop. Thus, we classify such loops in which the SRD is dependent on either an outer or inner loop as \textit{reuse loops} (reuse distance here is a function of normalized loop bound $N$, for example), and we classify the remaining loops (with small and constant reuse distance) as streaming loops. Indirect and irregular references such as a[b[i]] do not typically have a large reuse distance associated with them (compared to the sizes of modern caches) and it is impossible to analyze them at compile time; in our current approach, they are classified therefore as non-reuse references. \subsection{Beacons Hoisting \& Insertion} The beacon insertion compiler pass ensures that the beacons are hoisted at the entrances of outermost loops intra-procedurally. However, inter-procedural loops (function calls in loop body) can overload the scheduler with too many beacon calls. Hence, if the beacons are inside inter-procedural loops, then they are hoisted outside and also above the other call sites that are not inside loops along all paths. For hoisting the beacon call (\& embedding the inner-loop attributes), the inner loop bounds may not be available (or live) at the outermost points inter-procedurally. Thus, use expected loop bounds of the inner loops to calculate the beacon properties, timing information and memory footprint. Each interprocedural inner loop's memory footprint is added to the outermost inter-procedural loop's memory footprint. On the other hand, the loop timing is based only on the outermost inter-procedural loop. The beacon is classified as reuse if there is a single interprocedural nested loop. Unfortunately, such a conversion transforms many known/inferred beacons to unknown beacons. Also, hoisting is a repetitive process that stops once no beacons are inside inter-procedural loops. The decision trees are inserted as if-then-else blocks with the trip count value being passed to both the loop timing model and the memory footprint formula. The equations with the coefficients and loop bounds are instrumented at the preheader of the corresponding loop nests, followed by the memory footprint calculations. The variables that hold the timing and memory footprint values along with loop type (reuse or streaming) and beacon type are passed as arguments to the beacon library calls. Facilitated by the beacon library, the instrumented call fires a beacon with loop properties to the scheduler. We use shared memory for the beacon communications between the library and the scheduler. For every beacon, a loop completion beacon is inserted at either the exit points of the loop nest or after the call site for beacons hoisted above call site. The completion beacon sends no extra information other than signaling the completion of the loop phase and so that any sub-optimal scheduling decision can be rectified. \section{Beacons Runtime Component} \label{beacons_sch} After the beacons and its attributes (loop timing regression models, trip count classifiers, memory footprint calculations and reuse classification) are instrumented in the application, it's the job of the Runtime Component to evaluate \& communicate the attributes during the execution. These evaluated attributes are communicated to the scheduler through a library interface that communicates with the scheduler. We refer to these function calls to the library as ``\textbf{beacon calls}''. A beacon call fired from an application writes the beacons attributes to a shared memory which is continuously polled by the scheduler. Beacon Scheduler analyzes this beacon information and acts proactively to the resource requirements among the co-executing processes, which sets it apart from state-of-art schedulers like CFS. This establishes the communication between applications and scheduler (no special privileges required), and processes that can write to this shared memory are agreed upon during initialization with a key. The scheduler arbitrates the co-executing processes to maximize concurrency while simultaneously addressing the demand on the shared resources such as caches and memory bandwidth. Then goal of the scheduler is to facilitate efficient cache and memory bandwidth usage to improve system job throughput. \textbf{Types of Beacon Calls}: Based on the system and application's execution state, there can be three distinct beacon library calls: \textit{Beacon\_Init} (to initialize the shared memory for writing the attributes), \textit{Beacon} (this writes the beacon attributes the shared memory) \& \textit{Loop\_Complete} (this signals the end of a loop for a process). \textbf{Beacons Call Classification}: Based on the precision of the attribute information, the beacon calls can either be classified into \textbf{Known/Inferred} Beacon Calls, where the loop trip-counts, timing and memory footprints are calculated via closed-form expressions with high accuracy, and \textbf{Unknown} Beacon Calls, where the attribute information is non-exact, expected values mainly calculated by rule-based trip-count estimation. This distinction helps us to identify potential impreciseness in application's resource requirement and allows us rectify certain sub-optimal scheduling decisions. \subsection{Beacons Scheduler (BES)}\label{bec:sch} The beacon information sent by the applications is collected by the scheduler to devise a schedule with efficient resource usage. The beacon scheduler dynamically operates in two modes based on the loop data-reuse behaviour - reuse or streaming mode. The two modes corresponding to two types of reuse behaviour is to mitigate the adverse effects (resource demand overlaps) caused by multiple loops that co-execute together. Initially, the scheduler starts without a mode and schedules as many processes as required to fill up all the processors (cores) in the machine. One primary objective of the scheduler is to maximize system resource utilization and never keep any processors idle. The scheduler enters one of the two modes based on the first beacon it collects. Until the beacon call is fired, a process is treated as having no memory requirement and is referred to as a \textit{non-cache-pressure type process}. During the non-cache-pressure phase, the processes typically have memory footprint lower than the size of L1 private cache and do not affect the shared cache, unlike streaming or reuse type with cache requirements exceeding the L1 cache. Based on the timing information received from an incoming beacon, the scheduler estimates the time by which a certain loop should complete its execution. An important point to note here is although loop time values are obtained by compiling the process in isolation, the loop timing will still be similar even with multi-tenancy when scheduled by the beacon scheduler. This is because the scheduler ensures the avoidance of contention among the processes as detailed below. When any process fires a beacon, three possible timing scenarios (Fig~\ref{fig:scen}) can occur. In the first case, the completing (currently executing) beacon and the incoming beacon do not overlap (Fig~\ref{fig:scen} (right)). The completing beacon will relinquish its resources, which will be accordingly updated by the scheduler. The incoming beacon is then scheduled based on the resource availability.In the second case, the completing beacon and incoming beacon overlap for greater than 5-10\% (configurable) of the execution time (Fig~\ref{fig:scen} (middle)). Here, if the resources required by the incoming beacon is more than the available resources, then the incoming beacon process is descheduled and replaced with another process. Finally, in the third case where the overlap is less than 5-10\%, if the incoming beacons' resource requirement is satisfied on completion of the earliest beacon process, then the process is allowed to continue but with performance monitoring turned on. However, if the IPC of the beacon processes degrade, then the incoming beacon process is descheduled. Also, if the information is known to be imprecise (unknown beacons), then the scheduler turns on performance counters to rectify its actions. In each case the resource is either last level cache in reuse mode or memory bandwidth in stream mode. \begin{figure} [!ht] \centering\includegraphics[width=1.0\columnwidth]{figs/scenario_merge.jpg} \caption{Different timing Scenarios of Incoming Beacon} \label{fig:scen} \end{figure} \begin{figure} \centering\includegraphics[width=0.8\columnwidth]{figs/bes-fsm.png} \caption{A simplified Mealy state machine of the beacon scheduler. Key: \textbf{B}eacon, \textbf{R}euse, \textbf{S}treaming, \textbf{F}iller, \textbf{J}ob, \textbf{C}omplete, \textbf{T}hreshold, \textbf{deq}ueue, \textbf{enq}ueue, \textbf{\$}(cache)} \label{fig:fsm} \end{figure} \textbf{Reuse Mode}: The goal of the scheduler in reuse mode is to effectively utilize the cache by minimizing the execution overlap between the processes that are reuse bound. At any given time, the cores in the machine may be executing a mix of \textit{reuse loops} (\textbf{RJ}) that fit the cache and \textit{non-cache-pressure} (\textbf{FJ}) applications only as shown in the scheduler mealy machine Fig~\ref{fig:fsm}. If any of these FJ processes fires a \textit{reuse beacon} (\textbf{RB}), the scheduler first checks the memory information to ensure if the beacon fits in the available cache space or not. The scheduler only allows the process to continue if it fits in the available cache space. Once the reuse loop completes (loop\_completion beacon call), the process is re-classified as FJ again. If a FJ process fires a \textit{streaming beacon} (\textit{SB}), then the process is suspended and replaced by a suspended reuse process that fits in the cache. If no such suspended reuse process exists, then a non-cache-pressure process is scheduled. When all \textit{reuse loops are completed} (\textbf{RC}) or the number of suspended stream loops hits a \textit{threshold} (\textbf{ST}) (typically 90\% of the number of cores in the machine), then the remaining RJ processes are suspended, if any, and all the SJ processes are resumed and the scheduler switches to stream mode. \textbf{Stream Mode}: A stream loop does not reuse its memory in the cache and hence is not disturbed by other co-executing processes as long as the system memory bandwidth is sufficient. The expected (mean) memory bandwidth ($\mu_{bw}$) of a stream loop can be calculated by using the memory footprint and the timing information as: $\mu_{bw} = \frac{Memory Footprint}{Loop Time}$. In stream mode the scheduler schedules the SJ processes by replacing all other processes (RJ and FJ) as long as the Total Mean Memory Bandwidth (T$\mu_{bw}$) is less than the memory bandwidth of the machine. Any remaining core can only be occupied by a FJ process because a RJ process will get thrashed by the streaming applications. If a streaming loop completes, then it is replaced by a suspended streaming process when memory bandwidth is available. Otherwise, the process is allowed to continue as long as it does not fire a reuse beacon (\textbf{RB}). In other words, any non-streaming, non-cache-pressure application firing a reuse beacon is suspended and replaced by either a suspended streaming process or a non-cache-pressure application. When the number of such suspended reuse processes hits a threshold (RT), which is typically 10\% of the number of cores in the machine and based on whether the reuse processes can fill the cache, the scheduler switches from stream mode to reuse mode. An execution scenario is possible in which all streaming processes get suspended, all reuse processes are run, then after suspending more streaming jobs, all streaming processes are scheduled again in a batch, and so on. \section{Conclusion} \label{sec:conc} In this work, we propose a compiler-directed approach for proactively carrying out scheduling. The key insight is that the compiler produces predictions in terms of loop timings and underlying memory footprints along with the type of loop: reuse oriented vs streaming which are used to make scheduling decisions. A new framework based on the combination of static analysis coupled with ML models was developed to deal with irregular loops with statically non-determinable trip counts and with multiple loop exits. It was shown that this framework is able to successfully predict such loops with \textbf{85\%} accuracy. A prototype implementation of the framework demonstrates significant improvements in throughtput over CFS by an average of \textbf{76.78\%} with up to \textbf{3.25x} on Graviton2 for consolidated workloads. The value of prediction was also demonstrated over a reactive framework which under-performed CFS by \textbf{9\%}. Thus, to conclude, predictions help pro-activeness in terms of scheduling decisions which lead to significant improvements in throughput for a variety of workloads. \section{Evaluation} \label{sec:eval} Our goal is to evaluate Beacons Framework in environments, where throughput in terms of number of jobs completed per unit time or the time for completion of the batch is important and latency of each individual process itself is of not much value. A common example of such a scenario is a server conducting biological anomaly detection on thousands of patient data records (each patient as a new process) and with the goal to complete as many as possible to discover a particular pattern \cite{greensmith2010information}. \textbf{Experimental Platform}: The experiments were conducted on a Amazon Graviton2 (m6g.metal) machine, running Linux Ubuntu 20.4. The system has one socket with 64 processors and 32 MB L3 cache. We carried out our experiments on 60 processors, leaving the rest for other system applications to run smoothly and not interfere with our results. Beacons Compilation Component was implemented as unified set of compiler and profilling passes in LLVM 10.0. Machine learning library \textit{scikit-learn} was used to implement the classifier models. \textbf{Benchmarks}: We evaluated our system on four sets of diverse workload suites, consisting of 53 individual benchmarks. We perform our experiments on: \textit{PolyBench} \cite{yuki2015polybench}, a numerical computational suite, consisting of linear algebra, matrix multiplication kernels, \textit{Rodinia} \cite{che2009rodinia}, which consists of graph traversal, dynamic programming applications from diverse domains like medical imaging, etc and on various popular machine learning benchmarks like \textit{AlexNet} ~\cite{hinton2012improving}, \textit{DenseNet201} \cite{huang2017densely}, \textit{Resnet101} \cite{he2016deep}, \textit{Resnet-18}, \textit{Resnet-152}, and \textit{VGG16} \cite{simonyan2014very} by training these networks on a subset of CIFAR-10 Dataset \cite{krizhevsky2009learning}. In addition to that, we perform experiments on well-known pre-trained networks like \textit{TinyNet}, \textit{Darknet} and \textit{RNN} (with 3 recurrent modules) for predicting data samples from CIFAR-10, Imagenet ~\cite{deng2009imagenet} and NLTK \cite{bird2009natural} corpus respectively. \textbf{Methodology}: We run experiments and report all the benchmarks in Polybench. However, since the L1 data cache size is 32KB, the beacon calls are fired only if the loop memory footprint is above 32KB and if the loop predicted time is above 10ms. This is neccessary because the average processing time of loop complete, reuse, and stream beacons are 116us, 427us, and 292us respectively, and thus the loop timings below 10ms would be unneccessary for scheduling. \textit{Leukocyte} in \textit{Rodinia} is one such benchmark with all beacons statically removed because the expected memory footprint is lower than 32KB and hence we do not report the values here. Our ML workloads were created using \textit{Darknet} \cite{darknet13} and they were divided into training benchmarks and prediction benchmarks. The training benchmarks are well-known \textit{convolutional neural networks} (CNNs) and we ran them by training on a subset of Cifar-10 images. The prediction benchmarks are pre-trained models that were used to classify images from \textit{Imagenet} dataset. For all the benchmarks, input sets were divided into training \& test sets to obtain the loop-timing (regression) \& trip-count (classification) models. Table \ref{tab:ben} summarizes all the benchmarks used in our experiments. All the benchmarks were compiled with their defaults optimization flags (-O2/O3, -pthread, etc). \begin{table}[htb] \resizebox{\columnwidth}{!}{ \begin{tabular}{|l|l|l|} \hline \textbf{Benchmark Suite} & \textbf{Benchmarks} & \textbf{Dataset} \\ \hline Polybench & \begin{tabular}[c]{@{}l@{}}2mm, 3mm, atax, bicg, mvt, gemm,gesummv,\\ symm, syr2k, syrk, trmm, cholesky, lu, \\ ludcmp, trisolv, correlation,covariance, \\ floyd-warshall, nussinov, deriche, adi, fdtd-2d, \\ heat-3d, jacobi-1d, seidel-2d\end{tabular} & \begin{tabular}[c]{@{}l@{}}SMALL\\ STANDARD\\ EXTRALARGE \\ (Training)\\ \\ LARGE (Testing)\end{tabular} \\ \hline Rodinia & \begin{tabular}[c]{@{}l@{}}backprop, bfs, cfd, heartwall, hotspot, \\ hotspot3D, kmeans-serial, lavaMD, nn, \\ particlefilter, srad\_v2\end{tabular} & \begin{tabular}[c]{@{}l@{}}Custom Inputs (Training \\ \& Testing)\end{tabular} \\ \hline \begin{tabular}[c]{@{}l@{}}Convolutional Neural Network\\ (Training)\end{tabular} & \begin{tabular}[c]{@{}l@{}}Alexnet, Resnet-18, Resnet-101, Resnet-151,\\ VGG-16, Densenet-201\end{tabular} & \begin{tabular}[c]{@{}l@{}}CIFAR-10 (Training \\ \& Testing)\end{tabular} \\ \hline \begin{tabular}[c]{@{}l@{}}Convolutional Neural Network\\ (Pre-Trained)\end{tabular} & TinyNet, Darknet3 & \begin{tabular}[c]{@{}l@{}}Imagenet (Training \\ \& Testing)\end{tabular} \\ \hline \end{tabular}} \caption{Summary of Benchmarks used in our experiments} \label{tab:ben} \end{table} \textbf{Designing Scheduling Jobs}: Our mixes consists of large and small processes. We set a reasonable number of large processes (20-200) so the mix does not run for unusually large duration (hours) for experimentation although our scheduler is robust works long running processes. Once the large processes are executed, we inject 4-5 small processes per large process to simulate a real-life scenario of other processes getting added to mixes and trying to hog the cache. Thus, the scheduler can end up executing more than 10000 processes during the entire mix. In addition, our mixes are homogeneous so all processes are the same, but with different inputs only. We also created heterogeneous mixes of different applications but a homogeneous mix tends to be the worst case because all processes have the same phases and cache requirements and execute in somewhat of a phase synchrony causing each process to demand the same resources as other processes at the same time during its execution. \textbf{Baselines}: To evaluate the effectiveness of Beacons Scheduling mechanism, we compare it against - \textbf{(a)} Linux's CFS \cite{kobus2009completely} baseline, which is the widely-used standard scheduler in most computing environments, and \textbf{(b)} Merlin~\cite{priyanka:socc14}, which is a performance-counter based reactive scheduler (RES). The purpose of this comparison to investigate the necessity of compiler-guided scheduling vs traditional perf-based scheduling. Merlin first uses the cache misses per thousand instructions (MPKI) in LLC to determine memory intensity; then it estimates cache reuse by calculating the memory factor (MF), which is the ratio LLC/(LLC-1) MPKI. We use the same MF threshold as Merlin (0.6) to classify reuse and stream phases. \begin{figure} [!ht] \centering\includegraphics[width=1.0\columnwidth]{figs/loop_dist_pic.jpg} \caption{Loop Distribution across Rodinia \& ML Workloads and their trip-count prediction accuracy.} \label{fig:loopdistype} \end{figure} \subsection{Beacons Prediction Accuracies} \textbf{Loop Trip Count Prediction Accuracy:} Fig. \ref{fig:loopdistype} shows the distribution of different loop-classes for \textit{Rodinia} and \textit{Machine Learning} workloads. \textit{Polybench} is not shown in the pie-chart since it contains 100\% NBNE-type loops. \textit{Rodinia}'s loops are rule-based so there are no classifiers needed. The right part of Fig.\ref{fig:loopdistype} shows the accuracy of classifier-based models in predicting the trip counts. The average accuracy is \textbf{85.3\%}. The reason UECB achieves consistently high accuracy is because of the nature of these benchmarks. Machine Learning workloads can be broadly dissected into several constituent layers - convolutional layer, fully-connected layer, softmax-layer, dropout-layer, etc. Each of these layers perform an unique set of operations, that can be captured very well by classifier models employed by UECB. These models find the correlation between specific loop properties such as the trip counts, critical variable values and hence are able to perform well. Overall, trip counts for \textbf{60\%} of the loops in the workloads are predicted by \textit{classifier} models, while the rest are obtained by \textit{rule-based} models. \begin{figure} \includegraphics[width=1.0\linewidth]{figs/act_t_all.jpg} \caption{\small Three different cases of Loop Timing Accuracy: positive deviation (CFD), negative (2mm) and perfect fit (Backprop) }\label{fig:actvpred} \end{figure} \begin{figure*} \includegraphics[width=1.0\linewidth]{figs/bes_time.jpg} \caption{\small Loop Timing Accuracy across all three workloads suites} \label{fig:time1} \end{figure*} \textbf{Loop Timing Accuracy}: The overall loop timing accuracy for both \textit{unknown} and \textit{known} beacons collectively was \textbf{83\%} across all the workloads (Fig.\ref{fig:time1}). This accuracy can vary depending on different classes of loops and their respective training inputs for closed-form regression equation (Eq.\ref{equation:lm}). For known/inferred beacons (NBNE and other loops covered by UECB algorithm), the accuracy of timing info mainly depends on training. The regression fit in Eq.~\ref{equation:lm} works particularly well for continuous input sets, as the inputs can be monotonously increased or decreased to obtain a proper domain for the regression function. For example, in Fig.\ref{fig:actvpred}, \textit{backprop} takes in continuous integer inputs and the predicted curve matches closely with different testing inputs (mean-squared error $\mu = 0.057$). However, for applications with discrete inputs, the regression training becomes dependent on how representative the provided training inputs are of the actual application behaviour. Some benchmarks like \textit{hotspot} in Rodinia have five inputs (four used for training) that capture the behaviour of the loop. The precise loop curve overlaps almost exactly with the actual time curve, similar to Fig.\ref{fig:actvpred}. In contrast, a few cases had training inputs that are not sufficient enough to learn precise regression coefficients, thus decreasing the accuracy. For example, in 2mm, shown in Figure~\ref{fig:actvpred}, the predicted curve deviates for the fourth input (which is the test input). For some NBME, IBME and IBNE loops, the unknown beacons predicts a loop time that is loop bound obtained during regression runs. However, the actual loop time can deviate from the predicted time, resulting in either positive or negative error rate. These two cases are illustrated in Fig~\ref{fig:actvpred}. In \textit{CFD}, the timing information is generated by hoisting the expected values of inner loop bounds to a point above their inter-procedural outer loop in the beacon. As a result, we end up with a mean-squared error $\mu = 11.023$, which shows that ``unknown'' nature of these loops can sometimes cause unreliable prediction. However, to ensure that such cases do not impact the scheduling decisions, an end-of-loop beacon typically fires at the loop exit, which helps the scheduler correct its course. Ultimately, these few cases of expected predictions (with low accuracy) are still manageable mainly due to loop completion beacons. \subsection{Throughput Improvement \& Analysis} The throughput of the system is calculated as the total time required by the scheduler to finish a fixed number of incoming jobs which is same as the average number of jobs completed in unit time when normalized with a baseline (CFS). The throughput of both the beacon scheduler and Merlin-based reactive scheduler normalized against CFS is shown in Fig. \ref{fig:thr}. Based on geometric mean average, we achieved speedup of \textbf{76.78\%} on Gravitron2 compared to the 33\% slowdown by the Merlin-based reactive scheduler. Among 45 evaluated benchmarks from Polybench, Rodinia, and modern ML workloads, we had significant throughput improvement for 28 of them with the modern ML workloads showing the most throughput improvement (\textbf{2.47x}) on geometric mean. Polybench and Rodinia have a modest improvement of 69.01\% and 51.46\% respectively. These improvements are for the worst-case mix of homogeneous processes that have the same cache phases. \begin{figure*} \includegraphics[width=1.0\linewidth]{figs/bes_thr.jpg} \caption{\small Throughput Improvement across benchmarks in Polybench, Rodinia \& Machine Learning Workloads. Both scheduler’s throughputs are normalized against the baseline Linux’s CFS Scheduler}\label{fig:thr} \end{figure*} The performance benefit is mainly attributed to the smart processes scheduling leveraging the knowledge of process' loop type at a given time. The throughput improvement can be divided into several categories based on its throughput improvement and are analyzed below: \begin{itemize} \item \textbf{Insignificant Improvement}: In four workloads, beacons performed worse or got similar timings compared against CFS baseline. These workloads were typically dominated by streaming loops ($>95\%$), and thus majority of execution time was spend on streaming loops. In this scenario, beacons' scheduling is similar to CFS, where the resource demand are low and uniform. Adding the small scheduling and beacons call overheads, we end up with timing similar to CFS' or small slowdowns ($\leq9\%$). \item \textbf{Small Improvement} (10\% - 50\%): The majority of applications within this category tend to have small amount of reuse-based loops ($~5\% - 10\%$). Most of the reuse loops typically have smaller footprints or short duration. Deriche is a special case where reuse loops occur alternatively between streaming loops. Therefore, the minimal performance improvement is obtained from the data-reuse in alternate loops, but the frequent streaming loops prevents the inter-loop data reuse. While CFS can save on memory accesses across loops (because CFS does not preempt the application), BES gains performance during the reuse loops, leading to smaller overall improvement. \item \textbf{Medium Improvement} (50\% - 2x): Applications within this category spend a considerable amount of time within reuse loops. Bicg, gemm and atax have a majority of streaming loops but the reuse loop executes for the longest duration. On the other hand, trisolv has more reuse loops (but lesser duration) which allows beacons scheduler to be in reuse mode for a longer period of time collectively, and benefits from the proactive scheduling. \item \textbf{High Improvement} (2x - 3x): Applications run for longer durations and spend a majority of their time within reuse loops (although they have a mix of streaming and reuse loops in some cases). Evidently, it it's no surprise that all the ML workloads fall in this category. These workloads are mostly training or predicting so they have to continuously reuse their neuron weights during the execution. Aside from the neuron weights, they typically use matrix computations, which are further reused to do back-propagation. Both the matrices and weights account for a considerable amount of data, as the large networks like Alexnet has eight layers (especially five convolutional layers). Thus, beacons schedules the processes to enable fast matrix multiplications due to less trashing of the cache. \end{itemize} \begin{figure} [!ht] \centering\includegraphics[width=1.0\columnwidth]{figs/hist_job.jpg} \caption{Histograms for the job completion times of CFS and the beacon-enabled scheduler (BES) for cholesky (left) and correlation (right). The X axis represents discrete timesteps, and the Y axis is a count of the number of jobs that completed within a given timestep} \label{fig:hist} \end{figure} We finally present three interesting job completion timelines of \textit{Cholesky} (which showed substantial benefits with beacons), juxtaposed with those of \textit{Correlation} (which had no noticeable benefit)(Fig. \ref{fig:hist}) with three scheduler - \textbf{CFS}, Beacons' scheduler (\textbf{BES}) and Merlin-based reactive scheduler (\textbf{RES}). In \textit{Cholesky}, BES starts with the same jobs as CFS but soon replaces some of the reuse jobs with other non-cache-pressure types to avoid cache overflow, unlike CFS which takes longer to retire its first jobs. BES later on intelligently places reuse and non-cache-pressure jobs to maintain high throughput, whereas CFS keeps scheduling both the non-cache-pressure types and cache-pressure types throughout the execution. Compared to these two, RES keeps on moving both cache-pressure types and non-cache-pressure types rather than prioritizing a particular type of them at the beginning. In the case of correlation, the jobs are within the cache size limit and this can be seen by the two graphs (BES and RES) being interleaved. Thus, BES does not do anything differently from RES, and both complete their workloads at roughly the same time. BES and RES try to prioritize one group and this leads to no completions then a spike of processes completing especially in the tail end of the mix that saw ~1200 processes completing every second. On the other hand, just like in cholesky, CFS has no knowledge of the types and does not do it in a batch so CFS keep on scheduling and preempting processes to allow a constant amount of ~80 processes to complete at each second. Thus, its line is mostly horizontal. In summary, in \textit{Cholesky}, by limiting cache pressure through careful scheduling, BES wins over others whereas in \textit{Correlation}, it performs no worse. \section{Motivation \& Overall Framework} \label{sec:motiv} Maximizing system throughput by efficient process scheduling in a multi-tenant execution setting (data centers, cloud, etc) for modern workloads is challenging. The reason for this is that these execution scenarios consists of thousand of jobs, typically in batches. In such cases, completion time of each individual job itself is of no value, but the completion time of either whole batch of jobs, or the number of jobs completed per unit time (if the jobs are an incoming stream) is of utmost priority \cite{amvrosiadis2018diversity}. \subsection{Motivating Example: Reactive Vs Proactive} Consider an execution scenario in a multi-tenant enviroment, where we have the popular convolutional neural network (CNN) \textit{Alexnet}, being trained on different input sets with varied parameters (dropout rate, hidden units, etc) concurrently, as a batch. During the training, several other jobs (matrix multiplication computations on different matrices) co-execute, having access to the same shared resources (LLC, etc), but on different cores. Table \ref{tab:t} shows the comparison of execution time of this scenario with \textbf{(1)} widely used production Linux scheduler \textbf{CFS} \cite{kobus2009completely}, \textbf{(2)} a performance-counter based reactive scheduler \textbf{Merlin} \cite{priyanka:socc14} and \textbf{(3)} proposed \textbf{Beacons Framework} with Beacons Scheduler. \begin{table}[!ht] \resizebox{\columnwidth}{!}{ \begin{tabular}{|l|l|l|l|l|} \hline \multirow{2}{*}{\textbf{\begin{tabular}[c]{@{}l@{}}Constituent Processes\\ executing as a Batch\end{tabular}}} & \multirow{2}{*}{\textbf{Total Processes}} & \multicolumn{3}{l|}{\textbf{Execution Time (sec)}} \\ \cline{3-5} & & \textbf{CFS} & \textbf{Merlin} & \textbf{Beacons} \\ \hline Alexnet Training & 20 & \multirow{2}{*}{249.43} & \multirow{2}{*}{358.23} & \multirow{2}{*}{100.58} \\ \cline{1-2} Matrix Multiplication (2mm) & 133768 & & & \\ \hline \end{tabular}} \caption{Alexnet Training and 2mm (Polybench) executing as a batch. The 2mm process can be considered as a small process compared to Alexnet, and hence can act as hogging system resources with sheer numbers} \label{tab:t} \end{table} As we can see from Table \ref{tab:t}, the schedulers like CFS that are agnostic to the diverse requirements and overlap in resource requirements can suffer from slowdowns as high as \textbf{1.5x}. On the other hand, scheduler that use feedback-driven approach first uses performance counters to measure IPC/Cache miss and {\it then} undertakes scheduling decision perform even worse, having performance degradation of more than \textbf{3.5x}. The reason for this that \textbf{Merlin} \cite{priyanka:socc14} reacts to the resource requirements and suffers due to detection lag and other reasons mentioned earlier. Therefore, in order to maximize throughput, we need to act pro-actively, i.e anticipate the resource demand before it happens and act on its onset, which forms the primary objective of \textit{Beacons} Framework. \subsection{Overall Framework} Beacons framework consists of a \textbf{Compilation Component} (Fig. \ref{fig:system}), which in turn comprises of a sequence of compilation, training, and re-compilation steps to instrument the application; all of these steps are applied statically. Several challenges are overcome by to produce the above information at loop entrances. Beacons consist of statically inserted code at the entrances of the loops that evaluate closed-form formulae \& static learning models for predicting various artifacts related to loop's resource requirement. Other aspects, e.g. the amount of time a region executes, can be predicted \& enhanced by employing machine learning mechanisms that involves training. During runtime this information is evaluated by beacons using actual dynamic values and is conveyed to the beacons scheduler through library calls, which form the \textbf{Beacons Runtime Component} (Fig. \ref{fig:system}). The scheduler aggregates and analyzes this information across all the processes, constructing a global picture about contentions, the sensitivity to them, and moreover the duration of contentions. For the purposes of this paper, the resource under contention is the last level cache and memory bandwidth shared by all the processes in the machine. Since the resource demand and duration (loop timings) information is known to the scheduler {\it before} the loop executes, the scheduler is able to take pro-active scheduling decisions overcoming the afore-mentioned limitations of reactive approaches. \begin{figure*} \includegraphics[width=1.0\linewidth]{figs/new_beacons_compiler.jpg} \caption{\small Beacons Compilation Component Workflow. The source code is translated into IR with LLVM front-end and is subjected to various `beacon' compiler passes to generate the loop and memory profile information. The IR is then instrumented with beacons information to broadcast information at the runtime to the Beacons Scheduler with the help of Beacons library. }\label{fig:system} \end{figure*} \begin{figure}[!ht] \centering\includegraphics[width=1.0\columnwidth]{figs/RuntimeComponent.png} \caption{\small Beacons Runtime Component} \label{fig:bes_runtime} \end{figure} \section{Related Works} \label{sec:related} \textbf{Conservative scheduling}~\cite{yang2003conservative} presents a learning-based technique for load prediction on a processing node. The load information at a processing node over time is extrapolated to predict load at a future time. Task scheduling is done based on predicted future load over a time window. A compiler-driven approach to reduce power consumption by inserting statements to shut down functional units through a profile-driven approach in areas of a program where no access to the units happens is proposed in \cite{rele2002optimizing}; it uses a profile-driven approach that predicts the future execution paths and the latency. \textbf{Profile-based scheduling}: Prediction of applications' upcoming phases by using a combination of offline and online profiling is proposed in ~\cite{shen2004locality,padmanabha2013trace}. Similarly, another approach~\cite{sashaThroughputScheduling} uses a reuse distance model for simple caches calculated by profiling on a simulator for predicting L2 cache usage. A cache-aware scheduling algorithm is proposed in \cite{DBLP:conf/usenix/FedorovaSSN05}. It monitors cache usage of threads at runtime and attempts to schedule groups of threads that stay within the cache threshold. It is not compiler-driven, nor sensitive to phase changes within the threads. Several efforts have focused on the development of scheduling infrastructure for the shared server platforms~\cite{bubbleflux,bubbleup,deepdive,fedorova,priyanka:socc14}. A key feature of these efforts is their use of observation-based methods (i.e. reactive approaches) to establish resource contention (e.g. for caches, memory bandwidth, or other platform resources) and to further determine the interference at runtime, and/or to assess the workloads' sensitivity to the contended resource(s) by profiling.
{'timestamp': '2021-11-02T01:16:02', 'yymm': '2103', 'arxiv_id': '2103.06647', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06647'}
arxiv
\section{Introduction} \vspace{-1pt} \begin{figure}[!htb] \centering \subfloat[\label{fig:intro0}]{\includegraphics[width=0.24\textwidth]{intro0.pdf}} \subfloat[\label{fig:intro1}]{\includegraphics[width=0.24\textwidth]{intro1.pdf}} \caption{MagFace learns for (a) in-the-wild faces (b) a universal embedding by pulling the easier samples closer to the class center and pushing them away from the origin $o . As shown in our experiments and supported by mathematical proof, the magnitude $l$ before normalization increases along with feature's cosine distance to its class center, and therefore reveals the quality for each face. The larger the $l$, the more likely the sample can be recognized.} \label{fig:intro} \end{figure} Recognizing face in the wild is difficult mainly due to the large variability exhibited by face images acquired in unconstrained settings. This variability is associated to the image acquisition conditions (such as illumination, background, blurriness, and low resolution), factors of the face (such as pose, occlusion and expression) or biases of the deployed face recognition system~\cite{Kolf1}. To cope with these challenges, most relevant face analysis system under unconstrained environment (\eg, surveillance video) consists of three stages: 1) \textbf{face acquisition} to select from a set of raw images or capture from video stream the most suitable face image for recognition purpose; 2) \textbf{feature extraction} to extract discriminative representation from each face image; 3) \textbf{facial application} to match the reference image towards a given gallery or cluster faces into groups of same person. To acquire the optimal reference image in the first stage, a technique called face quality assessment~\cite{Best-Rowden2017,schlett2020face} is often employed on each detected face. Although the ideal quality score should be indicative of the face recognition performance, most of early work~\cite{ISO, ICAO} estimates qualities based on human-understandable factors such as luminances, distortions and pose angles, which may not directly favor the face feature learning in the second stage. Alternatively, learning-based methods~\cite{Best-Rowden2017, Hernandez-ortega} train quality assessment models with artificially or human labelled quality values. Theses methods are error-prone as there lacks of a clear definition of quality and human may not know the best characteristics for the whole systems. To achieve high end-to-end application performances in the second stage, various metric-learning~\cite{schroff2015facenet, sohn2016improved} or classification losses~\cite{Yuan2018,Ranjan2017,Liu2017,guo2020learning, Wang2018,Deng2018,cao2020domain} emerged in the past few years. These works learn to represent each face image as a deterministic point embedding in the latent space regardless of the variance inherent in faces. In reality, however, low-quality or large-pose images like Fig.~\ref{fig:intro0} widely exist and their facial features are ambiguous or absent. Given these challenges, a large shift in the embedded points is inevitable, leading to false recognition. For instance, performance reported by prior state-of-the-art~\cite{Shi2019} on IJB-C is much lower than LFW. Recently, confidence-aware methods~\cite{Shi2019,Chang2020} propose to represent each face image as a Gaussian distribution in the latent space, where the mean of the distribution estimates the most likely feature values while the variance shows the uncertainty in the feature values. Despite the performance improvement, these methods seek to separate the face feature learning from data noise modeling. Therefore, additional network blocks are introduced in the architecture to compute the uncertainty level for each image. This complicates the training procedure and adds computational burden in inference. In addition, the uncertainty measure cannot be directed used in conventional metrics for comparing face features. This paper proposes MagFace to learn a universal and quality-aware face representation. The design of MagFace follows two principles: 1) Given the face images of the same subject but in different levels of quality (\eg, Fig.~\ref{fig:intro0}), it seeks to learn a within-class distribution, where the high-quality ones stay close to the class center while the low-quality ones are distributed around the boundary. 2) It should pose the minimum cost for changing existing inference architecture to measure the face quality along with the computation of face feature. To achieve the above goals, we choose magnitude, the independent property to the direction of the feature vector, as the indicator for quality assessment. The core objective of MagFace is to not only enlarge inter-class distance, but also maintain a cone-like within-class structure like Fig.~\ref{fig:intro1}, where ambiguous samples are pushed away from the class centers and pulled to the origin. This is realized by adaptively down-weighting ambiguous samples during training and rewarding the learned feature vector with large magnitude in the MagFace loss. To sum up, MagFace improves previous work in two aspects: \begin{enumerate} \itemsep0em \item For the first time, MagFace explores the complete set of two properties associated with feature vector, direction and magnitude, in the problem of face recognition while previous works often neglect the importance of the magnitude by normalizing the feature. With extensive experimental study and solid mathematical proof, we show that the magnitude can reveal the quality of faces and can be bundled with the characteristics of recognition without any quality labels involved. \item MagFace explicitly distributes features structurally in the angular direction (as shown in Fig.~\ref{fig:intro1}). By dynamically assigning angular margins based on samples' hardness for recognition, MagFace prevents model from overfitting on noisy and low-quality samples and learns a well-structured distributions that are more suitable for recognition and clustering purpose. \end{enumerate} \section{Related Works} \vspace{-1pt} \begin{figure*}[!htb] \centering \subfloat[]{\includegraphics[width=0.25\textwidth]{method_0.pdf}\label{fig:method0}} \subfloat[]{\includegraphics[width=0.25\textwidth]{method_1.pdf}\label{fig:method1}} \subfloat[]{\includegraphics[width=0.25\textwidth]{method_2.pdf}\label{fig:method2}} \subfloat[]{\includegraphics[width=0.25\textwidth]{method_3.pdf}\label{fig:method3}} \caption{Geometrical interpretation of the feature space (without normalization) optimized by ArcFace and MagFace. (a) Two-class distributions optimized by ArcFace, where $w$ and $w'$ are the class centers and their decision boundaries $B$ and $B'$ are separated by the additive margin $m$. Circle 1, 2, 3 represent three types samples of class $w$ with descending qualities. (b) MagFace introduces $m(a_i)$ which dynamically adjust boundaries based on feature magnitudes, and ends to a new feasible region. (c) Effects of $g(a_i)$ and $m(a_i)$. (d) Final feature distributions of our MagFace. \textbf{Best viewed in color.}} \label{fig:method} \end{figure*} \subsection{Face Recognition} \vspace{-3pt} Recent years have witnessed the breakthrough of deep convolutional face recognition techniques. A number of successful systems, such as DeepFace~\cite{taigman2014deepface}, DeepID~\cite{sun2015deepid3}, FaceNet~\cite{schroff2015facenet} have shown impressive performance on face identification and verification. Apart from the large-scale training data and deep network architectures, the major advance comes from the evolution of training losses for CNN. Most of early works rely on metric-learning based loss, including contrastive loss~\cite{chopra2005learning}, triplet loss~\cite{schroff2015facenet}, n-pair loss~\cite{sohn2016improved}, angular loss~\cite{wang2017deep}, \etc. Suffering from the combinatorial explosion in the number of face triplets, embedding-based method is usually inefficient in training on large-scale dataset. Therefore, the main body of research in deep face recognition has focused on devising more efficient and effective classification-based loss. Wen \etal~\cite{wen2016discriminative} develop a center loss to learn centers for each identity to enhance the intra-class compactness. $L_2$-softmax~\cite{Ranjan2017} and NormFace~\cite{Wang2017} study the necessity of the normalization operation and applied $L_2$ normalization constraint on both features and weights. From then on, several angular margin-based losses, such as SphereFace~\cite{Liu2017}, AM-softmax~\cite{wang2018additive}, SV-AM-Softmax~\cite{Wang2018_sv}, CosFace~\cite{Wang2018}, ArcFace~\cite{Deng2018}, progressively improve the performance on various benchmarks to the newer level. More recently, AdaptiveFace~\cite{liu2019adaptiveface}, AdaCos~\cite{zhang2019adacos} and FairLoss~\cite{liu2019fair} introduce adaptive margin strategy to automatically tune hyperparameters and generate more effective supervisions during training. Compared to our method, all these work tend to suppress the effect of magnitude in the loss by normalizing the feature vector. \subsection{Face Quality Assessment} \vspace{-3pt} Face image quality is an important factor to enable high-performance face recognition systems~\cite{Best-Rowden2017}. Traditional methods, such as ISO/IEC 19794-5 standard~\cite{ISO}, ICAO 9303 standard~\cite{ICAO}, Brisque~\cite{sun2015no}, Niqe~\cite{Mittal2013} and Piqe~\cite{venkatanath2015blind}, describe qualities from image-based aspects (\eg, distortion, illumination and occlusion) or subject-based measures (\eg, accessories). Learning-based approaches such as FaceQNet~\cite{Hernandez-ortega} and Best-Rowden~\cite{Best-Rowden2017} regress qualities by networks trained on human-assessed and similarity-based labels. However, these quality labels are error-prone as human may not know the best characteristics for the recognition system and therefore cannot consider all proper factors. Recently, several uncertainty-based methods are proposed to express face qualities by the uncertainties of features. SER-FIQ~\cite{Kolf1} forwards an image to a network with dropout several times and measures face quality by the variation of extracted features. Confidence-aware face recognition methods~\cite{Shi2019,Chang2020} propose to represent each face image as a Gaussian distribution in the latent space and learn the uncertainty in the feature values. Although these methods work in an unsupervised manner like ours, they require additional computational costs or network blocks, which complicate their usage in conventional face systems. \subsection{Face Clustering} \vspace{-3pt} Face clustering exploits unlabeled data to cluster them into pseudo classes. Traditional clustering methods usually work in an unsupervised manner, such as K-means~\cite{lloyd1982least}. DBSCAN~\cite{ester1996density} and hierarchical clustering. Several supervised clustering methods based on graph convolutional network (GCN) are proposed recently. For example, L-GCN~\cite{wang2019linkage} performs reasoning and infers the likelihood of linkage between pairs in the sub-graphs. Yang \etal~\cite{yang2020learning} designs two graph convolutional networks, named GCN-V and GCN-E, to estimate the confidence of vertices and the connectivity of edges, respectively. Instead of developing clustering methods, we aim at improving feature distribution structure for clustering. \section{Methodology} \vspace{-1pt} \begin{figure*}[h] \centering \subfloat[Softmax]{\includegraphics[width=0.33\textwidth]{baseline_softmax.pdf}\label{fig:data1}} \subfloat[ArcFace]{\includegraphics[width=0.33\textwidth]{baseline_arc.pdf}\label{fig:data2}} \subfloat[MagFace]{\includegraphics[width=0.33\textwidth]{mf_10_110_04_08_50.pdf}\label{fig:data3}} \caption{Visualization of feature magnitudes and difficulties for recognition. Models are trained on MS1M-V2~\cite{guo2016ms,Deng2018} and 512 samples of the last iteration are used for visualization. Negative losses are used to reveal the hardness for Softmax while we use cosine value of $\theta$ (angle between a feature and its class center) for ArcFace and MagFace.} \label{fig:data_example} \end{figure*} In this section, we first review the definition of ArcFace~\cite{Deng2018}, one of the most popular losses used in face recognition. Based on the analysis of ArcFace, we then derive the objective and prove the key properties for MagFace. In the end, we compare softmax and ArcFace with MagFace from the perspective of feature magnitude. \subsection{ArcFace Revisited} \vspace{-3pt} Training loss plays an important role in face representation learning. Among the various choices (see \cite{du2020elements} for a recent survey), ArcFace~\cite{Deng2018} is perhaps the most widely adopted one in both academy and industry application due to its easiness in implementation and state-of-the-art performance on a number of benchmarks. Suppose that we are given a training batch of $N$ face samples $\{f_i, y_i\}_{i=1}^N$ of $n$ identities, where $f_i \in \mathbb{R}^d$ denotes the $d$-dimensional embedding computed from the last fully connected layer of the neural networks and $y_i = 1, \cdots, n$ is its associated class label. ArcFace and other variants improve the conventional softmax loss by optimizing the feature embedding on a hypersphere manifold where the learned face representation is more discriminative. By defining the angle $\theta_j$ between $f_i$ and $j$-th class center $w_j \in \mathbb{R}^d$ as $w_j^T f_i = \|w_j\|\|f_i\|\cos\theta_j$, the objective of ArcFace~\cite{Deng2018} can be formulated as \small \begin{align} L = -\frac{1}{N}\sum_{i=1}^{N} \log \frac{e^{s\cos{(\theta_{y_i}+ m)}}}{ e^{s\cos{(\theta_{y_i}+m)}} + \sum_{j\neq y_i} e^{s \cos{\theta_j}}}, \label{eq:arcloss} \end{align} \normalsize where $m>0$ denotes the additive angular margin and $s$ is the scaling parameter. Despite its superior performances on enforcing intra-class compactness and inter-class discrepancy, the angular margin penalty $m$ used by ArcFace is quality-agnostic and the resulting structure of the within-class distribution could be arbitrary in unconstrained scenarios. For example, let us consider the scenario illustrated in Fig.~\ref{fig:method0}, where we have face images of the same class in three levels of qualities indicated by the circle sizes: the larger the radius, the more uncertain the feature representation and the more difficulty the face can be recognized. Because ArcFace employs a uniform margin $m$, each image in one class shares the same decision boundary, \ie, $B: \cos(\theta + m) = \cos(\theta^{\prime})$ with respect to the neighbor class. The three types of samples can stay at arbitrary location in the feasible region (shading area in Fig.~\ref{fig:method0}) without any penalization by the angular margin. This leads to unstable within-class distribution, \eg, the high-quality face (type 1) stay along the boundary $B$ while the low-quality ones (type 2 and 3) are closer to the center $w$. This unstableness can hurt the performances on in-the-wild recognition as well as other facial application such as face clustering. Moreover, hard and noisy samples are over-weighted as they are hard to stay in the feasible area and the models may overfit to them. \subsection{MagFace} \label{subsec:magface} \vspace{-3pt} Based on the above analysis, previous cosine-similarity-based face recognition loss lacks more fine-grained constraint beyond a fixed margin $m$. This leads to unstable within-class structure especially in the unconstrained case (\eg, Fig.~\ref{fig:method0}) where the variability of each subject's faces is large. To address the aforementioned problem, this section proposes MagFace, a novel framework to encode quality measure into the face representation. Unlike previous work \cite{Shi2019,Chang2020} that call for additional uncertainty term, we pursue a minimalism design by optimizing over the magnitude $a_i = \|f_i\|$ without normalization of each feature $f_i$. Our design has two major advantages: 1) We can keep using the cosine-based metric that has been widely adopted by most existing inference systems; 2) By simultaneously enforcing its direction and magnitude, the learned face representation is more robust to the variability of faces in the wild. To our best understanding, this is the first work to unify the feature magnitude as quality indicator in face recognition. Before defining the loss, let us first introduce two auxiliary functions related to $a_i$, the magnitude-aware angular margin $m(a_i)$ and the regularizer $g(a_i)$. The design of $m(a_i)$ follows a natural intuition: for high-quality samples $x_i$, they should concentrate in a small region around the cluster center $w$ with high certainty. By assuming a positive correlation between the magnitude and quality, we thereby penalize more on $x_i$ in terms of $m(a_i)$ if its magnitude $a_i$ is large. To have a better understanding, Fig.~\ref{fig:method1} visualizes the margins $m(a_i)$ corresponding to different magnitude values. In contrast to ArcFace (Fig.~\ref{fig:method0}), the feasible region defined by $m(a_i)$ has a shrinking boundary with respect to feature magnitude towards the class center $w$. Consequently, this boundary pulls the low-quality samples (circle 2 and 3 in Fig.~\ref{fig:method2}) to the origin where they have lower risk to be penalized. However, the structure formed solely by $m(a_i)$ is unstable for high-quality samples like circle 1 in Fig.~\ref{fig:method2} as they have large freedom moving inside the feasible region. We therefore introduce the regularizer $g(a_i)$ that rewards sample with large magnitude. By designing $g(a_i)$ as a monotonically decreasing convex function with respect to $a_i$, each sample would be pushed towards the boundary of the feasible region and the high-quality ones (circle 1) would be dragged closer to the class center $w$ as shown in Fig.~\ref{fig:method3}. In a nutshell, MagFace extends ArcFace (Eq.~\ref{eq:arcloss}) with magnitude-aware margin and regularizer to enforce higher diversity for inter-class samples and similarity for intra-class samples by optimizing: \small \begin{align} L_{Mag} &= \frac{1}{N}\sum_{i=1}^{N} L_i, \quad \text{where} \label{eq:magloss} \\ L_i &= -\log \frac{e^{s\cos{(\theta_{y_i}+ m(a_i))}}}{ e^{s\cos{(\theta_{y_i}+m(a_i))}} + \sum_{j\neq y_i} e^{s \cos{\theta_j}}} + \lambda_g g(a_i). \nonumber \end{align} \normalsize The hyper-parameter $\lambda_g$ is used to trade-off between the classification and regularization losses. The design of MagFace not only follows intuitive motivations, but also yields result with theoretical guarantees. Assuming the magnitude $a_i$ is bounded in $[l_a, u_a]$, where $m(a_i)$ is a strictly increasing convex function, $g(a_i)$ is a strictly decreasing convex function and $\lambda_g$ is large enough, we can prove (see detailed requirements and proofs in the supplementary) that the following two properties of MagFace loss always hold when optimizing $L_i$ over $a_i$: \begin{prop1*} For $a_i \in [l_a, u_a]$, $L_i$ is a strictly convex function which has a unique optimal solution $a_i^*$. \end{prop1*} \begin{prop2*} The optimal $a_i^*$ is monotonically increasing as the cosine-distance to its class center decreases and the cos-distances to other classes increase. \end{prop2*} The property of convergence guarantees the unique optimal solution for $a_i$ as well as the fast convergence. The property of monotonicity states that the feature magnitudes reveal the difficulties for recognition, therefore can be treated as a metric for face qualities. \subsection{Analysis on Feature Magnitude} \label{subsec:magnitude} \vspace{-3pt} To better understand the effect of the MagFace loss, we conduct experiments on the widely used MS1M-V2~\cite{Deng2018} dataset and investigate for the training examples at convergence the relation between the feature magnitude and their similarity with class center as shown in Fig.~\ref{fig:data_example}. \textbf{Softmax.} The classical softmax-based loss underlies the objective of the pioneer work~\cite{taigman2014deepface,sun2014deep} on deep face recognition. Without explicit constraint on magnitude, the value of the negative loss for each sample is almost independent to its magnitude as observed from Fig.~\ref{fig:data1}. As pointed in \cite{Ranjan2017,Wang2017}, softmax tends to create a radial feature distribution because softmax loss acts as the soft version of max operator and scaling the feature magnitude does not affect the assignment of its class. To eliminate this effect, \cite{Ranjan2017,Wang2017} suggest that using normalized feature would benefit the task. \textbf{ArcFace.} ArcFace can be considered as a special case of MagFace when $m(a_i) = m$ and $g(a_i)=0$. As shown in Fig.~\ref{fig:data2}, high-quality samples with large similarity $\cos(\theta)$ to class center yield large variation in magnitude. This evidence echos our motivation on the unstable structure defined by a fixed angular margin in ArcFace for easy samples. On the other hand, for low-quality samples that are difficult to be recognized ($\cos(\theta)$ is small), the fixed angular margin determines the magnitude needs to be large enough in order to fit inside the feasible region (Fig.~\ref{fig:method0}). Therefore, there is a decreasing low bound for feature magnitudes \wrt the quality of face as indicated by the dash line in Fig.~\ref{fig:data2}. \textbf{MagFace.} In contrast to ArcFace, our MagFace optimizes the feature with adaptive margin and regularization based on its magnitude. Under this loss, it is clear to observe from Fig.~\ref{fig:data3} that there is a strong correlation between the feature magnitudes and their cosine similarities with class center. Those examples at the upper-right corner are the most high-quality ones. As the magnitude becomes smaller, the examples are more deviated from the class center. This distribution strongly supports the fact that the feature magnitude learned by MagFace is a good metric for face quality. \section{Experiments} \vspace{-1pt} \begin{figure*}[htb!] \centering \subfloat[][mean: 22.84 \\ range: (-$\infty$, 24) \\ \# of faces: 3692 ]{\includegraphics[width=0.12\textwidth]{meanface_0_3692_2284.jpg}} \subfloat[][mean: 25.13 \\ range: [24, 26) \\ \# of faces: 9955 ]{\includegraphics[width=0.12\textwidth]{meanface_1_9955_2513.jpg}} \subfloat[][mean: 27.03 \\ range: [26, 28) \\ \# of faces: 15459]{\includegraphics[width=0.12\textwidth]{meanface_2_15459_2703.jpg}} \subfloat[][mean: 29.03 \\ range: [28, 30) \\ \# of faces: 17565]{\includegraphics[width=0.12\textwidth]{meanface_3_17565_2903.jpg}} \subfloat[][mean: 31.01 \\ range: [30, 32) \\ \# of faces: 20627]{\includegraphics[width=0.12\textwidth]{meanface_4_20627_3101.jpg}} \subfloat[][mean: 32.99 \\ range: [32, 34) \\ \# of faces: 19743]{\includegraphics[width=0.12\textwidth]{meanface_5_19743_3299.jpg}} \subfloat[][mean: 34.80 \\ range: [34, 36) \\ \# of faces: 11238]{\includegraphics[width=0.12\textwidth]{meanface_6_11238_3480.jpg}} \subfloat[][mean: 36.55 \\ range: [36, $\infty$) \\ \# of faces: 1721]{\includegraphics[width=0.12\textwidth]{meanface_7_1689_3655.jpg}} \vspace{4pt} \caption{Visualization of the mean faces of 100k images sampled from the IJB-C dataset. Each mean face corresponds to a group of faces based on the magnitude level of the features learned by MagFace. } \label{fig:quality} \end{figure*} In this section, we examine the proposed MagFace on three important face tasks: face recognition, quality assessment and face clustering. Sec.~C in the supplementary presents the ablation study on relationships between margin distributions and recognition performances. \subsection{Face Recognition} \label{sec:exp_fr} \vspace{-3pt} \noindent \textbf{Datasets.} The original MS-Celeb-1M dataset~\cite{guo2016ms} contains about 10 million images of 100k identities. However, it consists of a great many noisy face images. Instead, we employ MS1M-V2~\cite{Deng2018} (5.8M images, 85k identities) as our training dataset. For evaluation, we adopt LFW~\cite{huang2008labeled}, CFP-FP~\cite{sengupta2016frontal}, AgeDB-30~\cite{moschoglou2017agedb}, CALFW~\cite{zheng2017cross}, CPLFW~\cite{zheng2018cross}, IJB-B~\cite{whitelam2017iarpa} and IJB-C~\cite{maze2018iarpa} as the benchmarks. All the images are aligned to $112\times 112$ by following the setting in ArcFace. \noindent \textbf{Baselines.} We re-implement state-of-the-art baselines including Softmax, SV-AM-Softmax~\cite{Wang2018_sv}, SphereFace~\cite{Liu2017}, CosFace~\cite{Wang2018}, ArcFace~\cite{Deng2018}. ResNet100 is equipped as the backbone. We use the recommended hyperparameters for each model, \eg, $s=64$, $m=0.5$ for ArcFace. \noindent \textbf{Training.} We train models on 8 1080Tis by stochastic gradient descent. The learning rate is initialized from 0.1 and divided by 10 at 10, 18, 22 epochs, and we stop the training at the 25th epoch. The weight decay is set to 5e-4 and the momentum is 0.9. We only augment training samples by random horizontal flip. For MagFace, we fix the upper bound and lower bound of the magnitude as $l_a=10, u_a=110$. $m(a_i)$ is chosen to be a linear function and $g(a_i)$ as a hyperbola. For detailed definition of $m(a_i)$, $g(a_i)$ and $\lambda_g$, please refer to Sec.~B2 in the supplementary. In the end, our mean margin as well as other hyperparameters are all consistent with ArcFace. \noindent \textbf{Test.} During testing, cosine distance is used as metric on comparing 512-D features. For evaluations on IJB-B/C, one identity can have multiple images. The common way to represent for an identity is to sum up the normalized feature $f_i^{norm} = \frac{f_i}{\|f_i\|}$ of each image and then normalize the embedding for comparisons, \ie, $f=\frac{\sum_i f_i^{norm}}{\| \sum_i f_i^{norm} \|}$. One benefit of MagFace is that we can assign quality-aware weight $\|f_i\|$ to each normalized feature $f_i^{norm}$. Therefore, we further evaluate ``MagFace+'' in Tab.~\ref{table:fr_ijb} by computing the identity embedding as $f_+=\frac{\sum_i f_i}{\| \sum_i f_i \|}$. \setlength{\tabcolsep}{4pt} \begin{table} \begin{center} \footnotesize{ \begin{tabular}{l|ccccc} \hline Method & LFW & CFP-FP & AgeDB-30 & CALFW & CPLFW \\ \hline \hline Softmax & 99.70 & 98.20 & 97.72 & 95.65 & 92.02 \\ SV-AM-Softmax~\cite{Wang2018_sv}& 99.50 & 95.10 & 95.68 & 94.38 & 89.48 \\ SphereFace~\cite{Liu2017} & 99.67 & 96.84 & 97.05 &95.58 & 91.27\\ CosFace~\cite{Wang2018} & 99.78 & 98.26 & \textbf{98.17} & \textbf{96.18} & 92.18\\ ArcFace~\cite{Deng2018} & 99.81 & 98.40 & 98.05 & 95.96 & 92.72\\ \rowcolor{Gray} MagFace & \textbf{99.83} & \textbf{98.46} & \textbf{98.17} & 96.15 & \textbf{92.87} \\ \hline \end{tabular} } \end{center} \caption{Verification accuracy (\%) on easy benchmarks.} \label{table:fr_faces} \end{table} \setlength{\tabcolsep}{1.4pt} \noindent \textbf{Results on LFW, CFP-FP, AgeDB-30, CALFW and CPLFW.} We directly use the aligned images and protocols adopted by ArcFace~\cite{Deng2018} and present our results in Tab.~\ref{table:fr_faces}. We note that performances are almost saturated. Compared to CosFace which is the second best baseline, ArcFace achieves $0.03\%, 0.14\%, 0.54\%$ improvement on LFW, CFP-FP and CPLFW, while drops $0.12\%, 0.22\%$ on AgeDB-30 and CALFW. MagFace obtains the overall best results and surpasses ArcFace by $0.02\%$, $0.06\%$, $0.12\%$, $0.19\%$ and $0.15\%$ on five benchmarks respectively. \setlength{\tabcolsep}{4pt} \begin{table} \begin{center} \footnotesize{ \begin{tabular}{lcccccc} \hline Method & \multicolumn{3}{c}{IJB-B (TAR@FAR)} & \multicolumn{3}{c}{IJB-C (TAR@FAR)} \\ \cline{2-7} & 1e-6 & 1e-5 & 1e-4 & 1e-6 & 1e-5 & 1e-4 \\ \hline VGGFace2*~\cite{cao2018vggface2} & - & 67.10 & 80.00 & - & 74.70 & 84.00 \\ CenterFace*~\cite{wen2016discriminative} & - & - & - & - & 78.10 & 85.30 \\ CircleLoss*~\cite{Sun2020} &-&-&-&-&89.60&93.95\\ ArcFace*~\cite{Deng2018} & - & - & 94.20 & - & - & 95.60 \\ \hline Softmax & \textbf{46.73} &75.17&90.06 &64.07 &83.68 &92.40\\ SV-AM-Softmax~\cite{Wang2018_sv}& 29.81 & 69.25 & 84.79 & 63.45 & 80.30 & 88.34 \\ SphereFace~\cite{Liu2017} & 39.40& 73.58 & 89.19 & 68.86 & 83.33 & 91.77 \\ CosFace~\cite{Wang2018} & 40.41& 89.25 & 94.01 & 87.96 & 92.68 & 95.56\\ ArcFace~\cite{Deng2018} & 38.68 & 88.50 & 94.09 & 85.65 & 92.69 & 95.74 \\ \rowcolor{Gray} MagFace & 40.91 & 89.88 & 94.33 & 89.26 & 93.67 & 95.81 \\ \rowcolor{Gray} MagFace+ & 42.32 & \textbf{90.36} & \textbf{94.51} & \textbf{90.24} & \textbf{94.08} & \textbf{95.97} \\ \hline \end{tabular} } \end{center} \caption{Verification accuracy (\%) on difficult benchmarks. ``*'' indicates the result quoted from the original paper.} \label{table:fr_ijb} \end{table} \setlength{\tabcolsep}{1.4pt} \noindent \textbf{Results on IJB-B/IJB-C.} The IJB-B dataset contains 1,845 subjects with 21.8K still images and 55K frames from 7,011 videos. As the extension of IJB-B, the IJB-C dataset covers about 3,500 identities with a total of 31,334 images and 117,542 unconstrained video frames. In the 1:1 verification, the number of positive/negative matches are 10k/8M in IJB-B and 19k/15M in IJB-C. We report the TARs at FAR=1e-6, 1e-5 and 1e-4 as shown in Tab.~\ref{table:fr_ijb}. Our implemented ArcFace is on par with the original paper, \eg, our TARs at FAR=1e-4 differ from the authors by $-0.11\%$ and $+0.14\%$ on IJB-B and IJB-C respectively. Compared to baselines, our MagFace remains the top at all FAR criteria except for FAR=1e-6 on IJB-B as the TAR is very sensitive to the noise when the number of FP is tiny. Compared to CosFace, MagFace gains $0.50\%, 0.63\%, 0.32\%$ on IJB-B at TAR@FAR=1e-6, 1e-5, 1e-4 and $1.30\%, 0.99\%, 0.25\%$ on IJB-C. Compared to ArcFace, improvements are of $2.23\%, 1.38\%, 0.24\%$ on IJB-B and $3.61\%, 0.98\%, 0.07\%$ on IJB-C respectively. This result demonstrates the superiority of MagFace on more challenging benchmarks. It is worth to mention that when multiple images existed for one identity, the average embedding can be further improved by aggregating features weighted by magnitudes. For instance, MagFace+ outperforms MagFace by $1.41\%/0.98\%$ at FAR=1e-6, $0.48\%/0.41\%$ at FAR=1e-5 and $0.18\%/0.16\%$ at FAR=1e-4. \subsection{Face Quality Assessment}\label{sec:exp_fq} \vspace{-3pt} \begin{figure}[htb!] \centering \includegraphics[width=0.4\textwidth]{qlt_dist.pdf} \caption{Distributions of magnitudes on different datasets. } \label{fig:dist_qlt} \end{figure} \begin{figure*}[!htb] \centering \subfloat[LFW - ArcFace]{\includegraphics[trim=20 5 50 30,clip, width=0.45\textwidth]{qlt_lfw_arc.pdf}} \subfloat[LFW - MagFace]{\includegraphics[trim=20 5 50 30,clip,width=0.45\textwidth]{qlt_lfw.pdf}}\\ \vspace{-12pt} \subfloat[CFP-FP - ArcFace]{\includegraphics[trim=20 5 50 30,clip, width=0.45\textwidth]{qlt_cfp_arc.pdf}} \subfloat[CFP-FP - MagFace]{\includegraphics[trim=20 5 50 30,clip, width=0.45\textwidth]{qlt_cfp.pdf}}\\ \vspace{-12pt} \subfloat[AgeDB-30 - ArcFace]{\includegraphics[trim=20 5 50 30,clip, width=0.45\textwidth]{qlt_agedb_arc.pdf}} \subfloat[AgeDB-30 - MagFace]{\includegraphics[trim=20 5 50 30,clip, width=0.45\textwidth]{qlt_agedb.pdf}}\\ \caption{Face verification performance for the predicted face quality values with two evaluation models (ArcFace and MagFace). The curves show the effectiveness of rejecting low-quality face images in terms of false non-match rate (FNMR). \textbf{Best viewed in color.}} \label{fig:qlt_fnmr} \end{figure*} In this part, we investigate the qualitative and quantitative performance of the pre-trained MagFace model mentioned in Tab.~\ref{table:fr_ijb} for quality assessment. \noindent \textbf{Visualization of the mean face.} We first sample 100k images form IJB-C database and divide them into 8 groups based on feature magnitudes. We visualize the mean faces of each group in Fig.~\ref{fig:quality}. It can be seen that when magnitude increases, the corresponding mean face reveals more details. This is because high-quality faces are inclined to be more frontal and distinctive. This implies the magnitude of MagFace feature is a good quality indicator. \noindent \textbf{Sample distribution of datasets.} Fig.~\ref{fig:dist_qlt} plots the sample histograms of different benchmarks with respect to MagFace magnitudes. We observe that LFW is the least noisy one where most samples are of large magnitudes. Due to the larger age variation, the distribution of AGEDB-30 slightly shifts left compared to LFW. For CFP-FP, there are two peaks at the magnitude around 28 and 34, corresponding to the frontal and profile faces respectively. Given the large variations in face qualities, we can conclude IJB-C is much more challenging than other benchmarks. For images (more examples can be found in the supplementary) with magnitudes $a \simeq 15$, there are no faces or very noisy faces to observe. When feature magnitudes increase from 20 to 40, there is a clear trend that the face changes from profile, blurred and occluded, to more frontal and distinctive. Overall, this figure convinces us that MagFace is an effective tool to rank face images according to their qualities. \noindent \textbf{Baselines.} We choose six baselines of three types for quantitative quality evaluation. Brisque~\cite{sun2015no}, Niqe~\cite{Mittal2013} and Piqe~\cite{venkatanath2015blind} are image-based quality metrics. FaceQNet~\cite{Hernandez-ortega} and SER-FIQ~\cite{Kolf1} are face-based ones. For FaceQNet, we adopt the released models by the authors. For SER-FIQ, we use the ``same model'' version which yields the best performance in the paper. Following the authors' setting, we set $m=100$ to forward each image 100 times with drop-out active in inference. As a related work, we re-implement the recent DUL~\cite{Chang2020} method that can estimate uncertainty along with the face feature. \noindent \textbf{Evaluation metric.} Following previous work~\cite{Grother2007, Kolf1, Best-Rowden2017}, we evaluate the quality assessment on LFW/CFP-FP/AgeDB via the error-versus-reject curves, where images with the lowest predicted qualities are unconsidered and error rates are calculated on the remaining images. Error-versus-reject curve indicates good quality estimation when the verification error decreases consistently while increasing the ratio of unconsidered images. To compute the feature for verification, we adopt the ArcFace* as well as our MagFace models in Tab.~\ref{table:fr_ijb}. \noindent \textbf{Results on face verification.} Fig.~\ref{fig:qlt_fnmr} shows the error-versus-reject curves of different quality methods in terms of false non-match rate (FNMR) reported at false match rate (FMR) threshold of 0.001. Overall, we have two high-level observations. 1) The curves on CFP-FP and AgeDB-30 are much more smooth than the ones obtained on LFW. This is because CFP-FP and AgeDB-30 consist of faces with larger variations in pose and age. Effectively dropping low-quality faces can benefit the verification performance more on these two benchmarks. 2) No matter computing the feature from ArcFace (left column) or MagFace (right column), the curves corresponding to MagFace magnitude are consistently the lowest ones across different benchmarks. This indicates that the performance of MagFace magnitude as quality generalizes well across datasets as well as face features. We then analyze the quality performance of each type of methods. 1) The image-based quality metrics (Brisque~\cite{sun2015no}, Niqe~\cite{Mittal2013}, Piqe~\cite{venkatanath2015blind}) lead to relatively higher errors in most cases as the image quality alone is not suitable for generalized face quality estimation. Factors of the face (such as pose, occlusions, and expressions) and model biases are not covered by these algorithms and might play an important role for face quality assessment. 2) The face-based methods (FaceQNet~\cite{Hernandez-ortega} and SER-FIQ~\cite{Kolf1}) outperforms other baselines in most cases. In particular, SER-FIQ is more effective than FaceQNet in terms of the verification error rates. This is due to the fact that SER-FIQ is built on top of the deployed recognition model so that its prediction is more suitable for the verification task. However, SEQ-FIQ takes a quadratic computational cost \wrt the number of sub-networks $m$ randomly sampled using dropout. In contrary, the neglectable overhead of computing magnitude makes the proposed MagFace more practical in many real-time scenarios. Moreover, the training of MagFace does not require explicit labeling of face quality, which is not only time consuming but also error-prone to obtain. 3) At last, the uncertainty method (DUL) performs well on CFP-FP but yields more verification errors on AgeDB-30 when the proportion of unconsidered images is increased. This may indicate that the Gaussian assumption of data variance in DUL is over-simplified such that the model cannot generalize well to different kinds of quality factors. \subsection{Face Clustering}\label{sec:exp_fc} \vspace{-3pt} In this section, we conduct experiments on face clustering to further investigate the structure of feature representations learned by MagFace. \begin{figure}[!htb] \centering \includegraphics[trim=30 0 30 40,clip, width=0.4\textwidth]{cluster_vis.pdf} \caption{Visualization of MagFace magnitudes of 500 samples from IJB-B-1845 \wrt their confidences of being class centers.} \label{fig:cluster_vis} \end{figure} \noindent \textbf{Baselines.} We compare the performances of MagFace and ArcFace by integrating their features with various clustering methods. For fair comparisons, we constrain hyperparameters of the two models to be consistent (\eg, s=64, mean margin 0.5) during training. Four clustering methods are used in the evaluation: K-means~\cite{lloyd1982least}, AHC~\cite{sarle1990algorithms}, DBSCAN~\cite{ester1996density} and L-GCN~\cite{wang2019linkage}. For non-deterministic algorithms (K-means and AHC), we report the average results from 10 runs. For L-GCN, we train the model on CASIA-WebFace~\cite{yi2014learning} (0.5M images from 10k individuals) and follow the recommended settings in the paper~\cite{wang2019linkage}. \noindent \textbf{Benchmarks.} We adopt the IJB-B~\cite{whitelam2017iarpa} dataset as the benchmark as it contains a clustering protocol of seven sub-tasks varying in the number of ground truth identities. Following~\cite{wang2019linkage}, we evaluate on three largest sub-tasks where the numbers of identities are 512, 1,024 and 1,845, and the numbers of samples are 18,171, 36,575 and 68,195, respectively. Normalized mutual information (NMI) and BCubed F-measure~\cite{amigo2009comparison} are employed as the evaluation metrics. \setlength{\tabcolsep}{4pt} \begin{table} \begin{center} \resizebox{0.47\textwidth}{!}{% \begin{tabular}{lccccccc} \hline Method & Net & \multicolumn{2}{c}{IJB-B-512} & \multicolumn{2}{c}{IJB-B-1024} & \multicolumn{2}{c}{IJB-B-1845} \\ \cline{3-8} & & F & NMI & F & NMI & F & NMI \\ \hline \hline K-means~\cite{lloyd1982least} & ArcFace & 66.70 & 88.83 & 66.82 & 89.48 & 66.93 & 89.88 \\ \rowcolor{Gray1} \cellcolor{white} & MagFace & \textbf{66.75} & \textbf{88.86} & \textbf{67.33}& \textbf{89.62} & \textbf{67.06} & \textbf{89.96} \\ AHC~\cite{sarle1990algorithms} & ArcFace & 69.72 & 89.61 & 70.47 & 90.54 & 70.66 & 90.90 \\ \rowcolor{Gray1} \cellcolor{white} & MagFace & \textbf{70.24} & \textbf{89.99} & \textbf{70.68} & \textbf{90.67} & \textbf{70.98}& \textbf{91.06} \\ DBSCAN~\cite{ester1996density} & ArcFace & 72.72 & 90.42 & 72.50 & 91.15 & 73.89 & 91.96 \\ \rowcolor{Gray1} \cellcolor{white} & MagFace & \textbf{73.13}& \textbf{90.61} & \textbf{72.68}& \textbf{91.30} & \textbf{74.26}& \textbf{92.13} \\ L-GCN~\cite{wang2019linkage} & ArcFace & 84.92 & 93.72 & 83.50 & 93.78 & 80.35 & 92.30 \\ \rowcolor{Gray1} \cellcolor{white} & MagFace & \textbf{85.27} & \textbf{93.83} & \textbf{83.79} & \textbf{94.10} & \textbf{81.58} & \textbf{92.79} \\ \hline \end{tabular} } \end{center} \caption{F-score (\%) and NMI (\%) on clustering benchmarks.} \label{table:clustering1} \end{table} \setlength{\tabcolsep}{1.4pt} \noindent \textbf{Results.} Tab.~\ref{table:clustering1} summarizes the clustering results. We can observe that with stronger clustering methods from K-means to L-GCN, the overall clustering performance can be improved. For any combination of clustering and protocol, MagFace always achieves better performance than ArcFace in terms of both F-score and NMI metrics. This consistent superiority demonstrates the MagFace feature is more suitable for clustering. Notice that we keep the same hyperparameters for clustering. The improvement of using MagFace must come from its better within-class feature distribution, where the high-quality samples around the class center are more likely to be separated across different classes. We further explore the relationship between feature magnitudes and the confidences of being class centers. Following the idea mentioned in \cite{yang2020learning}, the confidence of being a class center for each sample is estimated based on its neighbor structure defined by face features. The samples with dense and pure local connection have high confidence, while those with sparse connections or residing in the boundary among several clusters have low confidence. From Fig.~\ref{fig:cluster_vis}, it is easy to observe that the MagFace magnitude is positively correlated with confidence of class center on the IJB-B-1845 benchmark. This result reflects that the MagFace feature exhibits the expected within-class structure, where high quality samples distribute around class center while low quality ones are far away from the center. \section{Conclusion} \vspace{-1pt} In this paper, we propose MagFace to learn unified features for face recognition and quality assessment. By pushing ambiguous samples away from class centers, MagFace improves the within-class feature distribution from previous margin-based work for face recognition. The adequate theoretical and experimental results convince that MagFace can simultaneously access quality for the input face image. As a general framework, MagFace can be potentially extended to benefit other classification tasks such as fine-grained object recognition, person re-identification. Moreover, the proposed principle of exploring feature magnitude paves the way to estimate quality for other objects, \eg, person body in reid or action snippet in activity classification. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2021-07-27T02:34:36', 'yymm': '2103', 'arxiv_id': '2103.06627', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06627'}
arxiv
\section{Introduction and Motivation} \label{sec:Introduction} Due to the growing complexity of modern cellular networks, network optimization and control constitutes one of the main challenges. It is desirable by the Mobile Network Operators (MNOs) that the configuration is adjusted automatically in order to ensure acceptable Quality of Service (QoS) to each user connected to the network. In such application, the goal is to optimize a set of network KPIs such as \emph{coverage}, \emph{quality} and \emph{capacity} and to guarantee that certain bounds of these KPIs are not violated (safety specifications). This optimization is performed by adjusting the vertical electrical tilt of each of the antennas of the given network, known in the literature as remote electrical tilt (RET) optimization problem \cite{guo2013spectral, razavi2010fuzzy, fan2014self, buenestado2016self}. Reinforcement learning (RL) \cite{sutton2018reinforcement, mnih2015human, garcia2015comprehensive, bouton2020point} has become a powerful solution for dealing with the problem of optimal decision making for agents interacting with uncertain environments. However, it is known that the large-scale exploration performed by RL algorithms can sometimes take the system to unsafe states \cite{garcia2015comprehensive}. In the problem of RET optimization, RL has been proven to be an effective framework for KPI optimization due to its self-learning capabilities and adaptivity to potential environment changes \cite{vannella2020off}. For addressing the safety problem (i.e., to guarantee that the desired KPIs remain in specified bounds) authors in \cite{vannella2020off} have proposed a statistical approach to empirically evaluate the RET optimization in different baseline policies and in different worst-case scenarios. The aforementeioned statistical approach focus on ensuring the reward value remains above a desired baseline. However, more widely accepted notions of safety are expressed in terms of safe states, defined according to a (formal) intent specification \cite{fulton2018safe}. The approach in \cite{fulton2018safe} decouples the notion of safety from that of reward. Intuitively, safety intents define the boundaries within which the RL agent may be free to explore. Motivated by the abovementioned, in this work, we demonstrate a novel approach for guaranteeing safety in RET optimization problem by using model-checking techniques and in parallel, we seek to generalize the problem in order to facilitate richer specifications than safety. In order to express desired specifications to the network into consideration, LTL is used (see \cite{katoen, loizou_2004, alex_automatica_2017, alex_PhD}), due to the fact that it provides a powerful mathematical formalism for such purpose. Our proposed demonstration exhibits the following attributes: \begin{enumerate} \item a general automatic framework from LTL specification user input to the derivation of the policy that fulfills it; at the same time, blocking the control actions that violate the specification; \item novel system dynamics abstraction to companions Markov Decision Processes (MDP) which is computationally efficient; \item UI development that allows the user to graphically access all the steps of the proposed approach. \end{enumerate} \textbf{Related work}. Authors in \cite{alshiekh2018safe} propose a safe RL approach through shielding. However, they assume that the system dynamics abstraction into an MDP is given, which is challenging in network applications that this demonstration refers to. As mentioned previously, authors in \cite{vannella2020off} address the safe RET optimization problem, but this approach relies on statistical guarantees and it cannot handle general LTL specifications that we treat with this manuscript \begin{figure*} \centering \includegraphics[width=12.0cm,height=7.0cm]{framework-new.png} \caption{A graphical illustration of the proposed architecture.} \label{fig:test1} \end{figure*} \begin{figure*} \centering \includegraphics[width=15.0cm,height=6.0cm]{ui-map-mdpB-4.png} \caption{A graphical illustration of the UI for the demonstration of the approach. The user can chose: the desired LTL formula, the resulting BA; and the evolution of the RL agent training and the actions blocked by the safety shield.} \label{fig:UI} \end{figure*} \section{Demonstration} Our key contribution is a proposed architecture which allows for intent specifications in RL, demonstrated in a real-world example. Here we focus on task specifications given in LTL. The syntax of LTL (see \cite{katoen}) over a set of atomic propositions $\Sigma$ is defined by the grammar $$\varphi := \top \ | \ \varsigma \ | \ \neg \varphi \ | \ \varphi_1 \wedge \varphi_2 \ | \ \bigcirc \varphi \ | \ \varphi_1 \ \mathfrak{U} \ \varphi_2 \ | \ \Diamond \varphi \ | \ \square \varphi,$$ where $\varsigma \in \Sigma$ and $\bigcirc$, $\mathfrak{U}$, $\Diamond$, $\square$ operators stand for the next, until, eventually and always operators, respectively; $\neg$ and $\wedge$ are the negation and conjunction operator respectively. Every LTL formula can be translated to a B\"uchi Automaton (BA) that models all the system traces satisfying the formula \cite{gastin2001fast}. Consider a geographic area covered by Radio Base Stations (RBS) and cells that serve a set of UEs uniformly distributed in that area. The RET optimization problem has goal to maximize network capacity and coverage while minimizing interference between the antennas. The RET control strategy handles the antenna tilt of each of the cells (agents), and is executed independently for each cell. The environment of the RL agents is a simulated mobile network as it can be seen in Fig. \ref{fig:UI}. The system dynamical model is captured through an MDP $(\mathcal{S}, \mathcal{A}, \mathcal{P}, \mathcal{R}, \gamma)$ where: $\mathcal{S}$ are the states consisting of values for down-tilt and KPIs (coverage, capacity and quality); actions $\mathcal{A} = \{\text{downtilt}, 0, \text{uptilt}\}$; transition probability matrix $\mathcal{P}$ which describes the state evolution given the current and the executed by the action state; rewards $\mathcal{R}$; and, discount factor $\gamma$. The RL agent's policy $\pi: \mathcal{S} \to \mathcal{A}$ is a function that maps the states to actions that define the agent's strategy. Our solution takes a sequence of steps to match the LTL specification with the RL agent as it is depicted in Fig. \ref{fig:test1} and block the actions that lead to unsafe states. Initially, the desired user specification is translated into LTL logic and subsequently into a BA. Then, by gathering the experience data tuples from the RL agent which is trained to a simulation environment with state-of-the-art model-free RL algorithms (DQN, Q-learning, SARSA \cite{guo2013spectral, razavi2010fuzzy, fan2014self, buenestado2016self}) we construct the system dynamics modelled as an MDP. In this solution, we have a novel structure known as Companion MDPs (CMDPs). CMDPs encode the state transitions only in terms of the subset of features specified in the intent, not the full set of state features. This reduces the state space complexity, and keeps only the relevant features depending on the intent. An MDP matching component matches the intent to the relevant CMDP (depending on the features mentioned in the intent). The experience data tuples that are generated during training are in the form $(s, a, r, s')$ where $s$ indicates the current state, $a$ the executed action, $r$ the received reward that the agent receives after applying action $a$ at state $s$; and $s'$ the state the agent transitions to after executing action $a$ at state $s$. In order to match the BA from the given LTL specification and the MDP, the states of the MDP are labelled according to the atomic propositions from the LTL specification. Then, by computing the product of the MDP with the specification, we construct: an automaton $\mathcal{A}_{\varphi}$ that models all the system behaviours over the given specification; an automaton $\mathcal{A}_{\neg \varphi}$ that models all the traces violating the specification. Then, by utilizing graph techniques and model checkers, we are able to find all the system traces violating the specification (w.r.t the trained MDP); if no safe traces are found from all states in the MDP, the user specification cannot be satisfied, which means that the LTL has to be modified (or relaxed). If there exist some unsafe and some safe traces, then the process moves to a shield strategy that blocks the actions that lead to unsafe traces. This process is depicted more formally in Fig. 1 and Algorithm 1. \section{Discussions} \textbf{Interaction with the UI}. The UI is designed to be used by a network operations engineer who can specify safety intents, monitor tilts and their impact, and supervise the RL agent's operation. The initial screen of the UI depicts a geographic area with the available radio sites and cells. By clicking to one of the cells, a new screen appears with the KPI values depicted on the left. On the right part of the page, one can see: 1) the MDP system model; 2) a list of available LTL intents; 3) BAs representing each of the intents; 4) the button "Run safe RL" to run the simulation; and 5) the switch "with/without shield" for enabling the safety shield. The chosen actions on the MDP are depicted in blue, while the blocked actions by the shield are depicted in red. The user can view the training process and the optimal choice of actions that guarantee the satisfaction of given input as well as the block of unsafe actions. The current high level of detail in the UI is meant to illustrate the technology, it can be imagined that a production UI would instead show a summary of selected and blocked actions instead of large MDP models. The impact of the shield may also be viewed, and it is seen that the shield blocks a proportion of unsafe states (leading to 639 unsafe states instead of 994 without the shield). Interestingly, the shield also leads to a 68$\%$ improvement in the reward values. The video accompanying this paper can be found in:\\ \hspace{-5mm} \url{https://www.ericsson.com/en/reports-and-papers/research-papers/safe-ran-control} \\ \textbf{Applicability to other domains.} The proposed architecture is general and it can be applied to any framework in which the under consideration dynamical system is abstracted into an MDP, while LTL specifications need to be fulfilled. For example, in a robot planning applications, the states are locations of the environment that the robot can move, and atomic propositions are the goal state and the obstacles. The LTL formula of such application would include reachability and safety tasks. \textbf{Conclusions and future work.} In this paper, we have demonstrated an architecture for network KPIs optimization guided by user-defined intent specifications given in LTL. Our solution consists of MDP system dynamics abstraction, automata construction and products and model-checking techniques to block undesired actions that violate the specification. Future research directions will be devoted towards applying the proposed framework in other telecom use cases as well as in robotics (motion planning). \textbf{Acknowledgements.} The authors thank Ezeddin Al Hakim, Jaeseong Jeong, Maxime Bouton, Swarup Mohalik, Pooja Kashyap and Athanasios Karapantelakis for the fruitful discussion in topics related to this work and support in the simulation environment. Moreover, special thanks to Ericsson Research for supporting and funding our work. \begin{algorithm}[t!] \caption{} \begin{algorithmic}[1] \footnotesize{ \item[]\textbf{Input:} User specification $\varphi$ \STATE\textbf{Gather} experience replay $(s, a, r, s')$ from data; \STATE\textbf{Discretize} states into $N_{b}$. State space size is $|\mathcal{S}|^{N_b}$; \STATE\textbf{Construct} the MDP dynamics $(\mathcal{S}, \mathcal{A}, \mathcal{P}, \mathcal{R}, \gamma)$; \STATE\textbf{Translate} the LTL formula $\Phi$ to a BA $\mathcal{A}_{\varphi}$; \STATE\textbf{Compute} the product $\mathcal{T} = MDP \otimes \mathcal{A}_{\varphi}$ and pass it to model checker; \STATE\textbf{Model checking} returns traces that violate $\varphi$; \STATE\textbf{If} no safe traces found \textbf{Modify/Relax} $\varphi$ \STATE\textbf{Else} Block unsafe actions by function \textit{Shield}(MDP, $\mathcal{T}$). } \end{algorithmic} \end{algorithm} \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-03-12T02:19:43', 'yymm': '2103', 'arxiv_id': '2103.06602', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06602'}
arxiv
\section{Introduction} The {\em $p$-th R\'{e}nyi entropy} \cite{Cover1992,Gardner2002} of a probability density function $f: \mathbb{R}^n\rightarrow \mathbb{R}$ is defined as \begin{eqnarray} \label{I1} H_p(f):=\dfrac{1}{1-p}{\rm log}\int_{\mathbb{R}^n}f^p(x)dx, \end{eqnarray} for $0<p<+\infty$, $p\neq1$. The $p$-th R\'{e}nyi entropy power is given by \begin{eqnarray}\label{I2} N_p(f):={\rm exp}(\frac{\mu}{n}H_p(f)), \end{eqnarray} where $\mu$ is a real valued parameter. The R\'{e}nyi entropy for $p=1$ is defined as the limit of $H_p(f)$ as $p\rightarrow1$. It follows from definition \eqref{I1} that \begin{eqnarray*} H_1(f)=\underset{p\rightarrow1}{\rm lim}H_p(f)=-\int_{\mathbb{R}^n}f(x){\rm log}f(x)dx, \end{eqnarray*} which is Shannon's entropy. In this case, the proposed R\'{e}nyi entropy power of index $p=1, \mu=2$, given by \eqref{I2}, coincides with Shannon's entropy power \begin{eqnarray} \label{I3} N_1(f):={\rm exp}(\dfrac{2}{n}H_1(f)). \end{eqnarray} Shannon's {\em entropy power inequality (EPI)} is one of the most important information inequalities~\cite{Shannon1948}, which has many proofs, generalizations, and applications~\cite{Stam1959,Blachman1965,Lieb1978,VerduGuo2006,Rioul2011,Bergmans1974,Zamir1993,Liu2007,Wang2013}. In particular, Costa presented a stronger version of the EPI~\cite{Costa1985}. Let $X_t\triangleq X+N_n(0,tI)$ be the $n$-dimensional random vector introduced by Costa~\cite{Costa1985,GYG2020,GYG2020M} and $u(x_t)$ the {\em probability density} of $X_t$, which solves the heat equation in the whole space $\mathbb{R}^n$, \begin{eqnarray} \label{HeatEqu1} \dfrac{\partial}{\partial t}u(x_t)=\Delta u(x_t). \end{eqnarray} {\em Costa's differential entropy} is defined to be {\begin{equation} \label{1.1} H(u(x_t))=-\int_{{\mathbb{R}}^n} u(x_t)\log u(x_t){\hbox{\rm{d}}} x_t. \end{equation}} Costa~\cite{Costa1985} proved that the {\em Shannon entropy power} $N(u)=\frac{1}{2\pi e}e^{(2/n)H(u)}$ is a concave function in $t$, that is $({\hbox{\rm{d}}}/{\hbox{\rm{d}}} t)N(u)\ge0$ and $({\hbox{\rm{d}}}^2/{\hbox{\rm{d}}}^2 t)N(u)\le0$. Several new proofs and generalizations for Costa's EPI were given~\cite{Dembo1989,Villani2000,Toscani2015}. Savar\'{e}-Toscani~\cite{Savare2014} proved that the {\em concavity of entropy power} is a property which is not restricted to the Shannon entropy power \eqref{I3} in connection with the heat equation \eqref{HeatEqu1}, but it holds for the $p$-th R\'{e}nyi entropy power \eqref{I2}. They put it in connection with the solution to the {\em nonlinear heat equation} \begin{eqnarray} \label{HeatEqu2} \dfrac{\partial}{\partial t}u(x_t)=\Delta u(x_t)^p \end{eqnarray} posed in the whole space $\mathbb{R}^n$ and $p\in{\mathbb{R}}_{>0}$. In this paper, we give a generalization for {\em concavity of $p$-th R\'{e}nyi entropy power (CREP)}. Precisely, we give a propositional logic formula $\Phi(n,p,\mu)$ such that if $n\in{\mathbb{N}},p,\mu\in{\mathbb{R}}$ satisfy this formula, then the CREP holds. The condition $\Phi(n,p,\mu)$ extends the parameter's range of the CREP given by Savar\'{e}-Toscani~\cite{Savare2014} and contains much more cases. The formula $\Phi$ is obtained using a systematic procedure which can be considered as a parametric version of that given in \cite{GYG2020,GYG2020M,Zhang2018}, where parameters $n,p,\mu$ exist in the formulas. The procedure reduces the proof of the CREP to check the semi-positiveness of a quadratic form whose coefficients are polynomials in the parameters $n,p,\mu$. In principle, a necessary and sufficient condition for the parameters to satisfy this property can be computed with the quantifier elimination~\cite{QE}. In this paper, the problem is special and an explicit proof is given. The rest of this paper is organized as follows. In Section 2, we give the proof procedure and to prove concavity of entropy powers in the parametric case. In Section 3, we present the generalized version of CREP using the proof procedure. In Section 4, conclusions are presented. \section{Proof Procedure} \label{sec-2} In this section, we give a procedure to prove the { CREP}. To make the paper concise, we only give those steps that are needed in this paper. \subsection{Notations} Let $x_t=[x_{1,t},x_{2,t},\ldots,x_{n,t}]$ be a set of variables depending on $t$ and $$ \begin{aligned} {\hbox{\rm{d}}}^{(i)} x_t={\hbox{\rm{d}}} x_{1,t}{\hbox{\rm{d}}} x_{2,t}\ldots {\hbox{\rm{d}}} x_{i-1,t}{\hbox{\rm{d}}} x_{i+1,t}\ldots {\hbox{\rm{d}}} x_{n,t}, i=1,2\ldots,n. \end{aligned} $$ Let $[n]_0 = \{0,1,\ldots,n\}$ and $[n] = \{1,\ldots,n\}$. To simplify the notations, we use $u$ to denote $u(x_t)$ in the rest of the paper. Denote {\footnotesize $$\mathcal{P}_{n} =\{\frac{\partial^h u}{\partial^{h_1} x_{1,t}\cdots \partial^{h_n} x_{n,t}}: h = \sum_{i=1}^n h_i, h_i\in {\mathbb{N}}\}$$} to be the set of all derivatives of $u$ with respect to the differential operators $\frac{\partial}{\partial x_{i,t}},i=1,\ldots,n$ and $${\mathcal{R}}={\mathbb{R}}[n,p,\mu][\mathcal{P}_{n}]$$ to be the set of polynomials in $\mathcal{P}_{n}$ with coefficients in ${\mathbb{R}}[n,p,\mu]$, where $n,p,\mu$ are parameters. For $v\in\mathcal{P}_{h,n}$, let ${\rm{ord}}(v)$ be the order of $v$. For a monomial $\prod_{i=1}^r v_i^{d_i}$ with $v_i\in {\mathcal{P}}_{n}$, its {\em degree}, {\em order}, and {\em total order} are defined to be $\sum_{i=1}^r d_i$, $\max_{i=1}^r {\rm{ord}}(v_i)$, and $\sum_{i=1}^r d_i\cdot {\rm{ord}}(v_i)$, respectively. A polynomial in ${\mathcal{R}}$ is called a $k$th-order {\em differentially homogenous polynomial} or simply a $k$th-order {\em differential form}, if all its monomials have degree $k$ and total order $k$. Let ${\mathcal{M}}_{k,n}$ be the set of all monomials which have degree $k$ and total order $k$. Then the set of $k$th-order differential forms is an ${\mathbb{R}}$-linear vector space generated by ${\mathcal{M}}_{k,n}$, which is denoted as ${\hbox{\rm{Span}}}_{\mathbb{R}}({\mathcal{M}}_{k,n})$. We will use Gaussian elimination in ${\hbox{\rm{Span}}}_{\mathbb{R}}({\mathcal{M}}_{k,n})$ by treating the monomials as variables. We always use the {\em lexicographic order for the monomials} defined in \cite{GYG2020,GYG2020M}. \subsection{The proof procedure} \label{sec-p2} In this section, we give the procedure to prove the {\em CREP}. The property $\frac{{\hbox{\rm{d}}}}{{\hbox{\rm{d}}} t}N_p(u)\geq0$ can be easily proved~\cite{Savare2014}. We focus on proving $\frac{{\hbox{\rm{d}}}^2}{{\hbox{\rm{d}}}^2 t}N_p(u)\le0$. The procedure consists of four steps. In step 1, we reduce the proof of {\em CREP} into the proof of an integral inequality, as shown by the following lemma whose proof is given in section \ref{sec-p4}. \begin{lemma} \label{lm-pr1} Proof of $\frac{{\hbox{\rm{d}}}^2}{{\hbox{\rm{d}}}^2 t}N_p(u)\le0$ can be reduced to show \begin{equation} \label{eq-tt1} \begin{array}{ll} \displaystyle{\int_{{\mathbb{R}}^n}u^{3p-6}E_{2,n}{\hbox{\rm{d}}} x_t} \ge0 \end{array} \end{equation}} under the condition $p\geq1-\frac{\mu}{n}$, where $E_{2,n} =\sum_{a=1}^n\sum_{b=1}^n E_{2,n,a,b}$ is a $4$th-order differential form in ${\mathbb{R}}[n,p,\mu][{{\mathcal{P}}}_{2,n}]$ and \begin{equation} \label{eq-pm} {{\mathcal{P}}}_{2,n} =\{ \frac{\partial^h u}{\partial^{h_1} x_{a,t}\partial^{h_{2}} x_{b,t}}: h\in[3]_0; a,b\in[n]\}. \end{equation}} \end{lemma} Then the problem {$\frac{{\hbox{\rm{d}}}^2}{{\hbox{\rm{d}}}^2t}N_p(u)\leq0$} can be transformed to { $\int u^{3p-6}E_{2,n}{\hbox{\rm{d}}} x_t\geq0$}. Thus, Lemma \ref{lm-pr1} is proved. In step 2, we compute the constraints which are relations satisfied by the probability density $u$ of $X_t$. Since $E_{2,n}$ in \eqref{eq-tt1} is a $4$th-order differential form, we need only the constraints which are $4$th-order differential forms. A $4$th-order differential form $R$ is called an {\em equational or inequality constraint} if \begin{equation} \label{eq-c1} {\int_{{\mathbb{R}}^n}u^{3p-6}R{\hbox{\rm{d}}} x_t} =0 \hbox{ or } {\int_{{\mathbb{R}}^n}u^{3p-6}R{\hbox{\rm{d}}} x_t} \ge0. \end{equation} The method to compute the constraints is given in section \ref{sec-2oc}. Suppose that the equational and inequality constraints are respectively \begin{equation} \label{eq-cons} {\mathcal{C}}_{E} =\{R_i,\,|\, i=1,\ldots,N_1\}\hbox{ and } {\mathcal{C}}_{I} =\{I_i,\,|\, i=1,\ldots,N_2\}. \end{equation} In step 3, we find a propositional formula $\Phi(n,p,\mu)$ such that when $n,p,\mu\in{\mathbb{R}}$ satisfy $\Phi$, \begin{eqnarray} \label{eq-S1} \exists c_j, e_i\in{\mathbb{R}}, s.t. \,\, E_{2,n}-\sum_{i=1}^{N_1} e_i R_i -\sum_{j=1}^{N_2} c_j I_j =S\ge0 \hbox{ and } c_j\ge0,j=1,\ldots,n_2. \end{eqnarray} Details of this step and the formula $\Phi(n,p,\mu)$ are given in section \ref{sec-repi}. To summarize the proof procedure, we have \begin{theorem} \label{th-m1} The {\em CREP} is true if $\Phi(n,p,\mu)$ is valid. \end{theorem} \begin{proof} By Lemma \ref{lm-pr1}, we have the following proof: { \begin{equation} \label{eq-proof} \begin{aligned} &\int_{\mathbb{R}} u^{3p-6}{{E}_{2,n}}{\hbox{\rm{d}}} x_t\\ \overset{\eqref{eq-S1}}{=}&\int_{\mathbb{R}} u^{3p-6}({\sum_{i=1}^{N_1} e_i R_i+\sum_{j=1}^{N_2} c_j I_j+ S}){\hbox{\rm{d}}} x_t\\[0.1cm] \overset{S1}{=}&\int_{\mathbb{R}} u^{3p-6}(\sum_{j=1}^{N_2} c_j I_j+ S){\hbox{\rm{d}}} x_t\\[0.1cm] \overset{S2}{\geq} &\int_{\mathbb{R}} u^{3p-6}{S}{\hbox{\rm{d}}} x_t \overset{S3}{\geq}0. \end{aligned} \end{equation}} Equality S1 is true, because $R_i$ is a equational constraint. Inequality S2 is true, because $I_j$ is an inequality constraint. Inequality S3 is true, because $S\ge0$ under the condition $\Phi(n,p,\mu)$. \end{proof} \subsection{The equational constraints} \label{sec-2oc} In this section, we show how to find the second order equational constraints. A {\em second order equational constraint} is a $4$th-order differential form in ${\mathbb{R}}[n,p,\mu][{\mathcal{P}}_{2,n}]$ such that $\int_{{\mathbb{R}}^n}\ u^{3p-6}{R}\ {\hbox{\rm{d}}} x_t=0$. We introduce the following notations {\footnotesize \begin{equation} \label{eq-v2} {\mathcal V}_{a,b} =\{ \frac{\partial^h u}{\partial^{h_1} x_{a,t} \partial^{h_2} x_{b,t}}: h=h_1+h_2\in[3]_0\}, \end{equation}} where $a,b$ are variables taking values in $[n]$. Then ${\mathcal{P}}_{2,n}=\cup_{a=1}^n\cup_{b=1}^n {\mathcal{V}}_{a,b}$. We need the following property. \begin{property}\label{lemma4} Let $a,r,m_i,k_i \in {\mathbb{N}}_{>0}$ and $u^{(m_i)}$ an $m_i$th-order derivative of $u$. If $u(x_t)$ is a smooth, strictly positive and rapidly decaying probability density, then {\footnotesize \begin{equation}\label{lem4} \begin{aligned} \displaystyle{\int_{-\infty}^{\infty}\ldots\int_{-\infty}^{\infty}u^{3p-2}\left[\prod\limits_{i=1}^{r} \frac{[u^{(m_i)}]^{k_i}}{u^{k_i}}\right]\Bigg|_{x_{a,t}=-\infty}^{\infty}{\hbox{\rm{d}}}^{(a)}} x_t=0, \end{aligned} \end{equation}} with {\small $\sum_{i=1}^{r}k_im_i=4,\ \sum_{i=1}^{r}k_i=4$}. \end{property} When $p\geq2$, Property \ref{lemma4} follows from \cite{Treves2016}. While $0<p<2, p\neq1$, we make the assumption that $u(x_t)$ also satisfies Property \ref{lemma4}. Using Property \ref{lemma4}, we can compute the second order equational constraints using the method given in \cite{GYG2020,GYG2020M}: \begin{equation} \label{eq-2cons} {\mathcal{C}}_{2,n}=\{R_{i,a,b}\,:\,i=1,\ldots,28\}\subset{\mathbb{R}}[n,p,\mu][{\mathcal V}_{a,b}], \end{equation}} where $R_{i,a,b}$ can be found in the Appendix. Note that $a,b$ are variables taking values in $[n]$. We use an example to show how to obtain these constraints. Starting from a monomial $u\frac{\partial^2u}{\partial^2x_{a,t}}(\frac{\partial u}{\partial x_{a,t}})^2$ with degree 4 and total order 4, by integral by parts, we have \begin{equation}\begin{array}{ll} \int u^{3p-6}u\frac{\partial^2u}{\partial^2x_{a,t}}(\frac{\partial u}{\partial x_{a,t}})^2{\hbox{\rm{d}}} x_t\\ =\int_{-\infty}^{\infty}\ldots\int_{-\infty}^{\infty} [u^{3p-5}\frac{\partial u}{\partial x_{a,t}}(\frac{\partial u}{\partial x_{a,t}})^2]\Big|_{x_{a,t}=-\infty}^{\infty}{\hbox{\rm{d}}}^{(a)} x_t\\ -\int \frac{\partial u}{\partial x_{a,t}}[\frac{\partial}{\partial x_{a,t}}(u^{3p-5}(\frac{\partial u}{\partial x_{a,t}})^2)] {\hbox{\rm{d}}} x_t\\ \overset{\eqref{lem4}}{=}-\int \frac{\partial u}{\partial x_{a,t}}[\frac{\partial}{\partial x_{a,t}}(u^{3p-5}(\frac{\partial u}{\partial x_{a,t}})^2)] {\hbox{\rm{d}}} x_t. \end{array} \end{equation} Then, \begin{equation}\begin{aligned} \int u^{3p-6}u\frac{\partial^2u}{\partial^2x_{a,t}}(\frac{\partial u}{\partial x_{a,t}})^2 +\frac{\partial u}{\partial x_{a,t}}[\frac{\partial}{\partial x_{a,t}}(u^{3p-5}(\frac{\partial u}{\partial x_{a,t}})^2)]{\hbox{\rm{d}}} x_t\\ =\int u^{3p-6}[3p(\frac{\partial u}{\partial x_{a,t}})^4+3u\frac{\partial^2u}{\partial^2x_{a,t}}(\frac{\partial u}{\partial x_{a,t}})^2-5(\frac{\partial u}{\partial x_{a,t}})^4] {\hbox{\rm{d}}} x_t=0. \end{aligned}\end{equation} } We obtain a 2th-order constraint: $R_{1,a,b}=3p(\frac{\partial u}{\partial x_{a,t}})^4+3u\frac{\partial^2u}{\partial^2x_{a,t}}(\frac{\partial u}{\partial x_{a,t}})^2-5(\frac{\partial u}{\partial x_{a,t}})^4$. The other 27 constraints in ${\mathcal{C}}_{2,n}$ are obtained in the same way. \subsection{Proof of Lemma \ref{lm-pr1}} \label{sec-p4} We first prove several lemmas. \begin{lemma} \begin{equation}\begin{array}{ll} \frac{{\hbox{\rm{d}}} H_p(u)}{{\hbox{\rm{d}}} t}=\frac{p}{1-p}\frac{\int u^{p-1}\Delta u^p{\hbox{\rm{d}}} x_t}{\int u^p {\hbox{\rm{d}}} x_t},\label{dh1}\\ \end{array}\end{equation} \begin{equation} \frac{{\hbox{\rm{d}}}^2H_p(u)}{{\hbox{\rm{d}}}^2t}=\frac{p}{1-p}\frac{\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\int u^p{\hbox{\rm{d}}} x_t-p(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)^2}{(\int u^p{\hbox{\rm{d}}} x_t)^2}.\label{dh2} \end{equation}} \end{lemma} \begin{proof} By the definition of $p$-R\'{e}nyi entropy \eqref{I1}, we have {\scriptsize \begin{equation*}\begin{aligned} \frac{{\hbox{\rm{d}}} H_p(u)}{{\hbox{\rm{d}}} t}&=\frac{p}{1-p}\frac{\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t}{\int u^p {\hbox{\rm{d}}} x_t} =\frac{p}{1-p}\frac{\int u^{p-1}\Delta u^p{\hbox{\rm{d}}} x}{\int u^p {\hbox{\rm{d}}} x},\\ \frac{{\hbox{\rm{d}}}^2 H_p(u)}{{\hbox{\rm{d}}}^2t}&=\frac{p}{1-p}\frac{\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\int u^p{\hbox{\rm{d}}} x_t-\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t\frac{\partial}{\partial t}(\int u^{p}{\hbox{\rm{d}}} x_t)}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &\!\!\!\!=\frac{p}{1-p}\frac{\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\int u^p{\hbox{\rm{d}}} x_t-\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t\int pu^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &\!\!\!\!=\frac{p}{1-p}\frac{\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\int u^p{\hbox{\rm{d}}} x_t-p(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)^2}{(\int u^p{\hbox{\rm{d}}} x_t)^2}. \end{aligned}\end{equation*} } \end{proof} \begin{lemma} We have {\footnotesize \begin{eqnarray}\label{T1} \int u^{p-1}\Delta u^p{\hbox{\rm{d}}} x_t=\int\Delta u^{p-1} u^p{\hbox{\rm{d}}} x_t. \end{eqnarray}} \end{lemma} \begin{proof} Integrating by parts\cite{Savare2014}, we have {\footnotesize $$\int u^{p-1}\Delta u^p{\hbox{\rm{d}}} x_t=-\int\nabla u^{p-1}\nabla u^p{\hbox{\rm{d}}} x_t=\int\Delta u^{p-1} u^p{\hbox{\rm{d}}} x_t.$$ } \end{proof} \begin{lemma} By Cauchy-Schwarz inequality we have {\footnotesize \begin{eqnarray}\label{T2} (\int \Delta u^{p-1} u^p{\hbox{\rm{d}}} x_t)^2\leq\int u^p{\hbox{\rm{d}}} x_t\int(\Delta u^{p-1})^2u^p{\hbox{\rm{d}}} x_t. \end{eqnarray}} \end{lemma} Then, we obtain \begin{equation}\label{dN2} \begin{array}{ll} \frac{{\hbox{\rm{d}}}^2}{{\hbox{\rm{d}}}^2t}N_p(u)&\!\!\!=\frac{\mu}{n}\frac{{\hbox{\rm{d}}}^2H_p(u)}{{\hbox{\rm{d}}}^2t}{\rm e}^{\frac{\mu}{n}H_p(u)}+\left(\frac{\mu}{n}\frac{{\hbox{\rm{d}}} H_p(u)}{{\hbox{\rm{d}}} t}\right)^2{\rm e}^{\frac{\mu}{n}H_p(u)}\\[0.2cm] &\!\!\!=\frac{\mu}{n}{\rm e}^{\frac{\mu}{n}H_p(u)}I_{2,n}, \end{array}\end{equation}} where {\footnotesize $I_{2,n}=\frac{{\hbox{\rm{d}}}^2H_p(u)}{{\hbox{\rm{d}}}^2t}+\dfrac{\mu}{n}\left(\frac{{\hbox{\rm{d}}} H_p(u)}{{\hbox{\rm{d}}} t}\right)^2$}. So, by \eqref{dh1},\eqref{dh2},we have \begin{equation}\label{T33} \begin{aligned} I_{2,n}&=\frac{p}{1-p}\frac{\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\int u^p{\hbox{\rm{d}}} x_t-p(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)^2}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &+\frac{\mu}{n}(\frac{p}{1-p}\frac{\int u^{p-1}\Delta u^p{\hbox{\rm{d}}} x_t}{\int u^p{\hbox{\rm{d}}} x_t})^2\\ &=\frac{\mu p^2}{n(1-p)^2}\frac{(\int u^{p-1}\Delta u^p{\hbox{\rm{d}}} x_t)^2}{(\int u^p{\hbox{\rm{d}}} x_t)^2}+\frac{p}{1-p}\frac{\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\int u^p{\hbox{\rm{d}}} x_t}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &-\frac{p^2}{1-p}\frac{(\int u^{p-1}\Delta u^p{\hbox{\rm{d}}} x_t)^2}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &=(\frac{\mu p^2}{n(1-p)^2}-\frac{p^2}{1-p})\frac{(\int u^{p-1}\Delta u^p{\hbox{\rm{d}}} x_t)^2}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &+\frac{p}{1-p}\frac{\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\int u^p{\hbox{\rm{d}}} x_t}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &\overset{\eqref{T1}}{=}\frac{(\mu-n(1-p))p^2}{n(1-p)^2}\frac{(\int \Delta u^{p-1}u^p{\hbox{\rm{d}}} x_t)^2}{(\int u^p{\hbox{\rm{d}}} x_t)^2} +\frac{p}{1-p}\frac{\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\int u^p{\hbox{\rm{d}}} x_t}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &\overset{(i)}{\leq}\frac{(\mu-n(1-p))p^2}{n(1-p)^2}\frac{\int u^p {\hbox{\rm{d}}} x_t\int (\Delta u^{p-1})^2u^p{\hbox{\rm{d}}} x_t}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &+\frac{p}{1-p}\frac{\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\int u^p{\hbox{\rm{d}}} x_t}{(\int u^p{\hbox{\rm{d}}} x_t)^2}\\ &=\frac{1}{\int u^p{\hbox{\rm{d}}} x_t}\left(\frac{(\mu-n(1-p))p^2}{n(1-p)^2}\int (\Delta u^{p-1})^2u^p{\hbox{\rm{d}}} x_t+\frac{p}{1-p}\frac{\partial}{\partial t}(\int u^{p-1}\frac{\partial u}{\partial t}{\hbox{\rm{d}}} x_t)\right)\\ &=\frac{1}{\int u^p{\hbox{\rm{d}}} x_t}\int\left(\frac{(\mu-n(1-p))p^2}{n(1-p)^2}(\Delta u^{p-1})^2u^p+\frac{p}{1-p}\frac{\partial}{\partial t}(u^{p-1}\frac{\partial u}{\partial t})\right){\hbox{\rm{d}}} x_t\\ &=\frac{1}{\int u^p{\hbox{\rm{d}}} x_t}\int F_{2,n}{\hbox{\rm{d}}} x_t, \end{aligned} \end{equation} } where $F_{2,n}=\frac{(\mu-n(1-p))p^2}{n(1-p)^2}(\Delta u^{p-1})^2u^p+\frac{p}{1-p}\frac{\partial}{\partial t}(u^{p-1}\frac{\partial u}{\partial t})$. { \textbf{Remark:} In \eqref{T33}, the step $(i)$ is according to \eqref{T2}, and $\frac{(\mu-n(1-p))p^2}{n(1-p)^2}\geq0$ should be satisfied, which is true under condition $p\geq1-\frac{\mu}{n}$. When $\mu:=2+n(p-1)$, $\frac{(\mu-n(1-p))p^2}{n(1-p)^2}\geq0$ yields $p\ge1-\frac{1}{n}$. Savar\'{e}-Toscani \cite{Savare2014} also used the inequality \eqref{T2}, but ignore the nonnegativity of the coefficient $\frac{(\mu-n(1-p))p^2}{n(1-p)^2}$, thus the parameter's range $p>1-\frac{2}{n}$ in \cite{Savare2014} should be corrected to $p\ge1-\frac{1}{n}$.} Further, we can get \begin{equation}\label{T333} \begin{aligned} F_{2,n}&=\frac{(\mu-n(1-p))p^2}{n(1-p)^2}u^p\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n} [(\frac{\partial^2}{\partial^2x_{a,t}}u^{p-1})(\frac{\partial^2}{\partial^2x_{b,t}}u^{p-1})]\\ &+\frac{p}{1-p}\frac{\partial}{\partial t}[u^{p-1}\sum\limits_{a=1}^{n}(\frac{\partial^2}{\partial^2x_{a,t}}u^{p})]\\ &=\frac{(\mu-n(1-p))p^2}{n(1-p)^2}u^p\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n} [(\frac{\partial^2}{\partial^2x_{a,t}}u^{p-1})(\frac{\partial^2}{\partial^2x_{b,t}}u^{p-1})]\\ &+\frac{p}{1-p}\sum\limits_{a=1}^{n}[(p-1)u^{p-2}(\frac{\partial^2}{\partial^2x_{a,t}}u^p)\frac{\partial u}{\partial t} +pu^{p-1}\frac{\partial^2}{\partial^2x_{a,t}}(u^{p-1}\frac{\partial u}{\partial t})]\\ &=\frac{(\mu-n(1-p))p^2}{n(1-p)^2}u^p\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n} [(\frac{\partial^2}{\partial^2x_{a,t}}u^{p-1})(\frac{\partial^2}{\partial^2x_{b,t}}u^{p-1})]\\ &+\frac{p}{1-p}\sum\limits_{a=1}^{n}\left[(p-1)u^{p-2}(\frac{\partial^2}{\partial^2x_{a,t}}u^p)\sum\limits_{b=1}^{n}(\frac{\partial^2}{\partial^2x_{b,t}}u^p)\right.\\ &\left.+pu^{p-1}\frac{\partial^2}{\partial^2x_{a,t}}(u^{p-1}\sum\limits_{b=1}^{n}(\frac{\partial^2}{\partial^2x_{b,t}}u^p))\right]\\ &=\frac{(\mu-n(1-p))p^2}{n(1-p)^2}u^p\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n} [(\frac{\partial^2}{\partial^2x_{a,t}}u^{p-1})(\frac{\partial^2}{\partial^2x_{b,t}}u^{p-1})]\\ &+\frac{p}{1-p}\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n}\left[(p-1)u^{p-2}(\frac{\partial^2}{\partial^2x_{a,t}}u^p)(\frac{\partial^2}{\partial^2x_{b,t}}u^p)\right.\\ &\left.+pu^{p-1}\frac{\partial^2}{\partial^2x_{a,t}}\left(u^{p-1}(\frac{\partial^2}{\partial^2x_{b,t}}u^p)\right)\right]\\ &=\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n}\mathcal{T}_{a,b}, \end{aligned}\end{equation}} where \begin{equation}\label{T334} \begin{aligned} \mathcal{T}_{a,b}&=\frac{(\mu-n(1-p))p^2}{n(1-p)^2}u^p [(\frac{\partial^2}{\partial^2x_{a,t}}u^{p-1})(\frac{\partial^2}{\partial^2x_{b,t}}u^{p-1})]\\ &+\frac{p}{1-p}\left[(p-1)u^{p-2}(\frac{\partial^2}{\partial^2x_{a,t}}u^p)(\frac{\partial^2}{\partial^2x_{b,t}}u^p)\right.\\ &\left.+pu^{p-1}\frac{\partial^2}{\partial^2x_{a,t}}\left(u^{p-1}(\frac{\partial^2}{\partial^2x_{b,t}}u^p)\right)\right]. \end{aligned}\end{equation}} For convenience, introduce the notation $u_{i,j}:=\frac{\partial^{i+j}u}{\partial^ix_{a,t}\partial^j x_{b,t}}$. By simple computation, we have {\footnotesize $\mathcal{T}_{a,b}=-\frac{u^{3p-6}p^2}{(p-1)n}T_{a,b}$}, and { \begin{equation} \label{eq-tab} \begin{aligned} T_{a,b}&=4np^4u_{0, 1}^2u_{1, 0}^2+2np^3uu_{0, 1}^2u_{2, 0} +8np^3uu_{0, 1}u_{1, 0}u_{1, 1}\\& +4np^3uu_{0, 2}u_{1, 0}^2-15np^3u_{0, 1}^2u_{1, 0}^2 -\mu p^3u_{0, 1}^2u_{1, 0}^2+2np^2u^2u_{0, 1}u_{2, 1}\\& +2np^2u^2u_{0, 2}u_{2, 0} +4np^2u^2u_{1, 0}u_{1, 2}+2np^2u^2u_{1, 1}^2-3np^2uu_{0, 1}^2u_{2, 0}\\& -20np^2uu_{0, 1}u_{1, 0}u_{1, 1}-8np^2uu_{0, 2}u_{1, 0}^2-\mu p^2uu_{0, 1}^2u_{2, 0} -\mu p^2uu_{0, 2}u_{1, 0}^2\\& +16np^2u_{0, 1}^2u_{1, 0}^2+5\mu p^2u_{0, 1}^2u_{1, 0}^2 +npu^3u_{2, 2}-2npu^2u_{0, 1}u_{2, 1}\\& -npu^2u_{0, 2}u_{2, 0}-4npu^2u_{1, 0}u_{1, 2} -2npu^2u_{1, 1}^2-\mu pu^2u_{0, 2}u_{2, 0}\\& -npuu_{0, 1}^2u_{2, 0} +12npuu_{0, 1}u_{1, 0}u_{1, 1}+2npuu_{0, 2}u_{1, 0}^2+3\mu puu_{0, 1}^2u_{2, 0}\\& +3\mu puu_{0, 2}u_{1, 0}^2-npu_{0, 1}^2u_{1, 0}^2-8\mu pu_{0, 1}^2u_{1, 0}^2-nu^2u_{0, 2}u_{2, 0}\\& +\mu u^2u_{0, 2}u_{2, 0}+2nuu_{0, 1}^2u_{2, 0}+2nuu_{0, 2}u_{1, 0}^2-2\mu uu_{0, 1}^2u_{2, 0}\\& -2\mu uu_{0, 2}u_{1, 0}^2-4nu_{0, 1}^2u_{1, 0}^2+4\mu u_{0, 1}^2u_{1, 0}^2, \end{aligned}\end{equation}} which is a 4th-order differential form. From \eqref{dN2}, \eqref{T33}, \eqref{T333}, and \eqref{T334}, we have \begin{equation}\label{E2n} \frac{{\hbox{\rm{d}}}^2}{{\hbox{\rm{d}}}^2t}N_p(u)\le-\frac{p^2\mu}{n^2}e^{\frac{\mu}{n}H_p(u)}\frac{1}{\int u^p{\hbox{\rm{d}}} x_t}\int u^{3p-6} E_{2,n}{\hbox{\rm{d}}} x_t \end{equation}} where {$E_{2,n}=\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n}\frac{T_{a,b}}{p-1}$} and $T_{a,b}$ is defined in \eqref{eq-tab}. Then the problem {$\frac{{\hbox{\rm{d}}}^2}{{\hbox{\rm{d}}}^2t}N_p(u)\leq0$} can be transformed to { $\int u^{3p-6}E_{2,n}{\hbox{\rm{d}}} x_t\geq0$}. Thus, Lemma \ref{lm-pr1} is proved. \section{A generalized version of CREP} \label{sec-repi} In this section, we prove a generalized CREP using the procedure given in section \ref{sec-2}. \begin{theorem} \label{th-main1} Let $u(x_t)$ be a probability density in ${\mathbb{R}}^n$ solving \eqref{HeatEqu2} and satisfying \eqref{lem4}. Then we give a formula $\Phi(n,p,\mu)$ such that the $p$-th R\'{e}nyi entropy power defined in \eqref{I2} satisfies \begin{eqnarray} \label{eq-soi1} \frac{{\hbox{\rm{d}}}^2}{{\hbox{\rm{d}}}^2t}N_p(x_t)\leq0, \end{eqnarray} under the condition $\Phi(n,p,\mu)$, that is $N_p(x_t)$ is concave under $\Phi(n,p,\mu)$. \end{theorem} The proof of the above theorem consists three steps which will be given in the following subsections. \subsection{Reduce to a finite problem} We first give an inequality constraint. Denote that $|\nabla^2f|^2=\sum_{i,j}(\frac{\partial^2f}{\partial x_{i}\partial x_{j}})^2$. Then, based on the trace inequality $|\nabla^2f|^2\geq\frac{1}{n}(\Delta f)^2$, we give a nonnegative constraint: \begin{equation} \label{eq-nc1} \begin{aligned} I_1=\frac{u^p}{u^{3p-6}}\left[|\nabla^2u^{p-1}|^2-\frac{1}{n}(\Delta u^{p-1})^2\right] =\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n}I_{1,a,b}\ge0 \end{aligned} \end{equation}} where { $I_{1,a,b}=u^{6-2p}\left[(\frac{\partial^2u^{p-1}}{\partial x_{a,t}\partial x_{b,t}})^2-\frac{1}{n}\frac{\partial^2u^{p-1}}{\partial^2x_{a,t}}\frac{\partial^2u^{p-1}}{\partial^2x_{b,t}}\right]$}. From \eqref{E2n} and \eqref{eq-nc1}, in order for \eqref{eq-soi1} to be true, it suffices to solve \\[0.1cm] \noindent{\bf Problem I}. Find a formula $\Phi(n,p,\mu)$ such that $$ \begin{array}{l} {E}_{2,n}\ge\widetilde{E}_{2,n}=E_{2,n}+c_1I_1=\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n}(\frac{1}{p-1}T_{a,b} + c_1I_{1,a,b}) \ge0 \end{array} $$} under the conditions $c_1\le0$, $p\ge1-\frac{\mu}{n}$, {$R_{i,a,b}=0,i=1,\ldots,28$} given in \eqref{eq-2cons}. Since {\small $\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n}T_{a,b}=\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n}T_{b,a}$} and $I_{1,a,b}=R^{(I)}_{1,b,a}$, we have \begin{equation} \label{eq-Lab} \begin{aligned} \widetilde{E}_{2,n}&=\frac{1}{2}\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n}[\frac{1}{p-1} (T_{a,b}+T_{b,a})+c_1(I_{1,a,b}+I_{1,b,a})]=\frac{1}{2}\sum\limits_{a=1}^{n}\sum\limits_{b=1}^{n}L_{a,b}, \end{aligned}\end{equation}} where {\small$L_{a,b}=\frac{1}{p-1}(T_{a,b}+T_{b,a})+c_1(I_{1,a,b}+I_{1,b,a})$}. \subsection{Simplify the problem with the constraints} From \eqref{eq-Lab}, to solve {\bf Problem I}, it suffices to solve \\[0.1cm] \noindent{\bf Problem II}. Find a formula $\Phi(n,p,\mu)$ such that $L_{a,b}\ge0$ under the conditions $c_1\le0$, $p\ge1-\frac{\mu}{n}$, and $R_{i,a,b}=0,i=1,\ldots,{28}$. In this section, we simplify $L_{a,b}$ in {\bf Problem II} with the constraints. Note that the subscripts $a$ and $b$ are fixed and will be treated as symbols. Our goal is to reduce $L_{a,b}$ into a quadratic form in certain new variables. The new variables are all the monomials in ${\mathbb{R}}[{\mathcal V}_{a,b}]$ with degree 2 and total order 2, where ${\mathcal V}_{a,b}$ is defined in \eqref{eq-v2}. $$ \begin{aligned} & m_1=uu_{0,2},\ m_2=uu_{1,1},\ m_3=uu_{2,0}\\ & m_4=u_{0,1}^2,\ m_5=u_{1,0}u_{0,1},\ m_6=u_{1,0}^2. \end{aligned} $$} We will simplify the constraints in \eqref{eq-2cons} as follows. A quadratic monomial in $m_i$ is called a {\em quadratic monomial}. Write monomials in ${\mathcal{C}}_{2,n}=\{R_i,i=1,\ldots,N_1\}$ as quadratic monomials if possible. Doing Gaussian elimination to ${\mathcal{C}}_{2,n}$ by treating the monomials as variables and according to a monomial order such that a quadratic monomial is less than a non-quadratic monomial, we obtain $$\widetilde{{\mathcal{C}}}_{2,n}={ {\mathcal{C}}}_{2,n,1}\cup { {\mathcal{C}}}_{2,n,2},$$ where ${ {{\mathcal{C}}}}_{2,n,1}$ is the set of quadratic forms in $m_i$, ${{{\mathcal{C}}}}_{2,n,2}$ is the set of non-quadratic forms, and ${\hbox{\rm{Span}}}_{\mathbb{R}}({\mathcal{C}}_{2,n})={\hbox{\rm{Span}}}_{\mathbb{R}}(\widetilde{{\mathcal{C}}}_{2,n})$. We obtain ${{\mathcal{C}}}_{2,n,1}=\{\widehat{R}_i,i=1,\ldots,9\}$ and ${{\mathcal{C}}}_{2,n,2}=\{\widetilde{R}_i,i=1,\ldots,13\}$, where $$\begin{array}{ll} \widehat{R}_1=2m_{1}m_{5}+\frac{2(3p-5)}{3}m_{4}m_{5}, \widehat{R}_2=m_{2}m_{6}+\frac{3p-5}{3}m_{5}m_{6},\\ \widehat{R}_3=-6m_{3}m_{5}+2(5-3p)m_{5}m_{6}, \widehat{R}_4=(3p-5)m_{4}^2+3m_{1}m_{4},\\ \widehat{R}_5=(3p-5)m_{6}^2+3m_{3}m_{6}, \widehat{R}_6=(3p-5)m_{4}m_{5}+3m_{2}m_{4},\\ \widehat{R}_7=(3p-5)m_{5}^2+2m_{2}m_{5}+m_{3}m_{4}, \\ \widehat{R}_8=m_{1}m_{3}-m_{2}^2+\frac{9p-12}{2}m_{3}m_{4}+\frac{9p^2-27p+20}{2}m_{5}^2, \\ \widehat{R}_9=m_{1}m_{6}-m_{3}m_{4}.\\ \widetilde{R}_{1}=u^3u_{0,4}+(3-3p)m_{1}^2+(9p^3-36p^2+47p-20)m_{4}^2,\\ \widetilde{R}_{2}=u^3u_{1,3}+(3-3p)m_{1}m_{2}+(9p^3-36p^2+47p-20)m_{4}m_{5},\\ \widetilde{R}_{3}=u^3u_{3,1}+(3-3p)m_{2}m_{3}+(-9p^2+21p-12)m_{3}m_{5},\\ \widetilde{R}_{4}=u^3u_{4,0}+(3-3p)m_{3}^2+(9p^3-36p^2+47p-20)m_{6}^2,\\ \widetilde{R}_{5}=u^2u_{0,1}u_{0,3}+m_{1}^2+\frac{-9p^2+27p-20}{3}m_{4}^2,\\ \widetilde{R}_{6}=u^2u_{0,1}u_{1,2}+m_{1}m_{2}+\frac{-9p^2+27p-20}{3}m_{4}m_{5},\\ \widetilde{R}_{7}=u^2u_{0,1}u_{3,0}+m_{2}m_{3}+\frac{-9p^2+27p-20}{3}m_{5}m_{6},\\ \widetilde{R}_{8}=u^2u_{1,0}u_{0,3}+m_{1}m_{2}+\frac{-9p^2+27p-20}{3}m_{4}m_{5},\\ \widetilde{R}_{9}=u^2u_{1,0}u_{2,1}+m_{2}m_{3}+\frac{-9p^2+27p-20}{3}m_{5}m_{6},\\ \widetilde{R}_{10}=u^2u_{1,0}u_{3,0}+m_{3}^2+\frac{-9p^2+27p-20}{3}m_{6}^2,\\ \widetilde{R}_{11}=u^3u_{2,2}+(3-3p)m_{2}^2+\frac{9p^2-21p+12}{2}m_{3}m_{4}+\frac{27p^3-108p^2+141p-60}{2}m_{5}^2,\\ \widetilde{R}_{12}=u^2u_{0,1}u_{2,1}+m_{2}^2+\frac{4-3p}{2}m_{3}m_{4}+\frac{-9p^2+27p-20}{2}m_{5}^2, \\ \widetilde{R}_{13}=u^2u_{1,0}u_{1,2}+m_{2}^2+\frac{4-3p}{2}m_{3}m_{4}+\frac{-9p^2+27p-20}{2}m_{5}^2. \end{array}$$ We now simplify $L_{a,b}$ using ${\mathcal{C}}_{2,n,1}$ and ${\mathcal{C}}_{2,n,2}$. Eliminating the non-quadratic monomials in $L_{a,b}$ using ${\mathcal{C}}_{2,n,2}$, and doing further reduction by ${\mathcal{C}}_{2,n,1}$, we have {\scriptsize \begin{equation} \label{2.12a} \begin{aligned} &\widehat{L}_{a,b}=L_{a,b}-2(p^3c_{1}+4np^2-4p^2c_{1}-6np+5pc_{1}-2c_{1})\widehat{R}_{7}\\ &-\frac{2}{n}(2n^2p-p^2c_{1}+n^2-n\mu +2pc_{1}-c_{1})\widehat{R}_{8}\\ &-\frac{1}{n}(6n^2p^2-2p^3c_{1}-5n^2p-2np\mu +8p^2c_{1}-4n^2+4n\mu -10pc_{1}+4c_{1})\widehat{R}_{9}\\ &-\frac{2np}{p-1}\widetilde{R}_{11} -6np\widetilde{R}_{12} -6np\widetilde{R}_{13}\\ &=(2np+2n-2\mu )m_{2}^2+(5np-5np^2+5p\mu +4n-4\mu )m_{3}m_{4}\\ &+(18np^2-7np^3+7p^2\mu -3np-19p\mu -12n+12\mu )m_{5}^2\\ &+\frac{c_{1}}{n}[{(2n-2)(p^2-2p+1)}m_{2}^2+(4n-2np+5p-4)(p^2-2p+1)m_{3}m_{4}\\ &+(14np-4np^2+7p^2-12n-19p+12)(p^2-2p+1)m_{5}^2] \end{aligned}\end{equation}} In order for $\widehat{L}_{a,b}\ge0$ to be true, we need to eliminate the monomial $m_{3}m_{4}$ from $\widehat{L}_{a,b}$, which can be done with $\widehat{R}_{7}$ as follows. \begin{equation} \label{eq-or1} \widehat{L}_{a,b}+p_{7}\widehat{R}_{7}=A_1m_2^2+A_2m_2m_5+A_3m_5^2 \end{equation} where {\begin{equation*} \begin{aligned} &p_{7}=(2np^3c_{1}+5n^2p^2-8np^2c_{1}-5p^3c_{1}-5n^2p-5np\mu +10npc_{1}\\ &\quad +14p^2c_{1}-4n^2+4n\mu -4nc_{1}-13pc_{1}+4c_{1})/n.\\ &A_1=-2c_{1}p^2/n+4c_{1}p/n+2np+2c_{1}+2c_{1}p^2-4c_{1}p-2c_{1}/n-2\mu +2n,\\ &A_2=4c_{1}p^3-16c_{1}p^2-10c_{1}p^3/n-10p\mu +20c_{1}p+28c_{1}p^2/n-26c_{1}p/n\\ &\quad+10np^2-10np+8\mu -8c_{1}+8c_{1}/n-8n,\\ &A_3=-8\mu +8n+26c_{1}p^2-24c_{1}p-8c_{1}/n-12c_{1}p^3+2c_{1}p^4+8c_{1}-52c_{1}p^2/n\\ &\quad+34c_{1}p/n+34c_{1}p^3/n-8c_{1}p^4/n+18p\mu +8np^3-22np^2-8p^2\mu +10np. \end{aligned} \end{equation*}} \subsection{Compute $\Phi(n,p,\mu)$ } From \eqref{eq-or1}, in order to solve \textbf{Problem II}, it suffices to solve \noindent\textbf{Problem III}: Find a formula $\Phi(n,p,\mu)$ such that \begin{equation} \label{eq-A1} \Phi(n,p,\mu) = \exists c_1 \forall m_1,m_2,m_3 (c_1\le0 \wedge p\ge1-\frac{\mu}{n} \wedge A_1m_2^2+A_2m_2m_5+A_3m_5^2\ge0). \end{equation} In principle, \textbf{Problem III} can be solved with the quantifier elimination~\cite{QE}. In this paper, the problem is special and an explicit proof is given. By the knowledge of linear algebra, we have $A_1m_2^2+A_2m_2m_5+A_3m_5^2\ge0$ is equivalent to $\Delta_{1}=A_1=\frac{2}{n}s_1\ge0$, $\Delta_{2}=A_3=\frac{2}{n}s_{2}\ge0$, $\Delta_{3}=A_1A_3-\frac{1}{4}A_2^2=\frac{p}{n^2}s_3\ge0$, where \begin{equation*}\begin{aligned} &s_{1}=(p-1)^2(n-1)c_{1}+n^2(p+1)-n\mu ,\\ &s_{2}=(p-1)^2(n(p-2)^2-4p^2+9p-4)c_{1}\\ &+n^2(4p^3-11p^2+5p+4)-(4p^2-9p+4)n\mu ,\\ &s_{3}=(4-9p)n^2(\mu -\mu_3)(\mu -\mu_4), \end{aligned}\end{equation*}} where $\mu_3$ and $\mu_4$ are defined in \eqref{eq-mu1} and $p\neq \frac{4}{9}$ is assumed in $\mu_4$. We thus proved \begin{lemma} We can eliminate $m_1,m_2,m_3$ in \eqref{eq-A1}: \begin{equation}\label{set} \Phi(n,p,\mu)=\exists c_1(s_1\ge0 \wedge s_2\ge0\wedge s_3\ge0\wedge c_1\le0\wedge p\geq1-\mu/n). \end{equation} \end{lemma} We will give an explicit formula for $\Phi$ in \eqref{set}. First, introduce the following parameters. \footnotesize \begin{equation} \label{eq-phi0} \begin{array}{lll} n_1 = \frac{9-\sqrt{17}}{8}, &n_2=\frac{9+\sqrt{17}}{8}, &n_3=(\sqrt{17}+1)/2,\\ \theta_1=-\frac{2n}{(p-1)^2}, &\theta_2=\frac{2n^2p(9p-13)}{(p-1)^2(4n+9p-4)}, &\theta_3=(\sqrt{17}-9)n,\\ \theta_4=\frac{n^2p-n^2-n\mu}{(p-1)^2}, &\theta_5=\frac{n^2(9p^2-13p-4)-n(9p-4)\mu}{(p-1)^2(4n+9p-4)}, &\theta_6=\frac{-4n(\sqrt{17}-1)\mu+8n^2}{\sqrt{17}+1},\\ \theta_7 = n(1-p), &\theta_8 =5n/9, &\theta_9=-\frac{162n}{25},\\ \theta_{10}=\frac{64n}{\sqrt{17}-9}, &\theta_{11}=\frac{8(9\sqrt{17}+23)n^2}{-32n-49+9\sqrt{17}}, &\theta_{12}=-\frac{16(11\sqrt{17}+47)n\mu+152n^2}{26\sqrt{17}n+73\sqrt{17}+118n+305},\\ \theta_{13}=-\frac{4n(\mu\sqrt{17}+2n+\mu)}{\sqrt{17}-1}, &\theta_{14}=-\frac{8n(22\mu\sqrt{17}-19n-94\mu)}{26\sqrt{17}n+73\sqrt{17}-118n-305}, &\theta_{15}=-\frac{9}{5}n^2-\frac{81}{25}\mu n,\\ \theta_{16} = (\sqrt{17}-1)n/8, & &\\ \phi_1\triangleq p\ge1-\frac{1}{n}, & \phi_2 \triangleq \mu =2+n(p-1), &\phi_3 \triangleq p>1-\frac{1}{n}. \\ \end{array} \end{equation} } \begin{table}[ht] \centering \scalebox{0.8}{ \begin{tabular}{|c|c|c|c|} \hline $p>n_2$ & $\theta_4> \theta_1\wedge \theta_5\le0$ & * & $ \phi_1 \wedge \phi_2$ \\ \hline $p=n_2$ & $\theta_6> \theta_3 \wedge \theta_{12}\le0$ & * & $ \phi_1 \wedge \phi_2$ \\ \hline $\frac{13}{9}< p<n_2$ & $\theta_4> \theta_1\wedge \theta_5\le0$ & * & $ \phi_1 \wedge \phi_2$ \\ \hline $n_1<p\leq\frac{13}{9}$, $p\neq1$ & $\phi_3 \wedge \theta_4> \theta_1\wedge \theta_5\le \theta_2$ & $\phi_3 \wedge \theta_7 \le \mu \wedge \theta_4 > \theta_2$ & $ \phi_1 \wedge \phi_2$ \\ \hline $p=n_1$ & $n< n_3 \wedge \theta_{13}> \theta_{10} \wedge \theta_{14}\le \theta_{11}$ & $n< n_3 \wedge \theta_{13}> \theta_{11} \wedge \mu\ge \theta_{16}$ &$ \phi_1 \wedge \phi_2$ \\ \hline $\frac{4}{9}<p<n_1$ & $\phi_3 \wedge \theta_4> \theta_1\wedge \theta_5\le \theta_2$ & $\phi_3 \wedge \theta_7 \le \mu \wedge \theta_4 > \theta_2$ & $\phi_1 \wedge \phi_2$ \\ \hline $p=\frac{4}{9}$ & $n=1 \wedge \theta_{15}> \theta_9 \wedge \mu\ge \theta_8$ & * & $n=1\wedge -p\le\mu-1\le p$ \\ \hline $0<p<\frac{4}{9}$ & $n=1 \wedge \theta_7 \le \mu \wedge \theta_4 > \theta_1$ & $n=1 \wedge \theta_5< \theta_1 \wedge \mu\ge \theta_7$ & $n=1 \wedge -p\le\mu-1\le p$ \\ \hline \end{tabular}} \caption{The description for $\Phi$ in \eqref{set}}\label{tab11} \end{table} With these notations, we introduce the conditions for defining $\Phi$ in Table \ref{tab11}, where $*$ means $\varnothing$. Define $T(i,j)$ to be the formula in the $i$-th row and the $j$-th column in Table \ref{tab11}. Then we denote \begin{equation} \label{eq-tij} \mathbb{T}(i,j) \triangleq T(i,1) \wedge T(i,j) \hbox{ for } i=1,\ldots,8, j=2,\ldots, 4. \end{equation} For examples, $\mathbb{T}(1,2)=(p>n_2\wedge \theta_4> \theta_1\wedge \theta_5\le0)$, which means that if $p,n,\mu$ satisfy $\mathbb{T}(1,2)$ then there exists a $c_1\le0$ such that \eqref{eq-A1} is true and the CREP is valid. $\mathbb{T}(1,3)= \varnothing$, which means that there exist no values for $p,n,\mu$ such that \eqref{eq-A1} and the CREP are true. We now give the main result of the paper, which implies Theorem \ref{th-main1}. The proof for the theorem can be found in section \ref{sec-proof2}. Also, from the proof we can see that for the cases $\mathbb{T}(i,4),i=1,\ldots,8$, the corresponding value for $c_1$ is $c_1=\theta_1$. \begin{theorem} \label{nsconditions} The sufficient and necessary condition for \textbf{Problem III}, that is, \eqref{eq-A1} to be true, is $$\Phi(n,p,\mu)=\vee_{i=1}^{8}\vee_{j=2}^{4} \mathbb{T}(i,j),$$ where $\mathbb{T}(i,j)$ is defined in \eqref{eq-tij} and $\vee$ means disjunction. \end{theorem} \subsection{Compare with existing results} We will show that our result includes the result proved in \cite{Savare2014}, and essentially more results. In \cite{Savare2014}, CREP was proved under the conditions $\mu=2+n(p-1)$ and $p\geq1-\frac{1}{n}$. Obviously, the result proved in \cite{Savare2014} corresponds to $\mathbb{T}(i,4),i=1,\ldots,8$ in Table \ref{tab11}. We can also prove the result in \cite{Savare2014} directly as follows. Set $\mu=2+n(p-1)$ and $c_{1}=\theta_1\le0$ in \eqref{2.12a}, we obtain $\widehat{L}_{a,b}=0$. Also, the condition $p\geq1-\frac{\mu}{n}$ implies $p\geq1-\frac{1}{n}$. So, when $\mu=2+n(p-1)$ and $p\geq1-\frac{1}{n}$, the CREP is proved based on our proof procedure. We can use the SDP code in \cite{GYG2020}[APPENDIX B] to verify the result in Table \ref{tab11}. For instance, for $\mu=2, p=\frac{11}{5}, n=2$, the condition $p\geq1-\frac{\mu}{n}$ is satisfied naturally. With the SDP code in \cite{GYG2020}, we obtain $\widehat{L}_{a,b}+\frac{172}{25}\widehat{R}_{7}=(2\sqrt{2}m_{2}+\frac{344}{100\sqrt{2}}m_{5})^2+\frac{22}{625}m_{5}^2\geq0$ with $c_{1}=-\frac{5}{9}$. Thus, the CREP is proved when $\mu=2, p=\frac{11}{5}, n=2$. This case $[ \mu=2,p=\frac{11}{5},n=2, c_{1}=-\frac{5}{9}]$ is included in $\mathbb{T}(1,1)$ in Table \ref{tab11}. Note that $\mu=2+n(p-1)$ is not satisfied for these parameters. \subsection{Proof of Theorem \ref{nsconditions}} \label{sec-proof2} Introduce more parameters. \scriptsize \begin{equation} \label{eq-mu1} \begin{aligned} \mu_{1} &= ((p-1)^2(n-1)c_1 + n^2(p+1))/n,\\ \mu_{2} &=((p-1)^2(n(p-2)^2-4p^2+9p-4)c_{1}+n^2(4p^3-11p^2+5p+4))/(n(4p^2-9p+4))\\ \mu_{3} &= (n^2p-p^2c_{1}-n^2+2p c_{1}-c_{1})/n,\\ \mu_{4} &= (9n^2p^2-4np^2c_{1}-9p^3c_{1}-13n^2p+8npc_{1}+22p^2c_{1}-4n^2-4nc_{1}-17p c_{1}+4c_{1})/(n(9p-4)),\\ \mu_{5} &= -(nc_{1}\sqrt{17}-c_{1}\sqrt{17}+136n^2+17nc_{1}-17c_{1})/(4n(\sqrt{17}-17)),\\ \mu_{6} &= -(c_{1}\sqrt{17}-8n^2+c_{1})/(4n(\sqrt{17}-1)),\\ \mu_{7} &= -(26nc_{1}\sqrt{17}+73c_{1}\sqrt{17}+152n^2+118nc_{1}+305c_{1})/(16n(11\sqrt{17}+47)),\\ \mu_{8} &= -(nc_{1}\sqrt{17}-c_{1}\sqrt{17}-136n^2-17nc_{1}+17c_{1})/(4n(\sqrt{17}+17)),\\ \mu_{9} &= -(c_{1}\sqrt{17}+8n^2-c_{1})/(4n(\sqrt{17}+1)),\\ \mu_{10} &= -(26nc_{1}\sqrt{17}+73c_{1}\sqrt{17}-152n^2-118nc_{1}-305c_{1})/(16n(11\sqrt{17}-47)),\\ \mu_{11} &= (117n^2+25nc_{1}-25c_{1})/(81n),\\ \mu_{12} &= (7218n^2+1225nc_{1}-400c_{1})/(1296n),\\ \mu_{13} &= -(5(9n^2+5c_{1}))/(81n),\\ \eta_1&=\frac{2n^2}{p-1}, \eta_2=-\frac{16n^2}{\sqrt{17}-1}, \eta_3=-\frac{18}{5}n^2. \\ \end{aligned}\end{equation} } We first treat the three inequalities $s_1\ge0$, $s_2\ge0$, $s_3\ge0$. Firstly, $s_1\ge0$ is equivalent to $ \mu\le \mu_{1}$. Secondly, since the roots of $4p^2-9p+4=0$ are $n_1$ and $n_2$, we have $s_2\ge0 \Leftrightarrow \mu\le \mu_{2}$ if $p<n_1$ or $p>n_2$; and $s_2\ge0 \Leftrightarrow\mu\ge \mu_{2}$ if $n_1<p<n_2$. In order to analyse $s_3\ge0$, we first compute \begin{equation} \label{eq-m34} \mu_{3}-\mu_{4} = \frac{4((p-1)^2c_{1}+2n)}{9p-4}. \end{equation} Therefore, $s_3\ge0$ can be divided into four cases: $s_3\ge0 \Leftrightarrow \mu_{4}\le\mu\le \mu_{3}$ if $p>\frac{4}{9}$ and $\theta_1<c_1$; $s_3\ge0 \Leftrightarrow \mu_{3}\le\mu\le \mu_{4}$ if $p>\frac{4}{9}$ and $c_1< \theta_1$; $s_3\ge0 \Leftrightarrow \mu\ge\mu_{3}\ {\rm or}\ \mu\le\mu_{4}$ if $p<\frac{4}{9}$ and $c_1<\theta_1$; $s_3\ge0 \Leftrightarrow \mu\ge\mu_{4}\ {\rm or}\ \mu\le\mu_{3}$ if $p<\frac{4}{9}$ and $\theta_1<c_1$. Finally, $p\ge1-\frac{ \mu}{n}$ is equivalent to $ \mu\ge \theta_7$. Based on the above analysis and \eqref{set}, $\Phi(n,p,\mu)$ can be divided into six cases: \footnotesize \begin{equation} \label{eq-phi1} \begin{array}{l} \Phi(n,p,\mu) \Leftrightarrow \max(\mu_{4},\theta_7)\le\mu\le \min(\mu_{1},\mu_{2},\mu_{3}), \hbox{ if } ( p\in(\frac{4}{9},n_1) \hbox{ or } p> n_2 ) \hbox{ and } \theta_1<c_1\le0 ; \\ \Phi(n,p,\mu) \Leftrightarrow\max(\mu_{2},\mu_{4},\theta_7)\le\mu\le \min(\mu_{1},\mu_{3}) , \hbox{ if } p\in(n_1,n_2) \hbox{ or } \theta_1<c_1\le0 ; \\ \Phi(n,p,\mu) \Leftrightarrow \max(\mu_{3},\theta_7)\le\mu\le \min(\mu_{1},\mu_{2},\mu_{4}) , \hbox{ if } ( p\in(\frac{4}{9},n_1) \hbox{ or } p> n_2 ) \hbox{ or } c_1<\theta_1 ; \\ \Phi(n,p,\mu) \Leftrightarrow \max(\mu_{2},\mu_{3},\theta_7)\le\mu\le \min(\mu_{1},\mu_{4}) , \hbox{ if } p\in(n_1,n_2) \hbox{ or } c_1<\theta_1 ; \\ \Phi(n,p,\mu) \Leftrightarrow \theta_7\le\mu\le\min(\mu_{1},\mu_{2},\mu_{4}) \hbox{ or } \max(\mu_{3},\theta_7)\le \mu \le\min(\mu_{1},\mu_{2}) , \hbox{ if } p<\frac{4}{9} \hbox{ or } c_1< \theta_1 ; \\ \Phi(n,p,\mu) \Leftrightarrow \theta_7\le\mu\le\min(\mu_{1},\mu_{2},\mu_{3}) \hbox{ or } \max(\mu_{4},\theta_7)\le \mu\le\min(\mu_{1},\mu_{2}) , \hbox{ if } p<\frac{4}{9} \hbox{ or } \theta_1<c_1\le0. \end{array} \end{equation} } \noindent The special cases $p=\frac{4}{9}, n_1,n_2$ and $c=\theta_1$ need to be considered separately. Also, we omit $\exists c_1$ in the above formulations. In what below, we will give detailed analysis of the above six cases which leads to the results in Table 1. We first have the formulas: \footnotesize \begin{eqnarray} \mu_{1}- \mu_{3}&=&(p-1)^2c_{1}+2n,\label{eq-m13}\\ \mu_{1}-\mu_{4} &=& \frac{9p((p-1)^2c_1+2n)}{9p-4},\label{eq-m14}\\ \mu_{2}- \mu_{3}&=&\frac{2(p-2)^2((1/2)(p-1)^2c_{1}+n)}{(4p^2-9p+4)},\label{eq-m23}\\ \mu_{2}-\mu_{4} &= &\frac{p(3p-4)^2((p-1)^2c_{1}+2n)}{(4p^2-9p+4)(9p-4)},\label{eq-m24}\\ \mu_{4}- \theta_7 &=& \frac{-(p-1)^2(4n+9p-4)c_{1}+2n^2p(9p-13)}{n(9p-4)},\label{eq-m45}\\ \mu_{3}-\theta_7 &=& \frac{(p-1)(2n^2-pc_{1}+c_{1})}{n},\label{eq-m35}\\ \theta_2-\theta_1 &=& \frac{18n(np-n+1)(p-\frac{4}{9})}{(p-1)^2(4n+9p-4)},\label{eq-c1211}\\ \theta_1-\eta_1 &=& -\frac{2n(np-n+1)}{(p-1)^2},\label{eq-c1114}\\ \eta_1-\theta_2 &=& \frac{8n^2(np-n+1)}{(p-1)^2(4n+9p-4)}.\label{eq-c1412} \end{eqnarray} } We also have the following formulas which will be used to eliminate $c_1$ in the proof. \begin{equation} \label{eq-ec1} \begin{array}{ll} \mu\le\mu_{3}\Leftrightarrow c_1 \le \theta_4, &\mu\ge\mu_{4}\Leftrightarrow c_1\ge\theta_5, \hbox{ if } p>\frac{4}{9},\\ \mu\ge\mu_{4}\Leftrightarrow c_1\le\theta_5, \hbox{ if } p<\frac{4}{9}, &\mu\le\mu_{4}\Leftrightarrow c_1\le\theta_5, \hbox{ if } p>\frac{4}{9}, \\ \mu\le\mu_{4}\Leftrightarrow c_1\ge\theta_5, \hbox{ if } p<\frac{4}{9}, &\mu\le\mu_{6}\Leftrightarrow c_1\le\theta_6,\\ \mu\ge\mu_{7}\Leftrightarrow c_{1}\ge\theta_{12}, &\mu\le\mu_{9}\Leftrightarrow c_{1}\le\theta_{13}, \\ \mu\ge\mu_{10}\Leftrightarrow c_{1}\ge\theta_{14}, &\mu\le\mu_{13}\Leftrightarrow c_{1}\le\theta_{15}.\\ \end{array} \end{equation} We divide the proof into several cases, first according to the values of $c_1$ and then according to the values of $n$. {\bf Case 1}: $\theta_1< c_{1}\le0$. From \eqref{eq-m13}, we have $\mu_{1}> \mu_{3}$ in this case and from \eqref{eq-phi1}, $\Phi(n,p,\mu)$ simplifies to three cases: \begin{equation} \label{eq-phic1} \begin{array}{l} \Phi(n,p,\mu) \Leftrightarrow \max(\mu_{4},\theta_7)\le\mu\le \min(\mu_{2},\mu_{3}), \hbox{ if } p\in(\frac{4}{9},n_1) \hbox{ or } p> n_2;\\ \Phi(n,p,\mu) \Leftrightarrow \max(\mu_{2},\mu_{4},\theta_7)\le\mu\le \mu_{3}, \hbox{ if } p\in(n_1,n_2);\\ \Phi(n,p,\mu) \Leftrightarrow \theta_7\le\mu\le\min(\mu_{2},\mu_{3}) \hbox{ or } \max(\mu_{4},\theta_7)\le \mu\le\min(\mu_{1},\mu_{2}), \hbox{ if } p<\frac{4}{9}. \end{array} \end{equation} According to the vales of $p$, we consider seven cases below. {\bf Case 1.1:} $\theta_1< c_{1}\le0$ and $p>n_2$. In this case, from \eqref{eq-m23} and \eqref{eq-m45}, we have $\mu_{2}\ge \mu_{3}$ and $\mu_{4}> \theta_7$. From \eqref{eq-phic1}, we have $\Phi(n,p,\mu) \Leftrightarrow \mu_{4}\le \mu\le \mu_{3}$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow \exists c_1(p>n_2\wedge \theta_1< c_{1}\le0\wedge \mu_{4}\le \mu\le \mu_{3})$. By \eqref{eq-ec1}, $\mu_{4}\le \mu\le \mu_{3}$ is equivalent to $\theta_5\le c_1\le\theta_4$. $\exists c_1 (\theta_5\le c_1 \le \theta_4 \wedge \theta_1< c_{1}\le 0$) is equivalent to ($\theta_4> \theta_1\wedge\theta_5\le0$). Therefore, in this case $\Phi(n,p,\mu) \Leftrightarrow (p>n_2 \wedge \theta_4> \theta_1\wedge \theta_5\le0)$, and $\mathbb{T}(1,2)$ is proved. {\bf Case 1.2:} $\theta_1< c_{1}\le0$ and $p=n_2$. When $p=n_2$, we have $\theta_1=\theta_3,\ s_2=-\frac{1}{1024}(7\sqrt{17}-33)(c_{1}\sqrt{17}+64n+9c_{1})n$. Then $s_2\ge0\Leftrightarrow c_1\ge \theta_3$. Because $\theta_1< c_{1}\le0$ and $p=n_2>\frac{4}{9}$, we have $s_3\ge0\Leftrightarrow\mu_{4}\le\mu\le\mu_{3}$. By \eqref{eq-m45}, we have $\mu_{4}>\theta_7$. When $p=n_2$, we have $\mu_{3}=\mu_{6}$ and $\mu_{4}=\mu_{7}$. Thus $\Phi(n,p,\mu) \Leftrightarrow (\theta_3< c_{1}\le0, \mu_{7}\le \mu\le \mu_{6})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow \exists c_1(p=n_2\wedge \theta_3< c_{1}\le0\wedge \mu_{7}\le \mu\le \mu_{6})$. By \eqref{eq-ec1}, $\mu_{7}\le \mu\le \mu_{6}$ is equivalent to $\theta_{12}\le c_{1}\le\theta_6$. $\exists c_1 (\theta_{12}\le c_{1}\le\theta_6 \wedge \theta_3< c_{1}\le0)$ is equivalent to $\theta_6> \theta_3$ and $\theta_{12}\le0$. Therefore, in this case $\Phi(n,p,\mu) \Leftrightarrow (p=n_2 \wedge \theta_6> \theta_3 \wedge \theta_{12}\le0)$, and $\mathbb{T}(2,2)$ is proved. {\bf Case 1.3:} $\theta_1< c_{1}\le0$ and $p\in(n_1,n_2)$, $p\neq1$. Due to \eqref{eq-m45}, this case is divided into two sub-cases. {\bf Case 1.3.1:} $\theta_1< c_{1}\le0$ and $p\in(\frac{13}{9},n_2)$. By \eqref{eq-m24} and \eqref{eq-m45}, we have $\mu_{4}>\mu_{2}$ and $\mu_{4}>\theta_7$. From \eqref{eq-phic1}, we have $\Phi(n,p,\mu) \Leftrightarrow \mu_{4}\le \mu\le \mu_{3}$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow \exists c_1 (p\in(\frac{13}{9},n_2)\wedge \theta_1< c_{1}\le0\wedge \mu_{4}\le \mu\le \mu_{3})$. Similar to Case 1.1, we have $\Phi(n,p,\mu) \Leftrightarrow (p\in(\frac{13}{9},n_2) \wedge \theta_4> \theta_1\wedge \theta_5\le0)$, $\mathbb{T}(3,2)$ is proved. {\bf Case 1.3.2:} $\theta_1< c_{1}\le0$ and $p\in(n_1,\frac{13}{9}]$, $p\neq1$. By \eqref{eq-m24}, \eqref{eq-m35}, \eqref{eq-m45} and \eqref{eq-c1211}, we have $\mu_{4}\ge\mu_{2}$, ($\mu_{3}\ge\theta_7\Leftrightarrow c_1\le \eta_1$), ($\mu_{4}\ge\theta_7\Leftrightarrow c_{1}\le \theta_2$) and ($\theta_2> \theta_1\Leftrightarrow \phi_3$). Hence $\Phi(n,p,\mu) \Leftrightarrow \max(\mu_{4},\theta_7)\le \mu\le \mu_{3}$. This case is further divided into two sub-cases. {\bf Case 1.3.2.1:} If $c_{1}\le \theta_2$, then $\mu_{4}\ge\mu_{5}$, and $\Phi(n,p,\mu) \Leftrightarrow \mu_{4}\le \mu\le \mu_{3}$. So we need $\theta_1< \theta_2$, which yields $\phi_3$. From \eqref{eq-phic1}, we have $\Phi(n,p,\mu) \Leftrightarrow (\theta_1<c_1\le \theta_2, \phi_3, \mu_{4}\le \mu\le \mu_{3})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow\exists c_1 (p\in(n_1,\frac{13}{9})\wedge p\neq1\wedge \phi_3\wedge \theta_1<c_1\le \theta_2\wedge \mu_{4}\le \mu\le \mu_{3})$. Like Case 1.1, we have $\Phi(n,p,\mu) \Leftrightarrow (p\in(n_1,\frac{13}{9})\wedge p\neq1 \wedge \phi_3 \wedge \theta_4> \theta_1\wedge \theta_5\le \theta_2)$, and $\mathbb{T}(4,2)$ is proved {\bf Case 1.3.2.2:} If $c_{1}\ge \theta_2$, then $\mu_{4}\le\theta_7$, and $\Phi(n,p,\mu) \Leftrightarrow \theta_7\le \mu\le \mu_{3}$. So we need $\theta_7\le\mu_{3}$, which yields $c_{1}\le \eta_1$. By \eqref{eq-c1114}, we know $\eta_1> \theta_1$ results $\phi_3$, which yields $\theta_1< \theta_2< \eta_1$. From \eqref{eq-phic1}, we have $\Phi(n,p,\mu) \Leftrightarrow (\theta_2< c_{1}\le \min(0,\eta_1), \phi_3, \theta_7\le \mu\le \mu_{3})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow\exists c_1 (p\in(n_1,\frac{13}{9})\wedge p\neq1\wedge \phi_3\wedge \theta_2< c_{1}\le \min(0,\eta_1)\wedge \theta_7\le \mu\le \mu_{3})$. $\theta_7\le \mu\le \mu_{3}$ is equivalent to $\theta_7 \le \mu$ and $c_1 \le \theta_4$. $\exists c_1 (c_1 \le \theta_4 \wedge \theta_2< c_{1}\le \min(0,\eta_1)$) is equivalent to $\theta_4 > \theta_2$. Therefore, in this case $\Phi(n,p,\mu) \Leftrightarrow (p\in(n_1,\frac{13}{9})\wedge p\neq1\wedge \phi_3 \wedge \theta_7 \le \mu \wedge \theta_4 > \theta_2)$, and $\mathbb{T}(4,3)$ is proved. {\bf Case 1.4:} $\theta_1< c_{1}\le0$ and $p=n_1$. When $p=n_1$, we have $\theta_1=\theta_{10},\ \theta_2=\theta_{11},\ \eta_1=\eta_2,\ s_2=-\frac{1}{1024}(33+7\sqrt{17})(c_{1}\sqrt{17}-64n-9c_{1})n$. Then $s_2\ge0\Leftrightarrow c_1\ge \theta_{10}$. Because $\theta_1< c_{1}\le0$ and $p=n_1>\frac{4}{9}$, we have $s_3\ge0\Leftrightarrow\mu_{4}\le\mu\le\mu_{3}$. By \eqref{eq-m45}, we have $\mu_{4}\ge\theta_7\Leftrightarrow c_{1}\le \theta_2$. This case is divided into two sub-cases. {\bf Case 1.4.1:} Similar to Case 1.3.2.1, $\Phi(n,p,\mu) \Leftrightarrow (\theta_1<c_{1}\le \theta_2 \wedge \phi_3\wedge \mu_{4}\le \mu\le \mu_{3})$. When $p=n_1$, we have $\mu_{3}=\mu_{9},\ \mu_{4}=\mu_{10},\ \phi_3\Leftrightarrow n< n_3$. From \eqref{eq-phic1}, we have $\Phi(n,p,\mu) \Leftrightarrow (\theta_{10}<c_{1}\le \theta_{11}, n< n_3, \mu_{10}\le \mu\le \mu_{9})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow \exists c_1(p=n_1\wedge \theta_{10}<c_{1}\le \theta_{11}\wedge n< n_3\wedge \mu_{10}\le \mu\le \mu_{9})$. $\mu_{10}\le \mu\le \mu_{9}$ is equivalent to $\theta_{14}\le c_{1}\le\theta_{13}$. $\exists c_1 (\theta_{14}\le c_{1}\le\theta_{13} \wedge \theta_{10}< c_{1}\le \theta_{11})$ is equivalent to $\theta_{13}> \theta_{10}$ and $\theta_{14}\le \theta_{11}$. Therefore, in this case $\Phi(n,p,\mu) \Leftrightarrow (p=n_1\wedge n< n_3 \wedge \theta_{13}> \theta_{10} \wedge \theta_{14}\le \theta_{11})$, and $\mathbb{T}(5,2)$ is proved. {\bf Case 1.4.2:} Similar to Case 1.3.2.2, $\Phi(n,p,\mu) \Leftrightarrow (\theta_2< c_{1}\le \min(0,\eta_1)\wedge \phi_3\wedge \mu_{5}\le \mu\le \mu_{3})$. When $p=n_1$, we have $\theta_7=\theta_{16}$. From \eqref{eq-phic1}, we have $\Phi(n,p,\mu) \Leftrightarrow (\theta_{11}< c_{1}\le \eta_2, n< n_3, \theta_{16}\le \mu\le \mu_{9})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow \exists c_1(p=n_1\wedge \theta_{11}< c_{1}\le \eta_2\wedge n< n_3\wedge \theta_{16}\le \mu\le \mu_{9})$. $\theta_{16}\le \mu\le \mu_{9}$ is equivalent to $c_{1}\le\theta_{13}$ and $\mu\ge \theta_{16}$. $\exists c_1 (c_{1}\le\theta_{13} \wedge \theta_{11}< c_{1}\le \eta_2)$ is equivalent to $\theta_{13}> \theta_{11}$. Therefore, in this case $\Phi(n,p,\mu) \Leftrightarrow (p=n_1\wedge n< n_3 \wedge \theta_{13}> \theta_{11} \wedge \mu\ge \theta_{16})$, and $\mathbb{T}(5,3)$ is proved. {\bf Case 1.5:} $\theta_1< c_{1}\le0$ and $p\in(\frac{4}{9},n_1)$. By \eqref{eq-m23} and \eqref{eq-m45}, we have $\mu_{2}>\mu_{3}$ and ($\mu_{4}\ge\theta_7\Leftrightarrow c_{1}\le \theta_2$). Hence $\Phi(n,p,\mu) \Leftrightarrow \max(\mu_{4},\theta_7)\le \mu\le \mu_{3}$. This case is divided into two sub-cases. {\bf Case 1.5.1:} Similar to Case 1.3.2.1, we have $\Phi(n,p,\mu) \Leftrightarrow (\theta_1<c_{1}\le \theta_2\wedge \phi_3\wedge \mu_{4}\le \mu\le \mu_{3})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow \exists c_1(p\in(\frac{4}{9},n_1)\wedge \phi_3\wedge \theta_1<c_{1}\le \theta_2\wedge \mu_{4}\le \mu\le \mu_{3})$. Like Case 1.3.2.1, we have $\Phi(n,p,\mu) \Leftrightarrow (p\in(\frac{4}{9},n_1) \wedge \phi_3 \wedge \theta_4> \theta_1\wedge \theta_5\le \theta_2)$, and $\mathbb{T}(6,2)$ is proved {\bf Case 1.5.2:} Similar to Case 1.3.2.2, we have $\Phi(n,p,\mu) \Leftrightarrow (\theta_2< c_{1}\le \eta_1\wedge \phi_3\wedge \mu_{5}\le \mu\le \mu_{3})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow\exists c_1 (p\in(\frac{4}{9},n_1)\wedge \phi_3\wedge \theta_2< c_{1}\le \eta_1\wedge \theta_7\le \mu\le \mu_{3})$. Similar to Case 1.3.2.2, we have $\Phi(n,p,\mu) \Leftrightarrow (p\in(\frac{4}{9},n_1)\wedge \phi_3 \wedge \theta_7 \le \mu \wedge \theta_4 > \theta_2)$, and $\mathbb{T}(6,3)$ is proved. {\bf Case 1.6:} $\theta_1< c_{1}\le0$ and $p=\frac{4}{9}$. When $p=\frac{4}{9}$, we have $\theta_1=\theta_9,\ \eta_1=\eta_3,\ \theta_7=\theta_8,\ s_3=-\frac{4n}{6561}(162n+25c_{1})(45n^2+81nu+25c_{1})$. Then $s_3\ge0\Leftrightarrow \mu\le\mu_{13}$ if $c_{1}\ge \theta_9$. By \eqref{eq-m35}, we know $\mu_{3}\ge\theta_7\Leftrightarrow c_1\le \eta_1$. And $\theta_9< \eta_3\Leftrightarrow n=1$. From \eqref{eq-phic1}, we have $\Phi(n,p,\mu) \Leftrightarrow (\theta_9<c_{1}\le \eta_3, n=1, \theta_8\le \mu\le \mu_{13})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow\exists c_1 (p=\frac{4}{9}\wedge \theta_9<c_{1}\le \eta_3\wedge n=1\wedge \theta_8\le \mu\le \mu_{13})$. $\theta_8\le \mu\le \mu_{13}$ is equivalent to $c_{1}\le\theta_{15}$ and $\mu\ge\theta_8$. $\exists c_1 (c_{1}\le\theta_{15} \wedge \theta_9<c_{1}\le \eta_3)$ is equivalent to $\theta_{15}>\theta_9$. Therefore, in this case $\Phi(n,p,\mu) \Leftrightarrow (p=\frac{4}{9} \wedge n=1 \wedge \theta_{15}> \theta_9 \wedge \mu\ge \theta_8)$, and $\mathbb{T}(7,2)$ is proved {\bf Case 1.7:} $\theta_1< c_{1}\le0$ and $0<p<\frac{4}{9}$. This case is divided into two sub-cases. {\bf Case 1.7.1:} If we select $\theta_7\le\mu\le\min(\mu_{2},\mu_{3})$, by \eqref{eq-m23}, we have $\mu_{2}>\mu_{3}$. Thus $\Phi(n,p,\mu) \Leftrightarrow \theta_7\le \mu\le \mu_{3}$. So we need $\theta_7\le\mu_{3}$, which yields $c_{1}\le \eta_1$. By \eqref{eq-c1114}, we know $\eta_1> \theta_1$ results $\phi_3$, which yields $n=1$ with $0<p<\frac{4}{9}$. From \eqref{eq-phic1}, we have $\Phi(n,p,\mu) \Leftrightarrow (\theta_1< c_{1}\le \eta_1, n=1, \theta_7\le \mu\le \mu_{3})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow \exists c_1(p\in(0,\frac{4}{9})\wedge n=1\wedge \theta_1< c_{1}\le \eta_1\wedge \theta_7\le \mu\le \mu_{3})$. Similar to Case 1.3.2.2, we have $\Phi(n,p,\mu) \Leftrightarrow (p\in(0,\frac{4}{9})\wedge n=1 \wedge \theta_7 \le \mu \wedge \theta_4 > \theta_1)$, and $\mathbb{T}(8,2)$ is proved. {\bf Case 1.7.2:} If we select $\max(\mu_{4},\theta_7)\le \mu\le\min(\mu_{1},\mu_{2})$, by \eqref{eq-m14}, we have $\mu_{1}<\mu_{4}$, which yields contradiction. {\bf Case 2:} $c_{1}<\theta_1$. From \eqref{eq-m13}, we have $\mu_{1}< \mu_{3}$ in this case and from \eqref{eq-phi0}, $\Phi(n,p,\mu)$ simplifies to one case: $$\Phi(n,p,\mu) \Leftrightarrow\exists c_1 (\theta_7\le\mu\le\min(\mu_{1},\mu_{2},\mu_{4}), \hbox{ if } 0<p<\frac{4}{9} \hbox{ and }c_1< \theta_1).$$ Since $p$ satisfies $0<p<\frac{4}{9}$, we need only consider the following cases. {\bf Case 2.1:} $c_1<\theta_1$ and $0<p<\frac{4}{9}$. By \eqref{eq-m14}, \eqref{eq-m24} and \eqref{eq-m45}, we have $\mu_{1}>\mu_{4}$, $\mu_{2}>\mu_{4}$ and ($\mu_{4}\ge\theta_7\Leftrightarrow c_1\ge \theta_2$). Then we need $\theta_2< \theta_1$, which yields $\phi_3$ by \eqref{eq-c1211}. Because $\phi_3$ means $n=1$ with $0<p<\frac{4}{9}$, we have $\Phi(n,p,\mu) \Leftrightarrow (\theta_2\le c_{1}< \theta_1, n=1, \theta_7\le \mu\le \mu_{4})$. We now eliminate $c_1$ from $\Phi(n,p,\mu) \Leftrightarrow \exists c_1(p\in(0,\frac{4}{9})\wedge n=1\wedge \theta_2\le c_{1}< \theta_1\wedge \theta_7\le \mu\le \mu_{4})$. $\theta_7\le \mu\le \mu_{4}$ is equivalent to $c_{1}\ge\theta_5$ and $\mu\ge\theta_7$. $\exists c_1 (c_{1}\ge\theta_5 \wedge \theta_2\le c_{1}< \theta_1)$ is equivalent to $\theta_5<\theta_1$. Therefore, in this case $\Phi(n,p,\mu) \Leftrightarrow (p\in(0,\frac{4}{9}) \wedge n=1 \wedge \theta_5< \theta_1 \wedge \mu\ge \theta_7)$, and $\mathbb{T}(8,3)$ is proved {\bf Case 2.2:} $c_{1}<\theta_1$ and $p=n_2$. In Case 1.2, we know $\theta_1=\theta_3$ with $p=n_2$, and $s_2\ge0\Leftrightarrow c_1\ge \theta_3$, which yields contradiction. {\bf Case 2.3:} $c_{1}<\theta_1$ and $p=n_1$. In Case 1.4, we know $\theta_1=\theta_{10}$ with $p=n_1$, and $s_2\ge0\Leftrightarrow c_1\ge \theta_{10}$, which yields contradiction. {\bf Case 2.4:} $c_{1}<\theta_1$ and $p=\frac{4}{9}$. We have $\theta_1=\theta_9,\ \mu_{2}=\mu_{12},\ \mu_{3}=\mu_{13}$ based on $p=\frac{4}{9}$. Then we have ($s_2\ge0\Leftrightarrow \mu\le\mu_{12}$) and ($s_3\ge0\Leftrightarrow \mu\ge\mu_{13}$ if $c_{1}\le \theta_9$). So we need $\mu_{12}\ge \mu_{13}$. By \eqref{eq-m23}, we have $\mu_{12}<\mu_{13}$, which yields contradiction. {\bf Case 3:} $c_{1}=\theta_1$. When $c_{1}=\theta_1$, we have $s_1=n(np-n-\mu+2)$, $s_2=n(4p^2-9p+4)(np-n-\mu+2)$ and $s_3=-n^2(9p-4)(np-n-\mu+2)^2$. Thus, $s_1\ge0\Leftrightarrow \mu\le 2+n(p-1)$ and $s_3\ge0\Leftrightarrow (p\le\frac{4}{9}\ {\rm or}\ \mu=2+n(p-1))$. This case is divided into two sub-cases. {\bf Case 3.1:} If $\mu=2+n(p-1)$, then $s_1=s_2=s_3=0$. And $p\ge1-\frac{\mu}{n}\Leftrightarrow \phi_1$. Thus $\Phi(n,p,\mu) \Leftrightarrow (c_{1}= \theta_1\wedge\phi_1\wedge\phi_2)$, and $\mathbb{T}(i,4),\ i=1,\ldots,6$ are proved. {\bf Case 3.2:} If $p\le\frac{4}{9}$, then $s_2\ge0\Leftrightarrow \mu\le 2+n(p-1)$. Then we need $2+n(p-1)\ge\mu_{5}$, which yields $\phi_1$. And $\phi_1$ implies $n=1$ with $p\le\frac{4}{9}$. Thus $\Phi(n,p,\mu) \Leftrightarrow (c_{1}= \theta_1\wedge n=1\wedge-p\le\mu-1\le p)$, and $\mathbb{T}(7,4)$, $\mathbb{T}(8,4)$ are proved. \section{Conclusion} \label{sec-conc} This paper is an extension of the work \cite{GYG2020,GYG2020M} to the case where the entropy power involves parameters. The basic idea is to prove entropy power inequalities in a systematical way. Precisely, the concavity of R\'{e}nyi entropy power is considered, where the probability density $u_t$ solve the nonlinear heat equation with two parameters $p$ and $\mu$. Our procedure reduces the proof of the CREP to check the semi-positiveness of a quadratic form \eqref{eq-A1} whose coefficients are polynomials in the parameters $n,p,\mu$. In principle, a necessary and sufficient condition on parameters $n,p,\mu$ for this can be computed with the quantifier elimination~\cite{QE}. Based on the above method, we give a sufficient condition $\Phi(n,p,\mu)$ for CREP, which extends the parameter's range of the CREP given by Savar\'{e}-Toscani~\cite{Savare2014}. In fact, our results give the necessary and sufficient condition for CREP under certain conditions. But in the general case, Theorem \ref{th-m1} only gives a sufficient condition for the following reasons: 1. we use inequalities \eqref{T2} in step \eqref{T33}; 2. there might exist more constraints; 3. {\bf Problem II} may not equivalent to {\bf Problem III}. \section*{Acknowledgments} This work is partially supported by NSFC 11688101 and NKRDP 2018YFA0704705, Beijing Natural Science Foundation (No. Z190004), and China Postdoctoral Science Foundation (No. 2019TQ0343, 2019M660830). \section*{Appendix. Constraints in \eqref{eq-2cons}} In this appendix, we give the constraints in \eqref{eq-2cons}, where $u_{h_1,h_2}= \frac{\partial^{h_1+h_2} u}{\partial^{h_1} x_{a,t}\partial^{h_2} x_{b,t}}$. {\parskip=3pt $R_{1,a,b}=3pu_{1,0}^4+3uu_{2,0}u_{1,0}^2-5u_{1,0}^4,$ $R_{2,a,b}=3pu_{0,1}^4+3uu_{0,2}u_{0,1}^2-5u_{0,1}^4,$ $R_{3,a,b}=3pu^2u_{1,0}u_{3,0}+u^3u_{4,0}-3u^2u_{1,0}u_{3,0},$ $R_{4,a,b}=3pu^2u_{0,1}u_{3,0}+u^3u_{3,1}-3u^2u_{0,1}u_{3,0},$ $R_{5,a,b}=3pu^2u_{1,0}u_{2,1}+u^3u_{3,1}-3u^2u_{1,0}u_{2,1},$ $R_{6,a,b}=3pu^2u_{0,1}u_{2,1}+u^3u_{2,2}-3u^2u_{0,1}u_{2,1},$ $R_{7,a,b}=3pu^2u_{1,0}u_{1,2}+u^3u_{2,2}-3u^2u_{1,0}u_{1,2},$ $R_{8,a,b}=3pu^2u_{0,1}u_{1,2}+u^3u_{1,3}-3u^2u_{0,1}u_{1,2},$ $R_{9,a,b}=3pu^2u_{1,0}u_{0,3}+u^3u_{1,3}-3u^2u_{1,0}u_{0,3},$ $R_{10,a,b}=3pu^2u_{0,1}u_{0,3}+u^3u_{0,4}-3u^2u_{0,1}u_{0,3},$ $R_{11,a,b}=3pu_{0,1}u_{1,0}^3+3uu_{1,1}u_{1,0}^2-5u_{1,0}^3u_{0,1},$ $R_{12,a,b}=3pu_{0,1}^3u_{1,0}+3uu_{1,1}u_{0,1}^2-5u_{0,1}^3u_{1,0},$ $R_{13,a,b}=3pu_{0,1}^2u_{1,0}^2+2uu_{0,1}u_{1,0}u_{1,1}+uu_{1,0}^2u_{0,2}-5u_{1,0}^2u_{0,1}^2,$ $R_{14,a,b}=3puu_{1,0}^2u_{2,0}+u^2u_{1,0}u_{3,0}+u^2u_{2,0}^2-4uu_{2,0}u_{1,0}^2,$ $R_{15,a,b}=3puu_{0,1}u_{1,0}u_{2,0}+u^2u_{0,1}u_{3,0}+u^2u_{1,1}u_{2,0}-4uu_{2,0}u_{1,0}u_{0,1},$ $R_{16,a,b}=3puu_{1,0}^2u_{1,1}+u^2u_{1,0}u_{2,1}+u^2u_{1,1}u_{2,0}-4uu_{1,1}u_{1,0}^2,$ $R_{17,a,b}=3puu_{0,1}u_{1,0}u_{2,0}+u^2u_{1,0}u_{2,1}+u^2u_{1,1}u_{2,0}-4uu_{2,0}u_{1,0}u_{0,1},$ $R_{18,a,b}=3puu_{0,1}^2u_{2,0}+u^2u_{0,1}u_{2,1}+u^2u_{0,2}u_{2,0}-4uu_{0,1}^2u_{2,0},$ $R_{19,a,b}=3puu_{0,1}u_{1,0}u_{1,1}+u^2u_{0,1}u_{2,1}+u^2u_{1,1}^2-4uu_{0,1}u_{1,0}u_{1,1},$ $R_{20,a,b}=3puu_{1,0}^2u_{0,2}+u^2u_{1,0}u_{1,2}+u^2u_{0,2}u_{2,0}-4uu_{1,0}^2u_{0,2},$ $R_{21,a,b}=3puu_{0,1}u_{1,0}u_{1,1}+u^2u_{1,0}u_{1,2}+u^2u_{1,1}^2-4uu_{0,1}u_{1,0}u_{1,1},$ $R_{22,a,b}=3puu_{0,1}^2u_{1,1}+u^2u_{0,1}u_{1,2}+u^2u_{0,2}u_{1,1}-4uu_{1,1}u_{0,1}^2,$ $R_{23,a,b}=3puu_{0,1}u_{1,0}u_{0,2}+u^2u_{0,1}u_{1,2}+u^2u_{0,2}u_{1,1}-4uu_{0,2}u_{1,0}u_{0,1},$ $R_{24,a,b}=3puu_{0,1}u_{1,0}u_{0,2}+u^2u_{1,0}u_{0,3}+u^2u_{0,2}u_{1,1}-4uu_{0,2}u_{1,0}u_{0,1},$ $R_{25,a,b}=3puu_{0,1}^2u_{0,2}+u^2u_{0,1}u_{0,3}+u^2u_{0,2}^2-4uu_{0,2}u_{0,1}^2,$ $R_{26,a,b}=3pu_{0,1}u_{1,0}^3+2uu_{2,0}u_{1,0}u_{0,1}+uu_{1,1}u_{1,0}^2-5u_{1,0}^3u_{0,1},$ $R_{27,a,b}=3pu_{0,1}^2u_{1,0}^2+uu_{0,1}^2u_{2,0}+2uu_{0,1}u_{1,0}u_{1,1}-5u_{1,0}^2u_{0,1}^2,$ $R_{28,a,b}=3pu_{0,1}^3u_{1,0}+uu_{1,1}u_{0,1}^2+2uu_{0,2}u_{1,0}u_{0,1}-5u_{0,1}^3u_{1,0}.$ }
{'timestamp': '2021-03-12T02:22:54', 'yymm': '2103', 'arxiv_id': '2103.06650', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06650'}
arxiv
\section{Introduction} In 1966, Leo Moser \cite{MoserProblemFormulation} asked for the minimum area $A$ such that for any (possibly infinite) set $S$ of squares of total area $1$, there exists a rectangle $R$ of area $A$ and an axis-parallel, internally disjoint packing of $S$ into $R$ (see Figure~\ref{FigPackingMoser}). The fact that the problem under consideration indeed produces a minimum instead of just an infimum follows from a result by Martin~\cite{martin2002compactness}.\\ \begin{figure}[t] \centering \begin{tikzpicture}[scale = 0.3] \draw[draw = blue, fill = blue, fill opacity = 0.5] (0,0) rectangle (4,4); \draw[draw = green!70!black, fill = green!70!black, fill opacity = 0.5] (4,0) rectangle (7,3); \draw[draw = yellow!50!orange, fill = yellow!50!orange, fill opacity = 0.5] (5,3.5) rectangle (7.5,6); \draw[draw = red!80!blue, fill = red!80!blue, fill opacity = 0.5] (7.2,0.2) rectangle (9.7,2.7); \draw[draw = black, thick, fill = none] (0,0) rectangle (10,7); \node at (5,-1){\textcolor{green!60!black}{$\checkmark$}}; \begin{scope}[shift = {(12,0)}] \draw[draw = black, thick, fill = none] (0,0) rectangle (10,7); \draw[draw = blue, fill = blue, fill opacity = 0.5] (0,-0.5) rectangle (4,3.5); \draw[draw = green!70!black, fill = green!70!black, fill opacity = 0.5] (4,0) rectangle (7,3); \draw[draw = red!80!blue, fill = red!80!blue, fill opacity = 0.5] (6.7,0.2) rectangle (9.2,2.7); \draw[draw = yellow!50!orange, fill = yellow!50!orange, fill opacity = 0.5] (5.77,3.2)--(7.54,4.97)--(5.77,6.74)--(4,4.97)--(5.77,3.2); \node at (5.77,4.97) {\textcolor{red!70!black}{$\times$}}; \node at (6.85,1.425) {\textcolor{red!70!black}{$\times$}}; \node at (2,-0.25) {\textcolor{red!70!black}{$\times$}}; \end{scope} \end{tikzpicture} \caption{A feasible (left) and an infeasible (right) packing.}\label{FigPackingMoser} \end{figure} The first bounds on the value of the area $A$ asked for in the problem definition were provided by Moon and Moser \cite{MoonMoser} in 1967, showing that $1.2<A\leq 2$. While the lower bound arises by studying the case of two squares, the upper bound can be proven by considering a packing that accommodates the squares in horizontal layers in order of magnitude. The latter idea was generalized by Meir and Moser \cite{MeirMoser} to prove that for any dimension $k>0$, there exists an axis-parallel, internally disjoint packing of a (possibly infinite) set of $k$-dimensional hypercubes with edge lengths given by $x_1\geq x_2\geq \dots$ and finite total volume $V$ into a rectangular parallelepiped with edge lengths $a_1,\dots,a_k$ satisfying $a_j\geq x_1$ for all $j=1\dots,k$ as well as \begin{equation} x_1^k+\Pi_{j=1}^k (a_j-x_1)\geq V. \label{EqMeirMoser} \end{equation}The special case $k=2$ has found several applications in subsequent works, see for example \cite{Hougardy11} or \cite{Novotny96}.\\ In 1970, Kleitman and Krieger~\cite{KleitmanKrieger70} proved that any set of squares of total area $1$ can be packed into a rectangle with edge lengths $1$ and $\sqrt{3}$, which in particular implies an upper bound of $A\leq \sqrt{3}<1.733$. Moreover, five years later, they showed that a rectangle of edge lengths $\frac{2}{\sqrt{3}}$ and $\sqrt{2}$ (and area $\frac{4}{\sqrt{6}}<1.633$) can accommodate any \emph{finite} set of squares of total area $1$ \cite{KleitmanKrieger75}, which was generalized to the case of possibly infinite families of squares by Zernisch~\cite{Zernisch12} in 2012.\\ The best known lower bound of $\frac{2+\sqrt{3}}{3}$, which is actually believed to be the correct answer to the problem, was provided by Novotný~\cite{Novotny95} in 1995, who considered an instance consisting of one square of area $s_1^2=\frac{1}{2}$ and three squares of area $s_2^2=s_3^2=s_4^2=\frac{1}{6}$ (see Figure~\ref{FigWorstCase}). For packing up to $5$ squares, he proved that an area of $\frac{2+\sqrt{3}}{3}$ indeed suffices \cite{Novotny99}, which was extended to up to $11$ squares by Platz~\cite{Platz}. Moreover, using the results obtained in \cite{MeirMoser} and \cite{KleitmanKrieger75}, Novotný~\cite{Novotny96} proved an upper bound of $A< 1.53$ for the general case of possibly infinitely many squares.\\ The best known upper bound of $A<1.37$ is due to Hougardy~\cite{Hougardy11} and Ilhan~\cite{Ilhan}. They employed a computer-aided case distinction, where various packing routines are applied to accommodate the largest first squares and a rectangle meeting the criterion \eqref{EqMeirMoser} containing the remaining ones. In doing so, Hougardy~\cite{Hougardy11} first proved an upper bound of $A<1.40$, which was then refined to first $1.39$ and later $1.37$ in cooperation with Ilhan~\cite{Ilhan} by using a different set of packing methods.\\ In this paper, we present a general approach that allows us to reduce the task of showing that any set of squares of total area $1$ can be packed into a rectangle of area $\frac{2+\sqrt{3}}{3}\leq F\leq 1.37$ to the problem of proving this statement for \emph{finite} sets containing at most $N$ squares, where $N$ is a natural number that can be easily computed.\\ In a similar spirit, Liu~\cite{Liu17} has shown (among other results) that for each infinite set of squares $S=\{S_1,S_2,\dots\}$ of total area $1$, the minimum area of a rectangle into which the finite subset $\{S_1,S_2,\dots,S_n\}$ of $S$ can be packed axis-parallel and internally disjoint converges to the minimum area of a rectangle able to accommodate all of the squares in $S$ as $n$ approaches $\infty$. This is a relatively straightforward consequence of the Meir-Moser Theorem.\\ However, the strategy applied by Liu can only be used to reduce the infinite problem to a finite one within a certain error rate. More precisely, both \begin{itemize} \item considering a packing of $S_1,\dots,S_n$ into some rectangle $R$ of area $F$ and then slightly inflating $R$ to ensure that an additional rectangle being able to accommodate the remaining squares due to \eqref{EqMeirMoser} can be packed as well or \item packing all of the squares $S_{n},S_{n+1},\dots$ into some larger square $S'_{n}$ meeting the requirements of \eqref{EqMeirMoser} \end{itemize}will inevitably increase the total area of objects to be packed from $1$ to $1+\epsilon$ for some $\epsilon >0$. Therefore, these approaches only allow to deduce an area bound of $F\cdot(1+\epsilon)$ for a packing of a possibly infinite set of squares from an area bound of $F$ established for some finite case.\\ The same problem also seems to be inherent in the previous attempts to achieve improved upper bounds since most of them rely on the application of \eqref{EqMeirMoser} to get down to a finite number of rectangular objects to be packed.\\ In order to overcome this difficulty, instead of trying to pack a finite sub-collection of "large" squares together with an additional rectangle containing the "small" ones, we consider a packing that only respects the "large" squares and then show how to fit the remaining squares into the arising \emph{whitespace}. The latter is defined to be the closure of the set of points in the enclosing rectangle that are not covered by any of the squares already packed (see Definition~\ref{DefWhitespace}).\\ Note that a similar argument also appears in \cite{Platz}, proving that an area of $\frac{2+\sqrt{3}}{3}$ suffices to pack sets consisting of at most $11$ squares of total area $1$. In this context, the area of a largest square present in the whitespace arising from a packing of $n$ squares into a rectangle of the desired area $F$ is bounded from below by some constant $a_n$ depending only on $n$ (and $F$). This allows to inductively reduce the case where the smallest edge length occurring among those of the finitely many squares considered is less than $a_n$ to the case where the number of squares is one less. However, the bounds presented in \cite{Platz} are too weak to be applicable in the sort of argument we aim at.\\ Therefore, in the following section, we will first see how to produce sufficient bounds on the size of squares that can be accommodated within the whitespace, and then see how to apply these in order to obtain the desired result. \begin{figure}[t] \centering \begin{tikzpicture}[scale = 3] \draw[draw = blue, thick, fill = blue, fill opacity = 0.5] (0,0) rectangle (0.7071,0.7071); \draw[draw = green!70!black, thick, fill = green!70!black, fill opacity = 0.5] (0.7071, 0) rectangle (1.1153,0.4082); \draw[draw = green!70!black, thick, fill = green!70!black, fill opacity = 0.5] (0.7071,0.4082) rectangle (1.1153,0.8164 ); \draw[draw = green!70!black, thick, fill = green!70!black, fill opacity = 0.5] (1.1153, 0) rectangle (1.5235,0.4082); \draw[draw = black, thick, fill = none] (0,0) rectangle (1.5235,0.8164); \draw[<-, black, thick] (-0.15, 0)--(-0.15, 0.26); \draw[->, black, thick] (-0.15, 0.5564)--(-0.15, 0.8164); \node at(-0.15,0.4082) {\small$\frac{2}{\sqrt{6}}$}; \draw[<-, black, thick] (0, -0.15)--(0.46175, -0.15); \draw[->, black, thick] (1.06175, -0.15)--(1.5235, -0.15); \node at(0.76175,-0.15) {\small$\frac{1}{\sqrt{2}}+\frac{2}{\sqrt{6}}$}; \begin{scope}[shift = {(3,0)}] \node at (0,0.27){\textcolor{green!70!black}{$s_2=s_3=s_4=\frac{1}{\sqrt{6}}$}}; \node at (0,0.54){\textcolor{blue}{$s_1=\frac{1}{\sqrt{2}}$}}; \end{scope} \end{tikzpicture} \caption{The lower bound example provided by Novotný.}\label{FigWorstCase} \end{figure} \section{Reduction to a Finite Number of Squares\label{SecReductionFinite}} Let a target area $F\geq \frac{2+\sqrt{3}}{3}$ be given. This section shows how to compute a natural number $N(F)$ with the following property: If for any set of at most $N(F)$ squares of total area $1$, there exists a rectangle of area $F$ into which these squares can be packed axis-parallel and internally disjoint, then the same statement holds for any, possibly infinite set of squares of total area $1$.\\ From the way we compute $N(F)$, it is not hard to see that $N:=\max\{N(F),F\in[\frac{2+\sqrt{3}}{3},1.37]\}$ exists and is attained by $N(\frac{2+\sqrt{3}}{3})>4$. Note that these properties already imply that if we denote the correct answer to Moser's Square Packing Problem (when restricted to finite sets containing at most $N$ squares) by $A$ ($A'$), then $A=A'$:\\ First, $A < 1.37$ by \cite{Ilhan}. Furthermore, we clearly have $A'\leq A$: If for any set of squares of total area $1$, there is a rectangle of area $A$ into which the given squares permit an axis-parallel, internally disjoint packing, then this in particular also holds for any set of \emph{at most $N$} squares of total area $1$. Hence, $A'\leq A<1.37$.\\ Conversely, the fact that $N>4$ additionally implies that $\frac{2+\sqrt{3}}{3}\leq A'$ since the example yielding this lower bound consists of four squares \cite{Novotny95}. But now, by our choice of $N$, we must have $N(A')\leq N$ since $\frac{2+\sqrt{3}}{3}\leq A'<1.37$. As a consequence, by definition of $A'$, we know that for any set of at most $N(A')\leq N$ squares of total area $1$, there is a rectangle of area $A'$ in which the squares can be accommodated. By our choice of $N(A')$, this yields $A\leq A'$. Hence, we obtain $A=A'$ and $N$ possesses the desired property. \\ In order to determine numbers $N(F),F\in[\frac{2+\sqrt{3}}{3},1.37]$ as promised, we first note that without loss of generality, we can assume a set of squares of total area $1$ to be given by a non-increasing sequence $s_1\geq s_2\geq\dots$ of non-negative edge lengths satisfying $\sum_{i=1}^\infty s_i^2 =1$. This is because for any set $S$ of squares of total area $1$, the number of squares in $S$ with edge lengths in $[\frac{1}{n+1},\frac{1}{n}]$ for some fixed positive integer $n$ must be finite, and squares of edge length zero do not influence the packing task. For a given sequence $s_1\geq s_2\geq\dots$, we denote the corresponding squares by $S_1,S_2,\dots$.\\ We further observe that if $s_1$ is small enough, the criterion established by Meir and Moser provides a packing of $S$ into a rectangle of area $F$, so we can assume that $s_1$ is greater than a certain constant. Next, we show that there exists constants $N_0(F)$ and $c(F)$ with the following properties: If the total area of the squares with indices $N_0(F)+1$, $N_0(F)+2$, $\dots$ amounts to more than $c(F)^2$, (implying that the total area of the first $N_0(F)$ largest squares is less than $1-c^2(F)$,) then their edge lengths must be "small" and they can, therefore, be packed "efficiently". On the other hand, if the total area of $S_{N_0(F)+1}$, $S_{N_0(F)+2}$, $\dots$ is at most $c(F)^2$, then we also know that there must be some $N_0(F)+1\leq n\leq \lfloor\mathrm{e}^2\cdot N_0(F)\rfloor$ such that $s_n\leq\frac{c}{\sqrt{n}}$. For such $n$, we show that for any packing of the first $n$ squares into a rectangle of area $F$, the remaining squares can be accommodated in the arising \emph{whitespace} (see Definition~\ref{DefWhitespace}). This implies that it suffices to consider sets of at most \mbox{$N(F):=\lfloor\mathrm{e}^2\cdot N_0(F)\rfloor$} squares to find the correct answer to Moser's Square Packing Problem.\\ The remainder of this section provides the omitted details. We first restate the following, already mentioned results by Meir, Moon and Moser because we need them for the subsequent arguments. \begin{theorem}[Moon, Moser \cite{MoonMoser}] Any set of squares of total area $V$ and with maximum occurring edge length $x$ can be packed into any rectangle with edge lengths $a_1$ and $a_2$ satisfying $\min\{a_1,a_2\}\geq x$ and $2\cdot V\leq a_1\cdot a_2$. \label{double_area} \end{theorem} \begin{theorem}[Meir, Moser \cite{MeirMoser}] Any set of squares with total area $V$ and maximum occurring edge length $x$ can be packed into any rectangle with edge lengths $a_1$ and $a_2$ satisfying $\min\{a_1,a_2\}\geq x$ and $V\leq x^2+(a_1-x)\cdot (a_2-x)$. \label{MeirMoser} \end{theorem} \begin{figure}[t] \centering \begin{tikzpicture}[scale = 0.5] \draw[draw = black, thick, fill = none] (0,0) rectangle (10,7); \draw[draw=green!70!black, pattern = north east lines, pattern color = green!70!black] (0,0) rectangle (3,3); \draw[draw=green!70!black, pattern = north east lines, pattern color = green!70!black] (3,3) rectangle (10,7); \draw[thick, black, <-](0,-0.6)--(4.6,-0.6); \node at (5,-0.6){$a_1$}; \draw[thick, black, ->] (5.4,-0.6)--(10,-.6); \draw[thick, black, <-] (-0.6,0)--(-0.6,3.1); \node at (-0.6,3.5) {$a_2$}; \draw[thick, black, ->] (-0.6, 3.9)--(-0.6,7); \draw[thick, black, <-] (3.6,0)--(3.6,1.1); \node at (3.6,1.5) {$x$}; \draw[thick, black,->] (3.6, 1.9)--(3.6,3); \draw[thick, black, <-] (0,3.6)--(1.1, 3.6); \node at (1.5, 3.6) {$x$}; \draw[thick, black, ->] (1.9, 3.6)--(3,3.6); \draw[draw=green!70!black, pattern = north east lines, pattern color = green!70!black] (13.5,3) rectangle (14.5,4); \node at (15.5,3.5){$\geq V$}; \end{tikzpicture} \caption{Visualization of the condition established by Meir and Moser. The picture does \emph{not} indicate the packing strategy applied to prove the respective result.} \end{figure} \begin{corollary} Let $F > 1$, $V>0$ and $C >0$. Then any set of squares of total area $V$ and with maximum edge length at most $\frac{(F-1)V}{C}$ fits into any rectangle with edge lengths $a_1$ and $a_2$ satisfying $F\cdot V=a_1\cdot a_2$ and $a_1+a_2\leq C$. \label{circumference} \end{corollary} \begin{proof} Let $x$ denote the maximum edge length among the given squares and let $a_1$ and $a_2$ be as in the statement of the corollary. First, note that \[x\leq \frac{(F-1)V}{C}\leq \frac{FV}{C}\leq \frac{a_1\cdot a_2}{a_1+a_2}\leq \min\{a_1,a_2\}.\] Moreover, $x\cdot(a_1+a_2)\leq \frac{(F-1)V}{C}\cdot C=(F-1)V$. Hence, \[x^2+(a_1-x)\cdot(a_2-x)= 2x^2+a_1\cdot a_2 -x\cdot (a_1+a_2)\geq 2\cdot 0+ FV-(F-1)V=V,\] so Theorem~\ref{MeirMoser} yields the claim. \end{proof} Let $F\geq\frac{2+\sqrt{3}}{3}$ be fixed. \begin{proposition} Let $(s_i)_{i\in\mathbb{N}^+}$ be a non-increasing sequence of non-negative numbers such that $\sum_{i=1}^{\infty}s_i^2=1$.\newline If $s_1\leq \frac{1}{10}$, then there exists an internally disjoint packing of the squares with edge lengths $(s_i)_{i\in\mathbb{N}^+}$ into a square of edge length $\sqrt{F}$. \label{small_s1} \end{proposition} \begin{proof} We have $\sqrt{F}\geq\sqrt{\frac{2+\sqrt{3}}{3}}>\frac{11}{10}>\frac{1}{10}\geq s_1$ and, hence, also $\sqrt{F}-s_1 > 1$. Therefore, we get $s_1^2+(\sqrt{F}-s_1)^2>1$, so Theorem~\ref{MeirMoser} yields the claim. \end{proof} \begin{definition}[whitespace] Let a closed rectangle $R$ and a set $\mathcal{S}$ of closed squares be given, such that each of the squares in $\mathcal{S}$ is contained within $R$ and the interiors of two distinct squares from $\mathcal{S}$ do not intersect. We define the whitespace $\mathrm{whitespace}(R,\mathcal{S})$ arising from this packing of the squares in $\mathcal{S}$ into $R$ to equal \[\mathrm{whitespace}(R,\mathcal{S}):=\overline{R\backslash \bigcup_{S\in\mathcal{S}}S},\] where for a set $A$ of points in the Euclidean plane, $\bar{A}$ denotes its topological closure.\label{DefWhitespace} \end{definition} \begin{lemma} Let $c:= \sqrt{\left(\frac{3}{10}\right)^2+\frac{F-1}{5}}-\frac{3}{10}$. Then for $n\geq\max\{ (10F+\frac{1}{10})^2, 100c^2\}$ and any packing of $n$ squares of total area at most $1$ into a rectangle with edge lengths $\frac{1}{10}\leq W\leq H$ and area $W\cdot H=F$, any set of squares of total area at most $c^2$ and maximum edge length at most $\frac{c}{\sqrt{n}}$ permits an axis-parallel, internally disjoint packing into the arising whitespace. \label{PackRemainingSquares} \end{lemma} \begin{proof} Let $n\geq \max\{ (10F+\frac{1}{10})^2, 100c^2\}$ be a natural number and let $n$ squares $S_1,\dots,S_n$ with edge lengths $s_1,\dots,s_n$ and total area at most $1$ be given. Consider a packing of these squares into an enclosing rectangle $R$ with edge lengths $\frac{1}{10}\leq W\leq H$ and area $F$.\\ Moreover, let a set of squares of total area at most $c^2$ and maximum edge length at most $\frac{c}{\sqrt{n}}$ be given by a sequence $\frac{c}{\sqrt{n}}\geq s_{n+1}\geq s_{n+2}\geq\dots$. For a finite set, we have $s_j=0$ from some point on.\\ Let $k\geq n+1$ and assume that squares of edge lengths $s_{n+1},\dots,s_{k-1}$ have already been accommodated within the whitespace. Our goal is to find a lower bound on the area of the set of points in $R$ that serve as potential midpoints for squares of edge length $s_k$ contained in the remaining whitespace. If we can provide a positive lower bound on the area of the set of potential square midpoints for each $k\geq n+1$ for which $s_k>0$, this in particular implies that this set will never be empty. Hence, we can inductively construct a packing of the squares with edge length $s_{n+1}\geq s_{n+2}\geq\dots$ into the whitespace by always placing the next square at the lexicographically minimum feasible position. The latter exists as the space of feasible positions is compact.\\ Let $k\geq n+1$ such that $s_k>0$ and assume that squares $(S_i)_{i=n+1}^{k-1}$ with edge lengths $(s_i)_{i=n+1}^{k-1}$ have been placed axis-parallel and internally disjoint within the whitespace. Observe that the square of edge length $s_k$ with midpoint $p\in R$ is contained within the (remaining) whitespace if and only if the $l_\infty$-distance of $p$ to each of the $S_i$ for $i=1,\dots,k-1$ and to the boundary of $R$ is at least $\frac{s_k}{2}$. For $i=1,\dots,k-1$, let $S'_i$ denote the square arising from $S_i$ by extending it by $\frac{s_k}{2}$ in positive and negative $x$- and $y$-direction and let $F_i:=S'_i\backslash S_i$ for $i=1,\dots,n$. Moreover, let $R'$ be the rectangle with edge lengths $W-s_k$ an $H-s_k$ lying centered within $R$ (note that $s_k\leq\frac{c}{\sqrt{n}}\leq\frac{1}{10}\leq W\leq H$ by our choice of $n$) and let further $F_R:=R\backslash R'$. Then, for a point $p$ openly contained in the original whitespace, the square with midpoint $p$ and edge length $s_k$ is contained in the remaining whitespace after additionally packing $(S_i)_{i=n+1}^{k-1}$ if and only if $p$ is not openly contained within any of the frames $(F_i)_{i=1}^n$ around the squares $(S_i)_{i=1}^{n}$, any of the squares $(S'_i)_{i=n+1}^{k-1}$, or the frame $F_R$ inscribed into $R$. Figure~\ref{FigFeasibleMidpoints} illustrates the case $k=n+1$. \begin{figure}[t] \centering \begin{tikzpicture}[scale = 0.7, greenrect/.style = {draw = green!70!black, fill = {rgb:green,7;black,3;white,10}}] \draw[thick, black] (0,-0.5) rectangle (10.5,7.5); \draw[draw = none, pattern = north east lines, pattern color = red!70!black, fill opacity = 0.7] (0,-0.5) rectangle (10.5,7.5); \draw[draw = none, fill = white] (0.5,0) rectangle (10,7); \draw[draw = none, pattern = north east lines, pattern color = red!70!black, fill opacity = 0.7] (1,1) rectangle (5,5); \draw[draw = none, pattern = north east lines, pattern color = red!70!black, fill opacity = 0.7] (0.5,5) rectangle (2.5,7); \draw[draw = none, pattern = north east lines, pattern color = red!70!black, fill opacity = 0.7] (2.5,5) rectangle (4.5,7); \draw[draw = none, pattern = north east lines, pattern color = red!70!black, fill opacity = 0.7] (6,0) rectangle (9,3); \draw[draw = none, pattern = north east lines, pattern color = red!70!black, fill opacity = 0.7] (5.5,3) rectangle (9.5,7); \draw[draw = blue, fill = blue!50!white] (1.5,1.5) rectangle (4.5,4.5); \draw[draw = blue, fill = blue!50!white] (1,5.5) rectangle (2,6.5); \draw[draw = blue, fill = blue!50!white] (3,5.5) rectangle (4,6.5); \draw[draw = blue, fill = blue!50!white] (6.5,0.5) rectangle (8.5,2.5); \draw[draw = blue, fill = blue!50!white] (6,3.5) rectangle (9,6.5); \draw[greenrect] (2.3,0.5) rectangle (3.3,1.5); \node at (2.8,1){\textcolor{green!50!black}{$\times$}}; \end{tikzpicture} \caption{The white area that is not shaded remains feasible for midpoints of whitespace squares.}\label{FigFeasibleMidpoints} \end{figure} In particular, as the area of the (original) whitespace is at least $F-1$, the area of the set $M$ of potential midpoints of whitespace squares amounts to \[\textrm{area}(M)\geq F-1-\sum_{i=1}^{n}\textrm{area}(F_i)-\textrm{area}(F_R)-\sum_{i=n+1}^{k-1}\mathrm{area}(S'_i).\] We have \[\textrm{area}(F_i)=4\cdot s_i\cdot\frac{s_k}{2}+4\cdot\left(\frac{s_k}{2}\right)^2 = 2\cdot s_k\cdot s_i +s_k^2\] and \[\textrm{area}(F_R)=2\cdot (H+W)\cdot\frac{s_k}{2}-4\cdot\left(\frac{s_k}{2}\right)^2=(H+W)\cdot s_k-s_k^2.\] By the inequality between arithmetic and quadratic mean, we know that \[ \frac{\sum_{i=1}^{n}s_i}{n}\leq \sqrt{\frac{\sum_{i=1}^{n}s_i^2}{n}}\leq\sqrt{\frac{1}{n}} \qquad\Rightarrow\qquad \sum_{i=1}^{n}s_i \leq \sqrt{n}.\] We further have $H=\frac{F}{W}$ and $W\in[\frac{1}{10},\sqrt{F}]$ since $\frac{1}{10}\leq W\leq H$, so by convexity of the function $[\frac{1}{10},\sqrt{F}]\rightarrow\mathbb{R}^+,W\mapsto W + \frac{F}{W}$, which attains its minimum at $\sqrt{F}$ and is, therefore, monotonically decreasing, it follows that \[W+H\leq \frac{1}{10}+\dfrac{F}{\frac{1}{10}} = 10F+ \frac{1}{10}\leq\sqrt{n},\] where the last inequality is implied by our choice of $n$. Moreover, \[\sum_{i=n+1}^{k-1}\mathrm{area}(S'_i) = \sum_{i=n+1}^{k-1} (s_i+s_k)^2\leq \sum_{i=n+1}^{k-1} (2s_i)^2 = 4\sum_{i=n+1}^{k-1} s_i^2\leq 4(c^2-s_k^2),\] because the sequence $(s_i)_{i\geq n+1}$ is non-increasing. Hence, we obtain \begin{align*}\textrm{area}(M) &\geq F-1-\sum_{i=1}^{n}(2\cdot s_i\cdot s_k + s_k^2) -( (W+H)\cdot s_k -s_k^2 )-4(c^2-s_k^2)\\ &\geq F-1 -2\sqrt{n}\cdot s_k-n\cdot s_k^2 -\sqrt{n}\cdot s_k + s_k^2 -4c^2+4s_k^2 \\ &> F-1-4c^2 -3\sqrt{n}\cdot s_k-n\cdot s_k^2 \end{align*} and we need to see that the latter term is non-negative whenever $s_k>0$. To this end, we first want to show that our choice of $c$ implies \begin{equation}4\cdot c^2 \leq F.\label{Fgeq4csquared}\end{equation} We have \begin{alignat}{6} &4\cdot c^2 &&&\leq&\quad F \\ \Leftrightarrow\quad& 4\cdot \Biggl( \sqrt{\left(\frac{3}{10}\right)^2+\frac{F-1}{5}}&-&\frac{3}{10}\Biggr)^2 &\leq&\quad F\notag\\ \Leftrightarrow\quad& 4\cdot\left(\left(\frac{3}{10}\right)^2+\frac{F-1}{5}\right)&-&\quad 8\cdot \sqrt{\left(\frac{3}{10}\right)^2+\frac{F-1}{5}}\cdot\frac{3}{10}+4\cdot\left(\frac{3}{10}\right)^2 &\leq&\quad F\notag\\ \Leftrightarrow\quad& \frac{9}{25}+\frac{4}{5}\cdot F-\frac{4}{5}+\frac{9}{25} &\leq&\quad F+ \frac{12}{5}\cdot \sqrt{\left(\frac{3}{10}\right)^2+\frac{F-1}{5}}&&\notag\\ \Leftrightarrow\quad& \frac{18}{25}-\frac{20}{25} &\leq&\quad \frac{F}{5}+\frac{12}{5}\cdot \sqrt{\left(\frac{3}{10}\right)^2+\frac{F-1}{5}}&&\notag\\ \Leftrightarrow\quad& -\frac{2}{25} &\leq&\quad \frac{F}{5}+\frac{12}{5}\cdot \sqrt{\left(\frac{3}{10}\right)^2+\frac{F-1}{5}},&&\notag \end{alignat} which is true since the left hand side is negative and the right hand side is positive as $F>1$.\\ Now, we show that $0<s_k\leq \frac{c}{\sqrt{n}}$ and our assumptions on $c$ and $n$ imply that \[F-1-4c^2 -3\sqrt{n}\cdot s_k-n\cdot s_k^2\geq 0.\] As $F-1-4c^2-3\sqrt{n}\cdot x-n\cdot x^2 = 0$ if and only if \[x=\frac{1}{\sqrt{n}}\cdot\left(-\frac{3}{2}-\sqrt{\frac{9}{4}+F-1-4c^2}\right)\text{ or }x=\frac{1}{\sqrt{n}}\cdot\left(-\frac{3}{2}+\sqrt{\frac{9}{4}+F-1-4c^2}\right),\] where the discriminant is positive by~\eqref{Fgeq4csquared}, we know that $\mathrm{area}(M)>0$, provided that \linebreak[4] $s_k\leq \frac{1}{\sqrt{n}}\cdot\left(-\frac{3}{2}+\sqrt{\frac{9}{4}+F-1-4c^2}\right)$. To this end, as $s_k\leq\frac{c}{\sqrt{n}}$, it suffices to see that we have $c\leq -\frac{3}{2}+\sqrt{\frac{9}{4}+F-1-4c^2}$, or, equivalently, $c+\frac{3}{2}\leq \sqrt{\frac{9}{4}+F-1-4c^2}$ respectively $(c+\frac{3}{2})^2\leq \frac{9}{4}+F-1-4c^2$ since $c>0$. We get \begin{alignat*}{3} &\qquad\left(c+\frac{3}{2}\right)^2\quad &\leq&\quad \frac{9}{4}+F-1-4c^2\\ \Leftrightarrow &\qquad c^2 + 3c + \frac{9}{4} &\leq&\quad \frac{9}{4}+F-1-4c^2\\ \Leftrightarrow &\qquad 5c^2 + 3c -(F-1) \quad &\leq&\qquad 0\\ \Leftrightarrow &\qquad c^2+\frac{3}{5}c-\frac{F-1}{5} \quad &\leq&\qquad 0, \end{alignat*} which is equivalent to $-\frac{3}{10}-\sqrt{\left(\frac{3}{10}\right)^2+\frac{F-1}{5}}\leq c\leq -\frac{3}{10}+\sqrt{\left(\frac{3}{10}\right)^2+\frac{F-1}{5}}$ and follows from our choice of $c$ and since the left hand term is negative.\\ Hence, whenever $s_k>0$, the set of feasible midpoint locations for the respective square is non-empty, which concludes the proof. \end{proof} \begin{lemma} Let $c$ be defined as in Lemma~\ref{PackRemainingSquares} and let \[\delta:=\dfrac{F-1}{\frac{10F}{c^2}+\frac{1}{10}}.\] Then any set of squares with total area $V$ satisfying $c^2\leq V\leq 1$ and maximum edge length at most $\delta$ can be packed into any rectangle of area $F\cdot V$ with greater edge length at most $10F$. \label{delta} \end{lemma} \begin{proof} Let $0<a_1\leq a_2\leq 10F$ be the edge lengths of a rectangle of area $F\cdot V=a_1\cdot a_2$. Then we have $\sqrt{FV}\leq a_2\leq 10F$. As the function $(0,\infty)\rightarrow \mathbb{R}^+,$ $x\mapsto x +\frac{FV}{x}$ is convex and attains its minimum at $\sqrt{FV}$, it is monotonically increasing on $[\sqrt{FV},\infty)$. Consequently, we obtain \[a_1+a_2=a_2+\frac{FV}{a_2}\leq 10F+\frac{FV}{10F}=10F+\frac{V}{10}.\] By Corollary~\ref{circumference}, we know that any set of squares with total area $V$ and maximum edge length at most \[\dfrac{(F-1)V}{10F+\frac{V}{10}}=\dfrac{F-1}{\frac{10F}{V}+\frac{1}{10}}\] can be packed into the given rectangle. Since $V\geq c^2$, we have \[\delta=\dfrac{F-1}{\frac{10F}{c^2}+\frac{1}{10}}\leq \dfrac{F-1}{\frac{10F}{V}+\frac{1}{10}},\] so the latter holds in particular for any set of squares of total area $V$ and maximum edge length at most $\delta$. \end{proof} \begin{remark} A slightly better value of $\delta$ can be achieved in the following way: Let \[K:=\left\{(V,H): c^2\leq V\leq 1, \sqrt{FV}\leq H\leq 10F, \text{\scriptsize$\left(\dfrac{H+\frac{FV}{H}}{4}\right)^2\geq \frac{(F-1)V}{2}$}\right\}.\] Then $K$ is compact. Consider \begin{align*}f:=K&\rightarrow\mathbb{R}^+,\\ (V,H)&\mapsto \dfrac{H+\frac{FV}{H}}{4} - \sqrt{\left(\dfrac{H+\frac{FV}{H}}{4}\right)^2-\frac{(F-1)V}{2}}.\end{align*} This is a continuous function mapping $(V,H)$ to the smallest solution $x$ of \[x^2+\Bigl(H-x\Bigr)\cdot\left(\frac{FV}{H}-x\right)=V,\] if exists. Note that $K$ is just the set of all possible areas $V$ and greater edge lengths $H$ for which the discriminant is non-negative and such a solution does exist. Moreover, observe that we have $x^2+(H-x)\cdot(\frac{FV}{H}-x)\geq V$ for both $(V,H)\not\in K$ or $(V,H)\in K$ and $0\leq x\leq f(V,H)$ since $0^2+(H-0)\cdot(\frac{FV}{H}-0)=FV > V$ and by the intermediate value theorem. If $K$ is non-empty, then by compactness of $K$ and continuity of $f$, let $\delta_1$ be the minimum of $f$, otherwise let $\delta_1=1$. In either case, $\delta_1>0$ since all function values of $f$ are positive because \[\frac{(F-1)V}{2}>0 \quad\text{and}\quad \dfrac{H+\frac{FV}{H}}{4}>0\quad\text{for all positive values of $H$.}\] Let $\delta:=\min\{\delta_1,\frac{c^2}{10}\}$. Then for any $c^2\leq V\leq 1$ and any rectangle $R$ of area $FV$ and with greater edge length $H\leq 10F$, the smaller edge length $W=\frac{FV}{H}$ measures at least $\frac{c^2}{10}\geq \delta$. Besides, by choice of $\delta_1$ and as $\delta\leq \delta_1$, we have $x^2+(H-x)\cdot(W-x)\geq V$ for all $0\leq x\leq \delta$. By Theorem~\ref{MeirMoser}, any set of squares with total area $V$ and maximum edge length at most $\delta$ can be packed into $R$.\hfill $\qedsymbol$ \end{remark} \begin{lemma} Let $c$ be as in Lemma~\ref{PackRemainingSquares}, $\delta$ as in Lemma~\ref{delta} and define $N_0:=\max\{1,\lfloor\frac{1}{\delta^2}\rfloor\}$. Assume that for any set $S$ of at most $N_0$ squares of total area $1$, there exists a rectangle $R$ of area $F$ into which the squares in $S$ can be packed axis-parallel and internally disjoint.\\ Let $(s_i)_{i\in\mathbb{N}^+}$ be a non-increasing sequence of non-negative numbers such that\begin{itemize} \item $s_1\geq\frac{1}{10}$, \item $\sum_{i=1}^\infty s_i^2=1$ and \item $\sum_{i=N_0+1}^{\infty}s_i^2\geq c^2$.\end{itemize} Then, there exists a rectangle $R$ of area $F$ into which the squares with edge lengths given by $(s_i)_{i\in\mathbb{N}^+}$ permit an axis-parallel, internally disjoint packing. \label{N0} \end{lemma} \begin{proof} Let $(s_i)_{i\in\mathbb{N}^+}$ be as in the lemma. Note that since $s_1\geq \frac{1}{10}$, the total area of the first $N_0$ squares is strictly positive. Apply the assumption stated for sets of at most $N_0$ squares to the set of squares the edge lengths of which arise from the sequence $(s_i)_{i=1}^{N_0}$ by normalizing the area $\sum_{i=1}^{N_0} s_i^2$ to $1$, and then scale back. We obtain a rectangle $R'$ of area $F\cdot \sum_{i=1}^{N_0}s_i^2 \leq F$ into which we can pack the squares with edge lengths $s_1,\dots, s_{N_0}$. Let $W'$ be the smaller edge length of $R'$. Then \[\frac{1}{10}\leq s_1\leq W'\leq \sqrt{F}\cdot\sqrt{\sum_{i=1}^{N_0}s_i^2}\leq \sqrt{F}.\] Let $V:= \sum_{i=N_0+1}^{\mathbb{\infty}}s_i^2$ and let $R''$ be the rectangle with edge lengths $W'$ and $\frac{FV}{W'}$. Then \mbox{$c^2 \leq V \leq 1$} and for the greater edge length $H''$ of $R''$, we have \[H''=\max\left\{W',\frac{FV}{W'}\right\}\leq\max\left\{\sqrt{F},\dfrac{F}{\frac{1}{10}}\right\}=10F.\] Additionally, $s_1\geq\dots\geq s_{N_0}\geq s_{N_0+1}$ and $\sum_{i=1}^{\infty}s_i^2=1$ yield $s_{N_0+1}\leq\frac{1}{\sqrt{N_0+1}}\leq \delta$, so by Lemma~\ref{delta}, we can pack the squares with edge lengths $s_{N_0+1},s_{N_0+2},\dots$ into the rectangle $R''$. Gluing $R'$ and $R''$ together at the edge of length $W'$ yields a rectangle $R$ of area \[F\cdot \left(\sum_{i=1}^{N_0}s_i^2 +\sum_{i=N_0+1}^{\mathbb{\infty}}s_i^2\right)=F\] containing all squares (see Figure~\ref{FigGlueingRectangles}). \end{proof} \begin{figure}[t] \centering \begin{tikzpicture}[scale = 0.3] \draw[thick] (0,0) rectangle (20,10); \node[align = left] at (10,5){\small rectangle $R'$ of area $F\cdot\sum_{i=1}^{N_0}s_i^2$\\ containing the first $N_0$ squares}; \draw[draw =green!70!black, pattern = north east lines, pattern color = green!70!black] (20,0) rectangle (21,1); \draw[<->] (21,-0.4)to (20,-0.4); \node at (20.5,-1){\tiny $\delta$}; \draw[<->] (19.6,0) to (19.6,1); \node at (19,0.5){\tiny $\delta$}; \draw[draw =green!70!black, pattern = north east lines, pattern color = green!70!black] (21,1) rectangle (25,10); \draw[thick] (20,0) rectangle (25,10); \node at (26,5){$\leftarrow$}; \node[align = left] at (33,5) {\small Meir-Moser rectangle $R''$\\ of area $F\cdot\sum_{i= N_0+1}^\infty s_i^2$}; \end{tikzpicture} \caption{Gluing together $R'$ and $R''$ provides the desired packing.}\label{FigGlueingRectangles} \end{figure} \begin{theorem} Let $N_0$ as in Lemma~\ref{N0} and $c$ as in Lemma~\ref{PackRemainingSquares} and define \begin{itemize}\item $N_1:=\left\lfloor\max\left\{N_0, \left(10F+\frac{1}{10}\right)^2, 100c^2\right\}\right\rfloor$ as well as \item $N:=\lfloor\mathrm{e}^2\cdot N_1\rfloor.$\end{itemize} Then any set of squares of total area $1$ can be packed into some rectangle of total area $F$, provided this holds for any set of at most $N$ squares of total area $1$. \end{theorem} \begin{proof} Note that for any natural number $n$, we have \begin{align*} \ln(n+1)&=\int_1^{n+1}\frac{1}{x}dx \leq \sum_{i=1}^{n} (i+1-i)\cdot\frac{1}{i}=\sum_{i=1}^n \frac{1}{i} = 1+\sum_{i=2}^n\frac{1}{i}\\ &=1+\sum_{i=1}^{n-1}(i+1-i)\cdot\frac{1}{i+1}\leq 1+\int_1^n\frac{1}{x}dx = \ln(n)+1\\ \Rightarrow \ln(n+1)&\leq \sum_{i=1}^n \frac{1}{i}\leq \ln(n)+1.\end{align*} By our choice of $N$ and since $N_1\geq\lfloor N_0\rfloor=N_0\geq 1$, we have \begin{align*}\sum_{i=N_1+1}^{N}\frac{1}{i} &= \sum_{i=1}^{N}\frac{1}{i}-\sum_{i=1}^{N_1}\frac{1}{i}\geq \ln(N+1)-\ln(N_1)-1\geq \ln(\mathrm{e}^2N_1)-\ln(N_1)-1\\ &=\ln\left(\frac{\mathrm{e}^2N_1}{N_1}\right)-1=\ln(\mathrm{e}^2)-1=2-1=1.\end{align*} In particular, we get \begin{equation} \sum_{i=N_1+1}^{N}\frac{c^2}{i}\geq c^2. \label{Eqatleastc2} \end{equation} Consider any set of squares of total area $1$ and the corresponding non-increasing sequence $(s_i)_{i\in\mathbb{N}^+}$ of edge lengths. If $s_1\leq\frac{1}{10}$, we are done by Proposition~\ref{small_s1}.\\ So assume $s_1> \frac{1}{10}$. If $\sum_{i=N_1+1}^{\infty}s_i^2 \geq c^2$, then we are done by Lemma~\ref{N0} and our assumption since $N_0\leq N_1$ because $N_0$ is integral, and, therefore, also $\sum_{i=N_0+1}^{\infty}s_i^2 \geq c^2$. Hence, we can further assume that $\sum_{i=N_1+1}^{\infty}s_i^2 < c^2$. As $\sum_{i=N_1+1}^{N}\frac{c^2}{i} \geq c^2$ by \eqref{Eqatleastc2}, we cannot have $s_i\geq \frac{c}{\sqrt{i}}$ for all $N_1+1\leq i\leq N$, so there is $N_1+1\leq n\leq N$ with $s_n< \frac{c}{\sqrt{n}}$. By our packing assumption for sets of at most $N\geq n$ squares, we know that the squares with edge lengths $s_1,\dots,s_{n-1},\sqrt{1-\sum_{i=1}^{n-1}s_i^2}\geq s_n$ can be packed into some rectangle of area $F$, so this in particular also holds for the squares with edge lengths $s_1,\dots,s_n$. But now, as we also have $\sum_{i=n+1}^{\infty}s_i^2 \leq \sum_{i=N_1+1}^{\infty}s_i^2 < c^2$ and $\frac{c}{\sqrt{n}}\geq s_n\geq s_{n+1}\geq s_{n+2}\geq\dots$, we can apply Lemma~\ref{PackRemainingSquares}, knowing that $n\geq N_1+1\geq\max\{(10F+\frac{1}{10})^2, 100c^2\}$, to conclude the statement of the theorem. \end{proof} \section{Computing the Value of \texorpdfstring{$N$}{N}} In this section, we first compute the value of $N$ we achieve for $F=\frac{2+\sqrt{3}}{3}$ and then comment on some strategies to improve on the obtained value for any $F\geq \frac{2+\sqrt{3}}{3}$. Anyhow, as none of these seems to result in a value of $N$ providing hope to tackle the proof for at most $N$ squares by a computer-aided case distinction, we do not go into full details.\\ For $F=\frac{2+\sqrt{3}}{3}$, we first get a value of \[c=\sqrt{\left(\frac{3}{10}\right)^2+\frac{F-1}{5}}-\frac{3}{10}\approx 0.07256.\] From this, we get \[\delta=\dfrac{F-1}{\frac{10F}{c^2}+\frac{1}{10}}\approx 1.03278\cdot 10^{-4},\] which in turn provides a value of \[N_0=\left\lfloor\frac{1}{\delta^2}\right\rfloor = 93,752,341.\] From this, we obtain \[N_1=\left\lfloor\max\left\{N_0,\left(10F+\frac{1}{10}\right)^2,100c^2\right\}\right\rfloor=N_0=93,752,341\] and, finally, \[N=\left\lfloor \mathrm{e}^2 N_1\right\rfloor=692,741,307.\] Observe that this value of $N$ indeed provides an upper bound on the values $N(F)$ for $F\in[\frac{2+\sqrt{3}}{3},1.37]$: First, $c$ is monotonically increasing as a function of $F$, and \[\delta=\dfrac{F-1}{\frac{10F}{c^2}+\frac{1}{10}}=\dfrac{1-\frac{1}{F}}{\frac{10}{c^2}+\frac{1}{10F}}\] is monotonically increasing in both $c$ and $F$, when regarding them as independent parameters. This implies that larger values of $F$ result in larger values of $c$ and $\delta$, and hence smaller values of $N_0$. Given that for values of $F\in[\frac{2+\sqrt{3}}{3},1.37]$, the values $\max\left\{\left(10F+\frac{1}{10}\right)^2,100c^2\right\}$ may attain are several orders of magnitude smaller than the value of $N_0$ we receive for $F=\frac{2+\sqrt{3}}{3}$, it follows that $F=\frac{2+\sqrt{3}}{3}$ yields the maximum value of $N_1$ and, hence, $N$.\\ In order to improve on this value, there are several possible starting points. First, note that instead of choosing $\frac{1}{10}$ as a threshold for the value of $s_1$, we could take the smaller solution of $x^2+(\sqrt{F}-x)^2=1$, which is greater than $\sqrt{F}-1>\frac{1}{10}$. This slightly improves our bounds on the perimeter of the rectangles under consideration and, therefore, results in larger values of $c$ and $\delta$.\\ Next, note that in the proof of Lemma~\ref{PackRemainingSquares}, the considered packing has to be chosen particularly unlucky for none of the frames around the squares to intersect with another frame (around a square or inside of the enclosing rectangle), another square or the outside. By considering a bottom-left minimal packing (i.e.\ a packing where no square can be shifted to the left or to the bottom while keeping the other squares fixed), for example, a better bound on the area we lose due to the frames and hence a larger value of $c$ can be established. Moreover, we have already discussed how to (slightly) improve the value of $\delta$ obtained in Lemma~\ref{delta}.\\ However, a step that seems to be particularly wasteful and that we, therefore, consider worth being discussed in a bit more detail is our choice of $N_0$ in Lemma~\ref{N0}:\\ There, we pick $N_0:=\max\{1,\lfloor \frac{1}{\delta^2}\rfloor\}$ in order to ensure that the $N_0+1^\text{st}$ square has an edge length of no more than $\delta$. Although it is true that this is (almost) the minimum choice of $N_0$ that can guarantee this property, it is not hard to see that a much weaker condition would actually be sufficient for our purposes. To this end, observe that in the case where we really have $s_{N_0+1}=\frac{1}{\sqrt{N_0+1}}$, it immediately follows from the way the edge lengths are ordered and the fact that the total area is $1$ that also $s_1=s_2=\dots=s_{N_0}=\frac{1}{\sqrt{N_0+1}}$. In particular, the edge lengths of the first few squares are extremely small compared to the total area of the remaining ones, which is still close to $1$, so by the same \grqq gluing\grqq\space argument as applied in the proof of Lemma~\ref{N0}, we know that we are actually done at a much earlier stage.\\ In this spirit, the goal of the following considerations is to \grqq speed up\grqq\space the descent down to a total area of at most $c^2$ by considering lower bounds on the edge length $s_n$ of the $n^\text{th}$ square depending on the remaining area $\sum_{i=n+1}^\infty s_i^2$ and showing that we are already done after considering the first $n$ squares if these are not met.\\ More precisely, fix some $F\geq\frac{2+\sqrt{3}}{3}$ and consider a continuous, monotonically increasing function $\delta:[c^2,1]\rightarrow(0,1]$ with the following properties: Given an area $V\in[c^2,1]$ and a rectangle $R$ of area $FV$ such that the greater edge length of $R$ measures at most $10F$ (or $\frac{F}{\sqrt{F}-1}$, applying a better threshold for the minimum size of $s_1$, which still satisfies $\max\left\{\sqrt{F},\frac{F}{\sqrt{F}-1}\right\} =\frac{F}{\sqrt{F}-1}$ as required in the proof of Lemma~\ref{N0}), any set of squares of total area $V$ and maximum occurring edge length $\delta(V)$ can be packed into $R$. Analogously to the proof of Lemma~\ref{delta}, one can see that \[[c^2,1]\rightarrow(0,1],V\mapsto \dfrac{F-1}{\frac{10F}{V}+\frac{1}{10}}\] is a feasible choice for $\delta$. Given such a function $\delta$, we show how to obtain an improved value of $N_0$: \begin{lemma} Let $N_0:=1+\lfloor\int_{c^2}^1\frac{1}{\delta(V)^2}dV\rfloor$. Note that the considered integral exists since $\delta$ is monotonically increasing with minimum value $\delta(c^2)>0$. Assume that for any set $S$ of at most $N_0$ squares of total area $1$, there exists a rectangle $R$ of area $F$ into which the squares in $S$ can be packed axis-parallel and internally disjoint.\\ Let $(s_i)_{i\in\mathbb{N}^+}$ be a non-increasing sequence of non-negative numbers such that\begin{itemize} \item $s_1\geq\frac{1}{10}$, \item $\sum_{i=1}^\infty s_i^2=1$ and \item $\sum_{i=N_0+1}^{\infty}s_i^2\geq c^2$.\end{itemize} Then, there exists a rectangle $R$ of area $F$ into which the squares with edge lengths given by $(s_i)_{i\in\mathbb{N}^+}$ permit an axis-parallel, internally disjoint packing. \end{lemma} \begin{proof} Consider a non-increasing sequence of non-negative numbers $(s_i)_{i\in\mathbb{N}^+}$ satisfying $s_1\geq\frac{1}{10}$, $\sum_{i=1}^\infty s_i^2=1$ and $\sum_{i=N_0+1}^{\infty}s_i^2\geq c^2$. We show that there exists some $1\leq n\leq N_0$ such that $s_n<\delta(\sum_{i=n}^\infty s_i^2)$. Assume that this is not the case. Then in particular $s_n>0$ for all $1\leq n\leq N_0$ since all function values of $\delta$ are positive, and, moreover, $s_n^2\geq \delta(\sum_{i=n}^\infty s_i^2)^2$ and $\frac{1}{s_n^2}\leq\frac{1}{\delta(\sum_{i=n}^\infty s_i^2)^2}$.\\ We have \begin{align*} N_0 &= \sum_{n=1}^{N_0} \frac{s_n^2}{s_n^2}\leq\sum_{n=1}^{N_0}\frac{s_n^2}{\delta(\sum_{i=n}^\infty s_i^2)^2}=\sum_{n=1}^{N_0}\left(\sum_{i=n}^{\infty}s_i^2-\sum_{i=n+1}^\infty s_i^2\right)\cdot\frac{1}{\delta(\sum_{i=n}^\infty s_i^2)^2}\\ &\leq \sum_{n=1}^{N_0}\int_{\sum_{i=n+1}^\infty s_i^2}^{\sum_{i=n}^\infty s_i^2}\frac{1}{\delta(V)^2}dV = \int_{\sum_{i=N_0+1}^\infty s_i^2}^{\sum_{i=1}^\infty s_i^2} \frac{1}{\delta(V)^2}dV\leq \int_{c^2}^1 \frac{1}{\delta(V)^2}dV<N_0, \end{align*} a contradiction. Therefore, there exists some $1\leq n\leq N_0$ such that $s_n<\delta(\sum_{i=n}^\infty s_i^2)$. If $n=1$, we are done by definition of $\delta$. Otherwise, our requirements on the function $\delta$ allow us to conduct the same argument as in the proof of Lemma~\ref{N0} to obtain the desired packing. \end{proof} Using the function $\delta:[c^2,1]\rightarrow(0,1], V\mapsto \dfrac{F-1}{\frac{10F}{V}+\frac{1}{10}}$ for $F=\frac{2+\sqrt{3}}{3}$, we obtain an improved value of \[N_0=1+\left\lfloor\int_{c^2}^1\frac{1}{\delta(V)^2}dV\right\rfloor = 491,225.\] As a consequence, we get \[N_1=\left\lfloor\max\left\{N_0,\left(10F+\frac{1}{10}\right)^2,100c^2\right\}\right\rfloor=N_0=491,225\] and finally \[N=\lfloor \mathrm{e}^2 N_1\rfloor=3,629,689,\] which is already by a factor of more than $190$ smaller than the previous result. As before, it is not hard to see that the value of $N$ we obtain by applying the previous calculations indeed attains its maximum among all $F\in[\frac{2+\sqrt{3}}{3},1.37]$ for $F=\frac{2+\sqrt{3}}{3}$.\\ We remark that by making use of a slightly more sophisticated version of the $\delta$-function, that arises by attaching the rectangle $R''$ from the proof of Lemma~\ref{N0} at the smaller edge length of $R'$, if $V\leq \frac{1}{2}$, and at the greater edge length, if $V\geq \frac{1}{2}$, it is possible to get down to a value of $N\leq 26,000$. However, as we do not think that a reduction of the provided constant in this order of magnitude changes the qualitative statement of this paper, we spare the details of the computation. \newpage
{'timestamp': '2021-03-12T02:19:41', 'yymm': '2103', 'arxiv_id': '2103.06597', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06597'}
arxiv
\section{Introduction} \label{sec:introduction} With the advancement of sensing, surveillance, wireless connectivity and Internet-of-Things (IoT) technologies, current transportation networks can be supported with reliable sources of information about the traffic flow in the network and the congestion levels all over the network. Traffic information is a good asset that can be utilized by both the network operator and users to enhance the efficiency of traffic flow. In particular, we can think of two main domains of exploiting traffic information. The first one is the use of recorded historic information about traffic flows in machine learning applications such as traffic prediction and forecasting, and trips' scheduling and planning. The second one is the use of real-time (i.e., live) information about the network congestion levels in adaptive control applications such as updating routing plans dynamically to arrive at destination as quick as possible. In this work, we focus on the utility of real-time information in dynamic routing to enhance the efficiency of traffic flow and mitigate traffic jams. The advantages of utilizing traffic information have been demonstrated in a number of papers in the literature. For example, in \cite{Kim}, the value of real-time traffic information from the perspectives of a time-sensitive freight service that aims to determine the optimal routing policies as well as departure times is examined. The paper demonstrated the advantages of real-time information in terms of total cost savings and vehicle usage reduction. In another work, it is demonstrated that even when information is shared in a decentralized manner it can considerably improve the network performance \cite{Claes}. Furthermore, a decentralized approach to collect and distribute traffic forecast information is proposed as an alternative to depending solely on a central network coordinator. There are other works that focused mainly on developing routing algorithms. For example, a nice survey of search algorithms that can be used for routing problems is provided in the introduction of \cite{Xiao}. Then, a new algorithm is also proposed to exploit the information that is collected while a vehicle is en route to improve the routing quality. In \cite{Gitae}, the problem of estimating the probability distribution of travel time is investigated. A Markov decision process model is used, and approximate dynamic programming is applied. In another work, the combination of historical and real-time information is investigated in the context of a centralized navigation system \cite{Chen}. An integrated approach of offline computation of a number of good candidate routes using historical data, and selecting the best candidate among the pretrip identified routes using real-time data is proposed. The main motivation is to make real-time routing less expensive in terms of computation load. All of these works give examples of how traffic information can be utilized by a network user to improve it's path planning (i.e., routing) decisions. There are also some works that consider network perspectives and means of collecting information. In \cite{Guo}, collecting and aggregating real-time data from road segments and vehicles with the aid of IoT technologies is studied. In \cite{He}, it is proposed to employ large-scale social signal data to estimate travel demands, and to help travelers who experience severe congestion by proposing new routes to them. The list of references in this quick literature review is by no means exhaustive. There are also other interesting papers on dynamic routing and on collecting and utilizing traffic information to enhance the efficiency of transportation networks. As a new contribution to the literature, we consider the problem of selectively sharing traffic information with the network users. Our aim is get more insights into the utility of traffic information as a function of the percentage of network users who have access to real-time traffic information and, hence, can utilize it in dynamic routing. We assume that the central network operator (coordinator) has access to real-time traffic information and can communicate it in a selective manner to the vehicles in the network. The network operator has the objective of improving the overall network performance. To study this problem, we conducted a series of experiments using our developed large-scale traffic simulator (SmarTTS \cite{SmarTTS}). As an interesting and insightful observation, we demonstrate that sharing real-time information with all network users is sub-optimal, and it is actually better to share the information with only 50\% - 70\% of the total population to improve the overall network performance. This result is valid under the assumption that each network user decides it's route to destination locally. The rest of this paper is organized as follows. In Section~\ref{sec:setup}, we give an overview of the investigated research problem and the used simulation setup to study it. Then, in Section~\ref{sec:eval}, we discuss the main results, observations and key insights of the simulation experiments. Finally, we give some conclusions and suggested future work directions. \section{Problem Statement and Experiment Setup} \label{sec:setup} \subsection{Problem Definition} \label{sec:problem} We assume a smart transportation network environment that has access to real-time information about the traffic flow states all over the network via sensing and surveillance technologies and/or via communication with the vehicles in the roads. Additionally, we assume that the smart environment has the ability to communicate with the network users (i.e., vehicles in the roads) to support them with traffic information, if needed. The network users can get benefit from the communicated traffic information by updating their travel plans (i.e., routing decisions) locally (i.e., by themselves) to avoid traffic congestion and arrive at their destinations in the shortest possible duration. We distinguish between three possible scenarios in terms of sharing the traffic information: \begin{itemize} \item Scenario (A): No traffic information is shared at all. We assume in this case that the network users rely solely on the static geographical map of the network, and choose the routes of the {\bf shortest distance} to their intended destinations. We label this scenario as {\it static routing}. \item Scenario (B): Real-time traffic information is updated regularly over short periods of time and communicated to \underline{all} users of the network. We assume in this case that the users dynamically update their travel routes to follow the path with the {\bf shortest expected travel time}. We label this scenario as {\it dynamic routing}. \item Scenario (C): The smart environment \underline{selectively} communicates the real-time traffic information to a subset of the total population of the vehicles in the network. So, in this case, some network users will use {\it dynamic routing} to achieve the shortest expected travel time, and the others will use {\it static routing} following the shortest distance to destination. \end{itemize} Our objective is to compare the prospected performance of these three scenarios, and to get insights about the situations in which one of them becomes clearly favorable. Our performance metric is the efficiency of traffic flow all over the network. So, we choose the average travel time of all users as the performance metric that we aim to minimize. Enhancing traffic efficiency from the network perspective will certainly be reflected on enhancing the performance of the individual network users as well. We use our developed large-scale traffic simulator platform, called SmarTTS \cite{SmarTTS}, to run a series of experiments of the three scenarios that we want to investigate. The SmarTTS simulator has a number of features that are useful for our purpose. It enables us to generate network map freely, specify traffic injection rate and distribution, adjust traffic control operations (speed limits, traffic light operation, etc.) as needed, specify the information that can be communicated from the infrastructure to the vehicles, and generate detailed simulation trace file that can be used for statistical analysis. Furthermore, several vehicle mobility models, such as Intelligent Driver Model (IDM) and Krauss Car-Following Model (CFM) \cite{Kanagaraj}, are implemented in SmarTTS to mimic realistic traffic mobility. Those models deal with the vehicles propagation along the road. The lateral behavior of the vehicle in a multi-lane road is modeled using the MOBIL algorithm for lane changing \cite{Kesting}. Furthermore, a number of models are implemented to support collision avoidance behavior \cite{Kiefer, Knipling, NHTSA}. \subsection{Experiment Setup} A hypothetical Manhattan-like traffic network was simulated assuming non-uniform traffic distribution. The network consists of five horizontal (i.e., east-west) highways and five vertical (i.e., north-south) highways, as shown in Fig.~\ref{fig:Layout}. Each highway is assumed to have five lanes, and the network spans an area of 12 km by 12 km. All 25 intersections of the network are controlled by traffic lights that are actuated smartly based on the relative traffic volume in each direction of the intersection. \begin{figure} \centering \includegraphics[width=\linewidth]{./Layout.pdf} \caption{Simulated traffic network map.} \label{fig:Layout} \end{figure} For the purpose of our study, new traffic are continuously injected to the network from the entry roads on the boarders of the simulation area, which are labeled as $S_1$, $S_2$, ..., $S_{20}$ in Fig.~\ref{fig:Layout}. These are the traffic sources. Similarly, the traffic destinations are the outward directed roads at the boarders of the map, and they are labeled as $D_1$, $D_2$, ..., $D_{20}$. Traffic generation at the sources follows a Poisson process probability distribution, with traffic generation density $\lambda_{S_i}$ (in vehicles per hour) of source $S_i$ adjusted as a parameter of the simulation to control the congestion level in our experiments. The average (of all traffic sources) traffic generation density is denoted as $\lambda$ ($\lambda=\frac{1}{20}\sum_{i=1}^{20}\lambda_{S_i}$). To mimic real-traffic scenarios, we assume that the generation density of the sources varies such that traffic is injected form some entries more heavily than in other entries. Similarly, we control, as a simulation parameter, the traffic distribution matrix of the traffic flow from each source to each destination. For example, we can make a certain percentage of the vehicles injected from source $S_i$ go to destination $D_j$. We have generated a non-uniform distribution matrix for the purpose of our experiments. For example, we assumed that the traffic that is injected from $S_1$ is distributed as follows; 15\% to $D_5$, 20\% to $D_8$, 10\% to $D_{10}$, 10\% to $D_{12}$, 10\% to $D_{14}$, 15\% to $D_{15}$, 10\% to $D_{17}$, and 10\% to $D_{18}$. We simulate a two-hour operation of the transportation network, and measure the average total trip time (from source to destination), denoted $\tau_\text{avg}$ of all vehicles in the network. Travel times in the last 70 minutes of the simulation time are considered in the evaluation of the performance metric in order to make sure that the network has already reached steady state. We test the three possible routing scenarios, that were introduced in Section~\ref{sec:problem}. Whenever the experiment is repeated to test another scenario, we use the same traffic distribution matrix to make a valid comparison between the three cases. \subsection{Routing Algorithms} The routing decisions, whether they are based on shortest distance or shortest expected travel time, can be obtained by modeling the transportation network as a directed graph $G$. The graph is made up of two objects, a set $V$ whose elements are called “vertices” or “nodes” which represent all road segments in the network; and a set $E$ whose elements are called “edges”. Each edge represents a connection between two road segments. Each edge is assigned a weight $W$, which represents a cost metric for going from one road segment to another one that is connected to it at an intersection. The graph is commonly denoted as $G(V, E)$. The problem of optimal routing can be formulated as finding the shortest path (i.e., with least accumulated edges' weights) between two nodes in the graph (i.e., the source and destination node). This problem can be solved using a number of well-known search algorithms such as the {\it Dijkstra Algorithm} \cite{Dijkstra}, which we have implemented and used for our simulations. In static routing the weight of a certain edge corresponds to the travel distance between its two nodes, which is a static weight that is based on the geographic network map. On the other hand, dynamic routing calculates the weights of the edges based on the moving average time that the most recent vehicles have spent to travel between the two vertices (i.e., the time to go from the starting point of one road segment to the starting point of the next road segment including the expected waiting time at the intersection between them). This is a dynamic metric that changes over time based on the traffic congestion state on each road segments. To simulate the dynamic routing case, we assume that these weights get periodically updated every $\tau_\text{up}$ minutes, which is a simulation parameter. So, in summary, the cost metric (i.e. edges weights) in each scheme is calculated based on the following equation, \begin{equation*} W(v_i, v_j) = \left\{ \begin{matrix} D(v_i, v_j) & \text{Static routing} \\ \frac{1}{N_\text{car}}\sum_{k=1}^{N_\text{car}}\tau_k(v_i, v_j) & \text{Dynamic routing} \end{matrix} \right. \end{equation*} where $D(v_i, v_j)$ is the travel distance between vertex $v_i$ and $v_j$, and $\tau_k(v_i, v_j)$ is the travel time that the $k$th last vehicle has taken during the travel between the two vertices. In this case, only the last vehicles that moved between these two vertices are used in computing the moving average, where $N_\text{car}$ is the number of vehicles that is used in calculating the moving average. \section{Simulation Results And Discussions} \label{sec:eval} \begin{figure} \centering \includegraphics[width=\linewidth]{./5.pdf} \caption{Comparison of static routing and dynamic routing in terms of the total average travel time of all vehicles in the network over 70 minutes simulation time.} \label{fig:fifth} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{./2.pdf} \caption{Comparison of static routing and dynamic routing in terms of the moving average travel time of the vehicles in the network.} \label{fig:second} \end{figure} It is intuitive to predict that dynamic routing should be better than static routing since it exploits real-time traffic information to avoid congested roads. This is confirmed in Fig.~\ref{fig:fifth}, which compares static and dynamic routing for three different values of the average traffic generation density $\lambda$ (in vehicles per hour per source). Since we have 20 sources in our network, the total generated traffic rate in the network is 20$\times\lambda$. The results show that dynamic routing is always advantageous compared to static routing. However, the advantage becomes minimal when the traffic volume is low (such as when $\lambda = 281$). Furthermore, as shown in Fig.~\ref{fig:second}, when the traffic volume is high, dynamic routing does not only save travel time, but it does also keep the network stable, since in the case of static routing the moving average travel time keeps growing up. So, sharing real-time traffic information is vital in such cases. \begin{figure} \centering \includegraphics[width=\linewidth]{./6.pdf} \caption{Comparison of static routing, dynamic routing and selective dynamic routing, with only a percentage $\vartheta$ of the total number of vehicles follow dynamic routing.} \label{fig:sixth} \end{figure} The more interesting and insightful results are shown next in Fig.~\ref{fig:sixth} which shows the results including the scenario when only a subset of the network users (i.e., vehicles) receive real-time traffic information and utilize it in dynamic routing, and the remaining vehicles stick to shortest distance static routing. Here we assume that a percentage $\vartheta$ of the total number of network users are selected randomly to receive real-time traffic information. In this case, the overall network performance does not only improve upon the static routing scenario, but it does also improve upon the case when all vehicles perform dynamic routing. This is true given that $\vartheta$ is selected properly. For example, when only half of the total number of vehicles receive real-time traffic information, the overall performance is better than when all vehicles receive real-time traffic information. It is slightly further improved when only 70\% of the overall population receive real-time traffic updates. This is an interesting and counter-intuitive observation because it means that the utility of information is not monotonically increasing with the number of users who receive the information and utilize it locally. One might expect that static routing gives a lower bound of the performance and dynamic routing gives an upper bound, and having a mix of them will give a performance that lies between these two bounds. However, this is not true at all. Sharing information with all users such that all of them follow dynamic routing is not an upper bound. To explain these results, we should take into consideration that we assume that all routing decisions are localized at each individual vehicle, and each one of them will seek its own advantage. So, sharing information about real-time traffic will make all users in nearby of congested areas update their plans simultaneously, and hence the traffic congestion will eventually move from one place to another. On the other hand, the ignorance of some vehicles helps to achieve a more even distribution of the traffic in the network, which resolves the occurring traffic jams. It is intuitive to predict that some kind of centralized coordination, that learns the intended destinations of all users and runs a joint routing problem for all of them, would be advantageous at both individual vehicle level and at the overall network level. However, this would be a computationally expensive task that can be successfully replaced by the simpler strategy of just communicating with a subset of the users, and let them update their routes locally. \begin{figure*} \centering \includegraphics[width=\linewidth]{./4_1.pdf} \caption{Comparison between static routing users and dynamic routing users in scenarios when a percentage $\vartheta$ of users who follow dynamic routing.} \label{fig:fourth} \end{figure*} To get further insight, we differentiate in Fig.~\ref{fig:fourth} between the static routing users and the dynamic routing users in terms of total average travel time of all vehicles in the same class (i.e., static or dynamic routing). Also, the overall average is also shown for comparison. As expected, the performance of the dynamic routing users are better than the static routing users. However, it should be noted than when $\vartheta$ is 50\% or 70\%, the performance of the static-routing users does not get worse than the case when all users follow dynamic routing (i.e., $\vartheta$ is 100\%). It is only that the dynamic routing users get some extra advantage in this case relative to the all-dynamic routing scenario. It is as if the “dynamic-routing” vehicles get an extra benefit due to the “ignorance”' of the “static-routing” vehicles in this case. If all users receive real-time traffic information, then no one will receive extra performance gains. This result raises fairness concerns. If the central network coordinator wants to communicate the traffic information to a subset of the total network population with the sole goal of improving the overall network performance, some users will receive a preferential treatment. So, selecting the users to receive traffic information can be selected randomly so that everyone has the same chances of getting such preferential treatment. Having said that, it should be noted that in the case when $\vartheta=70\%$, the differences between the static-routing and dynamic-routing users become very minimal. \begin{figure*} \centering \includegraphics[width=\linewidth]{./3_2.pdf} \caption{Performance of the network users for different update rate $\tau_\text{up}$ of the network real-time information.} \label{fig:third} \end{figure*} Finally, Fig.~\ref{fig:third} show the results for different traffic information update rate $\tau_\text{up}$, of 3, 6 and 9 minutes. The timing between the real-time traffic information updates affect the frequency by which the travel plans get re-calculated in dynamic routing. The results show that having more frequent information updates is advantageous for the cases when $\vartheta=70\%$ and $\vartheta=100\%$ (i.e., all users follow dynamic routing). This is not the case for $\vartheta=10\%$ and $\vartheta=30\%$. \section{Conclusion and Future Work} \label{sec:conclusion} The key message of this work is that sharing real-time traffic information with all users of a transportation network is sub-optimal, and it is better to be selective in sharing traffic information in order to enhance the network efficiency. We have demonstrated this result via a number of simulation experiments of a large-network map. In our experiments, we assumed that traffic information are utilized locally at each vehicle to update its routing decisions dynamically. The results of this work can be further elaborated by supporting them with some theoretical foundations. In particular, we can establish a link between these observed experimental results and the concepts of ``Nash' equilibrium''and ``Pareto-Optimality'' that are discussed in game theory (e.g., \cite{Game}). We can think of the operating point of the network to be achieving a Nash equilibrium since each user would seek to achieve it's best performance, and this is far from the Pareto-optimal operating points of the network. However, the role of the network coordinator will be to selectively share information such that the Nash equilibrium becomes closer to Pareto-optimality. This theoretical framework will be elaborated in an extension of this work. Furthermore, selecting the subset of users to receive traffic information can be further investigated. It may be more efficient to choose the users based on their locations instead of communicating with the users all over the network in a completely random way. Moreover, comparing the suggested simple selective information sharing scheme with collaborative routing strategies, which are computationally expensive, would be a good continuation of this work. Finally, the shown results are relevant not only for transportation networks, but also for other network applications as well. This is because sharing information over networks is a fundamental problem that is applicable to many disciplines. \bibliographystyle{IEEEbib}
{'timestamp': '2021-03-12T02:18:38', 'yymm': '2103', 'arxiv_id': '2103.06574', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06574'}
arxiv
\section{Introduction} The ability to predict, forecast, and control disease outbreaks highly depends on the ability of disease surveillance. Compared to traditional laboratory reporting and physician reporting systems, automated case detection based on electronic medical records has much less time delay and can cover a large population. However, development of an automated case detection system may require a large training dataset for modeling, which not all regions have available. One solution is that, if region A were affected by an outbreak first, it could share its developed case detection system with region B before region B becomes significantly affected. Since both regions cover different populations that are served by healthcare institutions with different electronic medical record systems, their features and distributions for case detection could be different. These differences may not be handled well by traditional machine learning technologies, because they usually work under the assumption that the data for model development and the data for model deployment later have the same underlying distribution, an assumption that cannot hold when the training and test of the model are done at different regions/health care systems. Not only could the test data have a different set of features from the training data, but the correlation between predictive features and class variable could be different between training data and test data. Therefore, when applying a model developed with training data to the test data, the differences between them could lead to a dramatic performance drop. Transfer learning can be a potential solution. Transfer learning ~\cite{pan2009survey} offers an effective way of reusing data/model (for one task) for another task, by considering both the similarities and the differences between the two tasks. Having been successfully used for many tasks, transfer learning may be able to facilitate data/model sharing to enhance infectious disease case detection. Once region B has a few cases, transfer learning techniques could be used to adapt the case detection system from region A using the data pattern appearing in region B, thereby increasing the case detection capability for region B. This study explored the potential of deep transfer learning techniques for infectious disease case detection tasks, which aim to identify cases of infectious respiratory diseases (e.g., influenza) from emergency department visits based on their different clinical manifestations. The patients' clinical signs or symptoms have been extracted from electronic medical records using natural language processing, the use of which further increases the difference between data distributions that need to be handled by transfer learning. We compared different data-based and model-based deep transfer learning algorithms in both real world scenarios and simulated scenarios. The simulation experiments allow us to study how transfer learning generated models perform with respect to the known difference between the source and target distributions. \section{Background} Transfer learning is defined as follows : "Given a source domain $D_S$ and learning task $T_S$, a target domain $D_T$, and learning task $T_T$, transfer learning aims to help improve the learning of the target predictive function (target model) $f_{T}(.)$ in $D_T$ using the knowledge in $D_S$ and $T_S$, where $D_{S} \neq D_{T}$, or $T_S \neq T_T$.~\cite{pan2009survey}" In this definition, a domain is denoted by $D = \{X, P(X)\}$, where $X$ is the feature space, and $P(X)$ is the marginal probability distribution of features. A task is denoted by $T = \{Y, f(.)\}$, where $Y$ is the label space of the class variable, and $f(.)$ is an objective predictive function to be learned. Transfer learning has been studied in classic machine learning models, such as logistic regression~\cite{liao2005logistic}\cite{bickel2007discriminative}, SVM~\cite{jebara2004multi}\cite{evgeniou2004regularized}\cite{wu2004improving}, and Bayesian networks~\cite{schwaighofer2004learning}\cite{dai2007transferring}. Recent explorations of transfer learning mostly focus on deep neural networks~\cite{deep_transfer_learning_survey}, namely deep transfer learning. Deep transfer learning has been successfully applied in many biomedical image classification tasks~\cite{ribeiro2016exploring}\cite{kermany2018identifying} \cite{kim2018deep}\cite{mazo2018transfer} and for biomedical name entity recognition~\cite{sachan2018effective}. Deep transfer learning can be accomplished using either source data or source models. \textbf{Data-based deep transfer learning} leverages labeled source data along with labeled/unlabeled target data to learn a classifier with strong predictive ability on the target data. There exist several different approaches to using the source data. Mapping-based approaches learn a mapping of the source and target data to a new feature space in which the two are similar, as measured by some distance metric, and then train a classifier using this shared space. An example algorithm that learns the new mapping is Transfer Component Analysis (TCA)~\cite{pan2010domain}. Instance weighting approaches, like TrAdaBoost, find an appropriate weighting for some subset of the source data to be used to augment the target data~\cite{tradaboost}. This is particularly helpful when the domain data size is small. Recently, researchers have also found success in adversarial approaches, where a model is trained to be indiscriminate between the source and target data, while being discriminate for the original predictive task~\cite{deep_transfer_learning_survey}. To achieve this, the training objective combines the original classification loss with an additional loss corresponding to a domain classifier's ability to discriminate between source and target examples. Several state-of-the-art methods combine elements from these different approaches, for example by learning the shared source-target mapping through the inclusion of an adversarial domain classifier~\cite{dann}\cite{mcd}\cite{dada}. \textbf{Model-based deep transfer learning} reuses a partial network from a trained source model and tunes the remaining layers for the target domain, thereby making use of the shareable knowledge from the source~\cite{yosinski2014transferable}. For example, a recent study used a CNN trained on the ImageNet dataset (source model) plus 108,312 optical coherence tomography images (target data) to diagnose the most common blinding retinal diseases (target task)~\cite{kermany2018identifying}. Its results showed that deep transfer learning significantly increased the prediction accuracy and shortened the training time to perform the target task as compared to deep learning using the same target data without using a source model. \section{Methods} We compare a data-based deep transfer learning strategy with a model-based deep transfer learning strategy, because the latter may be more feasible for biomedical knowledge sharing across institutional boundaries. In particular, we conduct experiments in both real-world tasks and synthetic scenarios to gain insight into how the difference in the source and target distributions and the availability of target data influence transfer learning performance. \subsection{Data-Based Deep Transfer Learning} We consider two data-based transfer learning algorithms: domain adversarial neural networks (DANN)~\cite{dann} and maximum classifier discrepancy (MCD)~\cite{mcd}. We choose these two to explore because DANN represents the simplest approach to adversarial transfer learning and MCD recently achieved improvements on a few image domain adaptation tasks~\cite{mcd}. These two algorithms can conduct unsupervised transfer learning scenarios where the class labels of the target data are not available. \subsubsection{Domain Adversarial Neural Networks} The DANN approach (Figure \ref{fig:dann-workflow}) uses a single feedforward network, consisting of a feature extractor $G_f$ and label predictor $G_y$ (for the source task if no target label is available), in tandem with a domain classifier $G_d$. The loss function trades off between performing well on the source label prediction task and fooling the domain classifier, as controlled by a coefficient $\lambda$. In that way, the network learns a feature representation indiscriminate between the source and target domains while still being discriminate for the original prediction task. \begin{center} \includegraphics[width=8.5cm]{Plots/DANN.png} \captionof{figure}{DANN algorithm.} \label{fig:dann-workflow} \end{center} Formally, suppose the data is of size $N = n + n'$ where the first $n$ are from the source data and the last $n'$ are from the target data. Let $\mathcal{L}_y^i$ denote the source label prediction loss on the $i$th example and $\mathcal{L}_d^i$ denote the domain classifier loss on the $i$th example. Moreover, let $\theta_f$, $\theta_y$, and $\theta_d$ represent the parameters of $G_f$, $G_y$, and $G_d$, respectively. Then, the overall loss is given by: \begin{equation} \label{eq:dann_loss} \mathcal{L} = \frac{1}{n}\sum_{i=1}^{n}\mathcal{L}_y^i(\theta_f, \theta_y) - \lambda\left(\frac{1}{n}\sum_{i=1}^{n}\mathcal{L}_d^i(\theta_f, \theta_d) + \frac{1}{n'}\sum_{i=n+1}^{N}\mathcal{L}_d^i(\theta_f, \theta_d)\right) \end{equation} In particular, we choose $\mathcal{L}_y$ to be cross-entropy loss and $\mathcal{L}_d$ to be binary cross-entropy loss. The specific architectures for the networks $G_f$, $G_y$, and $G_d$ vary depending on the experiment. \subsubsection{Maximum Classifier Discrepancy} The MCD approach (Figure \ref{fig:MCD-workflow}) considers a feature extractor $G$ and two label predictors, $F_1$ and $F_2$. The two label predictors have the same network structure and will be trained using the same training data. The two label predictors' parameters are initiated differently, which results in different optimal parameters in the final models. The MCD approach introduces the concept of \textit{discrepancy}, which is a measure of the divergence between the probabilistic outputs of $F_1$ and $F_2$. Specifically, if there are $K$ classes, suppose $p_{i,k}$ denotes the probability of the $k$th class under $p_i$, the softmax output of $F_i$, where $k \in [K]$ and $i \in \{1,2\}$. Then, the discrepancy between $p_1$ and $p_2$ is \begin{equation} \label{eq:mcd_discrepancy} d(p_1, p_2) = \frac{1}{K}\sum_{k=1}^{K}|p_{1,k} - p_{2,k}|. \end{equation} \begin{center} \includegraphics[width=8.5cm]{Plots/MCD.png} \captionof{figure}{MCD algorithm.} \label{fig:MCD-workflow} \end{center} A single iteration of training the overall network occurs in steps, using discrepancy to optimize for the source task while generalizing to the target task. Let $(X_s, Y_s)$ denote the source data and labels, and let $X_t$ denote the target data. To begin, the source data is fed through $G$ to $F_1$ and $F_2$, optimizing the loss on the source task \begin{equation} \label{eq:mcd_step_a} \min_{G, F_1, F_2} \mathcal{L}(X_s, Y_s), \end{equation} where $\mathcal{L}(X_s, Y_s)$ is given by the summed cross-entropy loss with respect to $p_1$ and $p_2$. Then $F_1$ and $F_2$ take a step to maximize the discrepancy to improve their generalization to samples outside the source support with the objective \begin{equation} \label{eq:mcd_step_b_1} \min_{F_1, F_2} \mathcal{L}(X_s, Y_s) - \lambda \mathcal{L}_{\text{adv}}(X_t) \end{equation} where $\mathcal{L}_{\text{adv}}(X_t) = \mathbb{E}_{\mathbf{x}_t \sim X_t} [d(p_1(y \mid \mathbf{x}_t), p_2(y \mid \mathbf{x}_t))]$. \begin{comment} \begin{equation} \label{eq:mcd_step_b_2} \mathcal{L}_{\text{adv}}(X_t) = \mathbb{E}_{\mathbf{x}_t \sim X_t} [d(p_1(y \mid \mathbf{x}_t), p_2(y \mid \mathbf{x}_t))] \end{equation} \end{comment} Just as for DANN, $\lambda$ controls the weighting of the adversarial loss $\mathcal{L}_{\text{adv}}$. Finally, $G$ takes a step to minimize discrepancy to encourage learning a representation that maps target and source data to the same space; in particular, it considers the objective \begin{equation} \label{eq:mcd_step_c} \min_G \mathcal{L}_{\text{adv}}(X_t). \end{equation} After training, either $F_1$ or $F_2$ (or both) can be used for inference. \begin{comment} In practice, we include an additional class balance term \begin{equation} \label{eq:mcd_class_balance} \tau \cdot \mathbb{E}_{\mathbf{x}_t \sim X_t}\left[\sum_{k=1}^{K}(\log p_1(y = k \mid \mathbf{x}_t) + \log p_2(y = k \mid \mathbf{x}_t))\right] \end{equation} to Equations (\ref{eq:mcd_step_a}) and (\ref{eq:mcd_step_b_1}) with $\tau$ chosen to be $0.01$, following the original paper~\cite{mcd}. \end{comment} Again, the specific architectures for the networks $G$, $F_1$, and $F_2$ vary depending on the experiment. \subsection{Model-Based Deep Transfer Learning} We also consider transfer learning that adapts a source neural network model for a target setting. In particular, after training a source model, we can learn a target model (with the same architecture) by retraining parameters in three ways: (1) retrain the entire neural network, (2) freeze the first layer and retrain the remaining layers, and (3) freeze the first few layers and retrain the last layer. While each approach requires varying degrees of parameter re-tuning, all three may be feasible alternatives when the source data is not available (meaning data-based transfer learning is not applicable). \subsection{Synthetic Experiments} \label{subsec:methods_synthetic_experiments} The goal of synthetic experiments is to gain insight into the conditions under which the data-based and model-based transfer learning algorithms may perform successfully in infectious disease case detection tasks. To this end, we simulate synthetic research data, of which the joint distribution is represented using Bayesian networks. Each network realization follows an architecture defined by a single class variable $z$, which represents the diagnosis, and $n$ feature variables $\{x_i\}_{i=1}^{n}$, which represent symptoms where each $x_i$ has the sole parent $z$. For notation, let $s = |\mathcal{R}(z)|$ and $r_i = |\mathcal{R}(x_i)|$ for $1 \leq i \leq n$ where $\mathcal{R}(x)$ denotes the range of $x$. In other words, $s$ and $r_i$ give the number of different diagnoses and of different symptom levels for the $i$th symptom, respectively. Given this Bayesian network architecture, the probability tables for the target model were learned from the electronic medical records of (name of the institution) healthcare visits between January 2008 and May 2014. Training data included age groups, clinical features extracted by a medical natural language processing parser, and disease labels involving 3808 influenza visits, 6224 RSV visits, 2074 parainfluenza visits, and 2024 hMPV visits. Then, for the source models, we reuse the target model's marginal distribution for $z$ and generate the conditionals $p(x_i \mid z)$ as follows: We (1) convert the target model's conditional probabilities into log odds; (2) add random noise to the log odds where the noise follows a normal distribution $\mathcal{N}(0,\sigma^2)$; and (3) convert the log odds back to conditional probabilities. Specifically, we consider \\ $\sigma \in \{0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.5, 1.8, 2\}$. From these realized source models, we generate source training datasets of size 10,000, and from the target model, target training datasets of size 50, 100, 200, 400, 800, 2000, and 10,000 and a target test dataset of size 10,000. We (1) experiment assuming access to only source features/labels and target features for training to understand unsupervised data-based transfer learning and then (2) experiment assuming access to target labels for training as well to understand generally when transfer learning algorithms are applicable. \subsubsection{Difference in Source and Target Distributions} We explore the effect of the difference in source and target distributions on the success of the data-based transfer learning algorithms by experimenting with the synthetically simulated data. In particular, we use the KL divergence between the source distribution $p$ and target distribution $q$ as the measure of dissimilarity: \begin{equation} \label{eq:kl} KL(p, q) = \sum_{x_1, \dots, x_n, z} p(x_1, \dots, x_n, z) \log\left(\frac{p(x_1, \dots, x_n, z)}{q(x_1, \dots, x_n, z)}\right) \end{equation} Because our Bayesian network structure (for source and target distributions) is such that the diagnosis $z$ is the only parent for every symptom $x_i$, according to ~\cite{heckerman1995learning} we can rewrite the KL divergence as follows: \begin{equation} \label{eq:kl_factorized} KL(p, q) = \sum_{i=1}^{n} \sum_{j=1}^{s} \sum_{k=1}^{r_i} p(x_i = k \mid z = j) \cdot p(z = j) \log \left(\frac{p(x_i = k \mid z = j)}{q(x_i = k \mid z = j)}\right) \end{equation} Then, since $p(x_i = k \mid z = j)$ and $p(z = j)$ are given when defining the Bayesian network, Equation (\ref{eq:kl_factorized}) gives a computationally tractable form of the KL divergence. \subsubsection{Model Architectures for the Data-Based Algorithms} We prefer simple architectures for faster training for the synthetic experiments; therefore, the input data has dimension $128$, and there are $4$ possible output labels. For the DANN model, we chose the feature extractor $G_f$ to be a network with two $(128 \rightarrow 128 \rightarrow 128)$ fully-connected layers with ReLU activations, the label predictor $G_y$ to be one ($128 \rightarrow 4)$ fully-connected layer with batch-norm and ReLU activation, and the domain classifier $G_d$ to be three ($128 \rightarrow 1024 \rightarrow 1024 \rightarrow 1$) fully-connected layers with batch-norm and ReLU activations for the first two layers and sigmoid activation for the final layer. Similarly, for the MCD model, we chose the feature generator $G$ to be the same as $G_f$ and the classifiers $F_1$ and $F_2$ to be three ($128 \rightarrow 128 \rightarrow 128 \rightarrow 4$) fully-connected layers, with ReLU activation for the first two layers. The choice for $G_d$ was borrowed from the original DANN paper~\cite{dann}, and the choices for $G_f = G$, $G_y$, $F_1$, and $F_2$ were mostly arbitrary. However, empirically, we did find that increasing the hidden dimensions to be $1024$ rather than $128$ and adding an additional fully-connected layer did not provide any meaningful performance improvement, so we stayed with the smaller network architectures. Our baseline models use the same architecture as the DANN model's backbone; \textit{i.e.}\ they consist of $G_f$ composed of $G_y$. When we do not assume access to the target labels, we limit the baseline model to only the source data during training; otherwise, we train the baseline on the target data. \subsubsection{Regularizing the Adversarial Loss} \label{subsubsec:reg_lambda_dann} Recall from Equation (\ref{eq:dann_loss}) that the tradeoff between the domain adversarial loss \\ $\frac{1}{n}\sum_{i=1}^{n}\mathcal{L}_d^i(\theta_f, \theta_d) + \frac{1}{n'}\sum_{i=n+1}^{N}\mathcal{L}_d^i(\theta_f, \theta_d)$ and the source prediction loss $\frac{1}{n}\sum_{i=1}^{n}\mathcal{L}_y^i(\theta_f, \theta_d)$ is controlled by the coefficient $\lambda$. As a hyperparameter, $\lambda$ needs to be tuned, and by default, a standard choice is $\lambda = 1$. In the original paper introducing the DANN approach, Ganin \textit{et al.}\ consider $\lambda = 6$ in their toy experiments and use an increasing schedule from $\lambda = 0$ to $\lambda = 1$ in their benchmark experiments~\cite{dann}. In our synthetic experiments, since we know the KL divergence between the source and target distributions (say $p$ and $q$, respectively), we tried to incorporate that information into our choice of $\lambda$. Intuitively, when $p$ and $q$ are similar (\textit{i.e.}\ $KL(p, q) \approx 0$), it is not a priority to learn a representation indiscriminate of source and target since the two come from approximately the same distribution anyway. However, when $p$ and $q$ are dissimilar (\textit{i.e.}\ $KL(p, q) \gg 0$), it is important to force the model to extract more indiscriminate features, so we prefer penalizing the domain adversarial loss more. Na\"ively, one option is to directly choose $\lambda = KL(p, q)$. However, the KL divergence being unbounded may be undesirable, so another option is to choose \begin{equation} \label{eq:dann_lambda} \lambda = \alpha (1 - e^{- KL(p, q)}) \end{equation} where $\alpha > 0$ are selected empirically. This chooses $\lambda \approx \alpha$ for any reasonably large $KL(p, q)$ but chooses a smaller $\lambda$ when $KL(p, q)$ is close to $0$. As an example, since in the benchmark experiments of the original DANN paper, $\lambda$ was in $[0,1]$, we may choose a setting such as $\alpha = 1$. In our experiments, we try following both the na\"ive approach and Equation (\ref{eq:dann_lambda}). \subsection{Real-World Experiments} We consider two real-world tasks: (1) classifying influenza positive and negative cases and (2) classifying four respiratory disease cases (Table \ref{tab:real world tl settings}). For these tasks, we tried different fully-connected networks that differ in the number of layers and units in each layer:\\ \textbf{M1:} input $\rightarrow$ 128 units (ReLU) $\rightarrow$ \# of classes (softmax) \\ \textbf{M2:} input $\rightarrow$ 64 units (ReLU) $\rightarrow$ \# of classes (softmax) \\ \textbf{M3:} input $\rightarrow$ 64 units (ReLU) $\rightarrow$ 32 units (ReLU) $\rightarrow$ \# of classes (softmax) \\ \textbf{M4:} input $\rightarrow$ 128 units (ReLU) $\rightarrow$ 128 units (ReLU) $\rightarrow$ \# of classes (softmax) \\ \textbf{M5:} input $\rightarrow$ 128 units (ReLU) $\rightarrow$ 128 units (ReLU) $\rightarrow$ 64 units (ReLU) $\rightarrow$ \# of classes (softmax) \\ \textbf{M6:} input $\rightarrow$ 128 units (ReLU) $\rightarrow$ 64 units (ReLU) $\rightarrow$ 32 units (ReLU) $\rightarrow$ 16 units (ReLU) $\rightarrow$ \# of classes (softmax) \begin{table*} \caption{Four real-world transfer learning settings} \centering \begin{tabular}{llll} \toprule Task & Source & Target-train & Target-test \\ \midrule flu vs. non-flu & $U_{1415}$ (670, 3276) & $I_{14winter}$ (396, 1385) & $I_{15spring}$ (204, 3627) \\ flu vs. non-flu & $I_{1415}$ (600, 5012) & $U_{14winter}$ (455, 1311) & $U_{15spring}$ (215, 1965) \\ flu vs. RSV vs. parainfluenza vs. hMPV & $U_{0815}$ (2270, 1022, 261, 307) & $I_{0814}$ (3808, 6224, 2074, 2024) & $I_{1415}$ (626, 1094, 459, 235) \\ flu vs. RSV vs. parainfluenza vs. hMPV & $I_{0815}$ (4434, 7318, 2533, 2259) & $U_{0814}$ (1828, 688, 139, 202) & $U_{1415}$ (442, 334, 122, 105) \\ \bottomrule \end{tabular} \begin{tablenotes}\footnotesize \item[*] For each healthcare system (I or U), sample sizes of each diseases are provided in parentheses. \end{tablenotes} \label{tab:real world tl settings} \end{table*} \begin{table*} \caption{Comparison of six different network structures (highest value in each row is bolded)} \centering \begin{tabular}{llllllll} \toprule Train & Test & M1 & M2 & M3 & M4 & M5 & M6\\ \midrule $I_{flu-14winter}$ & $I_{flu-15spring}$ & \textbf{84.91} & 81.05 & 79.77 & 76.64 & 75.49 & 81.83\\ $U_{flu-14winter}$ & $U_{flu-15spring}$ & 88.39 & 49.40 & \textbf{89.22} & 45.73 & 46.47 & 68.67\\ $I_{4diseases-0814}$ & $I_{4diseases-1415}$ & 27.59 & 26.47 & 26.55 & 27.55 & \textbf{27.67} & 26.01 \\ $U_{4diseases-0814}$ & $U_{4diseases-1415}$ & 48.26 & 52.04 & 53.74 & 53.94 & \textbf{54.04} & 45.96 \\ \bottomrule \end{tabular} \label{tab:compare models in real world data} \end{table*} \begin{table*} \caption{Comparison of different transfer learning algorithms} \centering \begin{tabular}{lllll} \toprule Model & $U_{flu} \rightarrow I$ & $I_{flu} \rightarrow U$ & $U_{4diseases} \rightarrow I$ & $I_{4diseases} \rightarrow U$\\ \midrule network structure & M1 & M1 & M5 & M5\\ source & 94.57 & 89.95 & 29.25 & 54.44 \\ target & 84.91 & 88.39 & 27.67 & 54.04 \\ MCD & (94.68) & (\textbf{90.14}) & (33.89) & (\textbf{55.73}) \\ DANN & (\textbf{94.62}) & 87.43 & (\textbf{41.59}) & 41.67 \\ DANN-target & 86.79 & 88.76 & (29.58) & 48.35 \\ model-tune1 & 94.13 & 55.92 & 26.14 & 53.34 \\ model-tune2 & 84.99 & 53.21 & 25.97 & 53.44 \\ model-tune3 & NA & NA & 26.10 & 53.74\\ model-tune4 & NA & NA & 26.72 & 52.94\\ \bottomrule \end{tabular} \label{tab:compare tl models in 4 settings} \end{table*} We experimentally determined which of these architectures was best-suited for the two real-world tasks and used those architectures as network structures for baseline models, model-based transfer learning, and data-based transfer learning (the feature extractor). \section{Results} \subsection{Synthetic Experiments} \subsubsection{Choosing $\lambda$ for DANN} \label{subsubsec:dann_lambda} As mentioned in Section \ref{subsubsec:reg_lambda_dann}, we tried different approaches to setting the regularization parameter $\lambda$. We focused our experiments on the DANN approach since it trained faster, and we fixed our target training data size to be $400$ as a happy medium. Moreover, we considered (1) setting $\lambda \in \{1, 2, 4, 8\}$ always, (2) setting $\lambda = KL(p, q)$, and (3) setting $\lambda = \alpha (1 - e^{- KL(p,q)})$ for $\alpha \in \{1, 2, 4, 8\}$. From Figure \ref{fig:dann_lambda}, we see that, contrary to our expectations, the choice of $\lambda$ was not that impactful on the test performance for the DANN approach. There is not a visible difference in setting $\lambda$ to a fixed constant, to the KL divergence itself, or to some (exponentially) increasing function of the KL divergence. Moreover, choosing a suitable magnitude of $\lambda$ does not appear to depend much on the dissimilarity between the source and target distributions. \subsubsection{Varying KL Divergence and Target Data Size for DANN \& MCD} \label{subsubsec:varying_kl_target_data_size} Because the results of our experiments in Section \ref{subsubsec:dann_lambda} showed that the choice of $\lambda$ did not appear to be too instrumental to the model performance, for simplicity, we fixed $\lambda = 1$ for both the DANN and the MCD approaches on the synthetic data. Then we considered the effect of the difference in source and target distributions, as measured by the KL divergence given in Equation (\ref{eq:kl_factorized}) and the effect of different target training data sizes. Specifically, we considered all $14$ settings of $\sigma$ for the source models to achieve a range of KL divergences, and we tried all target training data sizes mentioned in Section \ref{subsec:methods_synthetic_experiments}. Figures show the test performance of the DANN (Figure \ref{fig:dann_acc_vs_kl}) and MCD (Figure \ref{fig:mcd_acc_vs_kl}) approaches, respectively, compared against the baseline (source model). We see that the DANN approach achieves meaningful transfer for target training data sizes of at least $200$. The MCD approach sees slightly worse performance, but it still beats the baseline for target training sizes of at least $400$. Overall, we see that the transfer learning algorithms work to reduce the accuracy drop when working with a target distribution dissimilar from the source distribution but are unable to fully mitigate the difference. Notably though, we did not expect the MCD approach to be outclassed by the simpler DANN approach, which also took less time to train. \subsubsection{When Is Transfer Learning Useful?} Next, to assess the usefulness of transfer learning in general, we broadened our scope to compare the data-based transfer learning approaches with model-based transfer learning approaches and baseline methods (source model and target model) on the synthetic data. Across the different plots (Figure \ref{fig:target50},\ref{fig:target100},\ref{fig:target200},\ref{fig:target400},\ref{fig:target800},\ref{fig:target2000},\ref{fig:target10000}), we vary the amount of target training data available. \textbf{Target model curve vs. transfer learning model curves:} The target model was developed using the target training data only (\textit{i.e.}\ without source data). The target curve (in cyan) is a straight line in each subplot since we use the same target training dataset each time. We see that with a sample size of at most $800$ (\textit{i.e.}\ from Figure \ref{fig:target50},\ref{fig:target100},\ref{fig:target200},\ref{fig:target400},\ref{fig:target800}), the target model curve is lower than a transfer learning model's curve. Moreover, the benefit of transfer learning depends on the similarity between the source and target domains. When the target size is $50$, the KL divergence should be at most $3$ in order to have benefits of the source information, and when the target size is $\geq 100$, the KL divergence should be at most $0.5$. However, we emphasize that the target model requires target labels, which we may not have; in such a case, we can still use the DANN and MCD methods to outclass the baseline trained only on source data. \textbf{Source model curve vs. transfer learning model curves:} This comparison reiterates the results from Section \ref{subsubsec:varying_kl_target_data_size}. We refer to the baselines trained only on the source data as the source model (whose curve is in grey). Again, our experiments show that the transfer learning models perform much better than the source models when the KL divergence is greater than $1$. Moreover, the advantage is more obvious for larger divergences. Thus, we see that data-based transfer learning is very useful when the two domains are not very similar and the target domain does not have labeled training data. \textbf{DANN target vs. DANN vs. MCD:} When the KL divergence is greater than 3, the DANN approach with access to the target labels performs significantly better than the normal DANN approach, and the normal DANN approach performs better than the MCD approach. \textbf{Model-tune3 vs. model-tune2 vs. model-tune1:} The numeric suffix denotes the number of layers tuned (following the model-based approach). We see that when the target training data size is sufficient, tuning more layers works better, especially if the KL divergence is large. \textbf{Model-based vs data-based:} When the KL divergence is large, the fully-tuned models perform better than the data-based models on the synthetic data. When the KL divergence is small and target training data is insufficient, data-based models perform similarly to model-based models. \subsection{Real-World Experiments} \subsubsection{Model Architecture Search} Table \ref{tab:compare models in real world data} shows that, for the flu classification tasks (rows 1-2), a simple one-hidden layer (128 units) network, M1, performs relatively well. This indicates that the flu classification task only needs a simple model. In contrast, for the four-disease classification tasks (rows 3-4), a three-layer network, M5, performs the best, indicating that a deeper network may be better for more complicated tasks. Thus, we use M1 for further experiments related to the flu classification tasks and M5 for further experiments related to the four-disease classification tasks in Section \ref{subsubsec:models for real world}. \subsubsection{Compare transfer learning algorithms} \label{subsubsec:models for real world} For the four settings in Table \ref{tab:real world tl settings}, Table \ref{tab:compare tl models in 4 settings} lists the performance of the different models for the four settings in Table 1. The highest value per row is bolded and model accuracy values greater than those of both the source and target models are in parentheses. Interestingly, the source models all performed better than the target models. The source training datasets combine the source institution's visits in historical seasons and the most recent season, while the target training datasets contain the target institution's visits in historical seasons and have a smaller sample size in all settings except the third. Results for this experiment show that transfer learning may be useful for infectious disease classification tasks. Although the accuracy gains for transfer learning in setting 1, 2, and 4 were not significant, in the third setting, transfer learning models clearly outperformed just training on the source data or target data. In all four of the settings, the data-based transfer learning models (MCD or DANN) always performed the best (bold in each column). The MCD model performed the best when sharing from I to U, and the DANN model performed the best when sharing from U to I. Contrary to expectations, tuning the models (the last four rows) resulted in a performance worse than that of the source models. For settings 3 and 4, one possible explanation is that there is a relatively significant domain shift in the joint distribution $P(\text{findings}, \text{disease})$ from the historical seasons (target training data) to the most recent season (target test data). The domain shift in the marginal $P(\text{findings})$ may be relatively small, allowing data-based methods use the unlabeled target data to perform better than the source models. For settings 1 and 2, unfortunately, we do not have any good explanation as to why using the target training data to tune the source models resulted in reduced performance (especially the dramatic drops in setting 2). In fact, in these two settings, the target training dataset and the test dataset were from the first half and the second half of one season in the same institute respectively and thus were expected to have much less domain shift. \section{Discussion} \subsection{Synthetic Experiments} Both of the data-based transfer learning algorithms that we explored, DANN and MCD, were originally proposed in the context of images~\cite{dann}\cite{mcd}, while here, we applied the techniques to infectious disease classification. Notably, the features considered in the synthetic experiments were all categorical corresponding to symptoms as opposed to the spatially-structured pixels that comprise an image. To accommodate this difference, we replaced convolutional layers with fully-connected layers in the suggested architectures. Perhaps, this substitution hindered the performance of the transfer-learning approaches. While we experimented with one-step changes such as increasing the hidden dimensions or adding additional layers, we did not thoroughly investigate more sophisticated changes such as incorporating varying levels of dropout or employing more complex layer architectures. Still, since the goal of the synthetic experiments was to understand general trends and relationships, the absolute test accuracy was not the focus. Rather, from our exploration, we found that the coefficient $\lambda$ controlling the relative weighting of the adversarial loss was not impactful in the DANN algorithm, suggesting that there may not be a need to tune it precisely. Furthermore, we evidenced that transfer learning does have its place in this infectious disease context, as it was able to reduce the performance drop when predicting on increasingly dissimilar target domains. This observation partially motivated our further investigation on the real-world data. We also saw success with the model-based approach. In particular, we saw that tuning more layers was important when the KL divergence between the source and target distributions was large. Hence, in general in the synthetic setting, we learned that we should not limit ourselves to only retraining one or two layers if possible. As such, we can view the entire source model simply as a warm start that provides a more favorable initialization for the model meant for the target task. \subsection{Real-World Data Experiments} Our real-world data experiments demonstrated that data-based transfer learning, especially the MCD approach, may develop a model that performs better than both a source model and a target model. However, model-based transfer learning did not further improve the performance of a source model that was set as a warm start. We hypothesize that this result is due to the domain shift in the joint distribution of clinical findings and disease between the target training data and the target test data. As mentioned earlier, the training data was older, while the test data came from the most recent season. This shift did not exist for the synthetic experiments since in that case the training and test data were randomly generated from the same distribution, so we did not see such a drop in performance. Hence, in the future, we must also account for temporal differences in the training and test data as a part of the domain shift. In other words, if we apply a transfer learning method, we should consider the shift between source and target domains as well as within the target domain over time. \section{Conclusion} To conclude, in the context of infectious disease classification, transfer learning may be useful when (1) the source and target are similar and the target training data is insufficient and (2) the target training data does not have labels. We saw that model-based transfer learning works well in the first situation, where case the performance closely matched that of the data-based transfer learning models. However, further investigation is needed to understand the drop in performance that model-based transfer learning experiences from the domain shift in real world research. \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/dann_lambda.png} \captionof{figure}{DANN test accuracy with different settings of $\lambda$.} \label{fig:dann_lambda} \end{center} \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/dann_acc_vs_kl.png} \captionof{figure}{DANN: test accuracy with different target training data sizes.} \label{fig:dann_acc_vs_kl} \end{center} \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/mcd_acc_vs_kl.png} \captionof{figure}{MCD: test accuracy with different target training data sizes.} \label{fig:mcd_acc_vs_kl} \end{center} \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/target50_acc_vs_kl_v2.png} \captionof{figure}{Comparisons of model performance (target sample size = 50).} \label{fig:target50} \end{center} \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/target100_acc_vs_kl_v2.png} \captionof{figure}{Comparisons of model performance (target sample size = 100).} \label{fig:target100} \end{center} \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/target200_acc_vs_kl_v2.png} \captionof{figure}{Comparisons of model performance (target sample size = 200).} \label{fig:target200} \end{center} \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/target400_acc_vs_kl.png} \captionof{figure}{Comparisons of model performance (target sample size = 400).} \label{fig:target400} \end{center} \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/target800_acc_vs_kl.png} \captionof{figure}{Comparisons of model performance (target sample size = 800).} \label{fig:target800} \end{center} \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/target2000_acc_vs_kl.png} \captionof{figure}{Comparisons of model performance (target sample size = 2000).} \label{fig:target2000} \end{center} \begin{center} \includegraphics[width=9cm]{Plots/Synthetic Experiments/target10000_acc_vs_kl.png} \captionof{figure}{Comparisons of model performance (target sample size = 10000).} \label{fig:target10000} \end{center} \section*{IRB Information} The research data was collected through PRO13030471 and study LM011370. \section*{Acknowledgments} Dr. Ye Ye was supported by NIH NLM K99LM013383 grant, under the guidance of Drs. Michael Becich, Gregory Cooper, Michael Wagner, and Heng Huang. We would like to thank our collaborators, Drs. Jeffery Ferraro, Peter Haug, and Per Gesteland from Intermountain Healthcare, for providing research data. We would like to thank Jonathon Byrd and Drs. Ruslan Salakhutdinov, Andrej Risteski for research advice. Starter code for the data-based and model-based transfer learning algorithms was taken from~\cite{dalib}. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-03-12T02:25:37', 'yymm': '2103', 'arxiv_id': '2103.06710', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06710'}
arxiv
\section{Introduction} With the further development of computing power's marginalization, the traffic from the end devices (EDs) has increased dramatically. However, due to the limited resources and computing performance, the EDs may face insufficient capabilities when processing computation-intensive and time-sensitive applications. To solve the problem mentioned above, computation offloading allocates tasks with a large amount of computing requirements to a server with sufficient computing resources to process and retrieve the results. Computation offloading in cloud computing transfers tasks to remote cloud servers for execution and uses its computing and storage resources to alleviate computing and storage limitations and extend the EDs battery life \cite{b1}, while offloading tasks to cloud servers face problems such as unpredictable delays and long transmission distances \cite{b2}. Unlike cloud computing, edge computing that uses servers to process and analyze data has emerged and is complementary to traditional cloud computing \cite{b3}, which provides cloud computing functions at the edge of the wireless access network near mobile users, providing computing services for EDs more quickly and efficiently while alleviating the pressure on the core network \cite{b4}. From the perspective of computing, offloading can significantly shorten the tasks' execution delay and reduce energy consumption in local computing. In contrast, from the perspective of communication, the upload of data and feedback of the results introduce additional time and energy consumption \cite{b5}. To solve the deficiencies of EDs in resource storage, computing performance, and energy efficiency, offloading the task of EDs to cloud servers and edge servers has become the mainstream direction of computation offloading. As the dependencies between tasks become more complex, it is more general to abstract them as Directed Acyclic Graph (DAG). On the premise of not violating mutual dependence, tasks in DAG applications can be executed in parallel in cloud servers and edge servers \cite{b6}. Considering different application scenarios and requirements, researchers have researched the decision-making problem of offloading. From the perspective of minimizing delay or energy consumption, many existing solutions propose corresponding models for offloading based on mathematical models, and solve NP-hard problems based on heuristic or approximate algorithms \cite{b7,b8}. However, these solutions rely heavily on accurate mathematical models. Therefore, it is difficult for one specific algorithm to fully adapt to the dynamic scenarios from the increasing complexity of applications.If the dynamic arrival of tasks, random changes in task attributes, user movement, and dynamic changes of wireless channels are not considered, the offloading decision process can be abstracted as a Markov Decision Process (MDP) and requires a State Transition Probability Matrix (STPM) to describe the system state's change probability under different offloading decisions \cite{b9}. After that, the optimal offloading decision can be obtained through value iteration or policy iteration. As the STPM is difficult to obtain, the optimal policy can be learned by using Reinforcement Learning (RL) methods through continuous interaction. RL is a branch of machine learning used to learn the optimal policy when there is no information about the surrounding environment \cite{b10,b11,b12}. It can directly predict the new state and action reward based on the model without interacting with the environment. In terms of update methods, MDP-Based RL can be divided into two categories by focusing on policy or value. The Value-Based RL outputs the action's value, and chooses the action with the highest value, while the Policy-Based RL outputs the probability of the next action, and selects actions based on the probability \cite{b13}. The optimal transport (OT) focuses on solving the optimal transport scheme between two different distributions, and its distance optimization problem is highly similar to the offloading problem that we need to solve, which is transferring tasks from EDs to computation nodes providing computing services \cite{b14}. We formulate joint optimization as an MDP problem and develop an Optimal-Transport-Based RL approach to solve it \cite{b15}. It is based on a Policy-Based RL to obtain a weighted sum that minimizes the processing delay of all tasks and end devices' energy consumption. Fusing the RL and the regularized annealing scheduling learning policy in the optimal transport can adaptively adjust the policy space during the RL exploration, thereby making the training process more stable. The contributions of this paper are as follows: \begin{itemize} \item We propose a collaborative computation offloading model considering both delay and energy consumption, which can effectively utilize the computing resources among cloud servers and edge servers, and we formulate it as an optimization problem. \item To speed up the convergence, we introduce optimal transport into the exploration of Policy-Based RL and propose an Optimal-Transport-Based RL approach and construct a corresponding hybrid algorithm to solve the multi-objective optimization problem. \item We evaluate the performance of the proposed approach compared to other three baselines, and simulation results show that the proposed approach significantly reduces delay and energy consumption. \end{itemize} The remainder of this paper is organized as follows. The system model is presented in Section \uppercase\expandafter{\romannumeral2}. In Section \uppercase\expandafter{\romannumeral3}, we describe the problem formulation for computation offloading. In section \uppercase\expandafter{\romannumeral4}, we propose the Optimal-Transport-Based RL approach to solve our proposed problem. The proposed approach's performance is evaluated and analyzed by simulation experiments in Section \uppercase\expandafter{\romannumeral5}. Finally, in Section \uppercase\expandafter{\romannumeral6}, we conclude this paper. \section{System Model} As illustrated in Fig. 1, we consider a wireless powered cloud-edge-end network, including EDs and computation nodes containing cloud servers and edge servers. In our computation offloading model, EDs can upload their tasks to the computation nodes for processing. Let $t_{i}= c_{i},s_{i}$ represents the task from EDs, where $c_{i}$ represents the number of CPU cycles required to complete the task, and $s_{i}$ represents the input data size of the task. We use $d_{i}={-1,0,1}$ to represent the offloading method of tasks, $d_{i}=-1$ means processing tasks on EDs, $d_{i}=0$ means that the task is offloaded by the edge base station to a nearby edge server for processing, and $d_{i}=1$ means that the task is offloaded to the cloud server for processing. \begin{figure}[htbp] \centering \includegraphics[height=7.5cm,width=7.5cm]{Visio-OT-RL-1} \caption{Collaborative Computation Offloading Model.} \end{figure} \subsection{Communication Model} We assume that the channel state between EDs and base stations (BS) containing Small-Cell BS or Macro-Cell BS in the computation offloading model varies with time, that is, the channel state is different in each time slot. There is only one eNB in one BS, so the interval interference is neglected. It’s assumed that if multiple applications choose to offload the task simultaneously, the wireless bandwidth would be equally allocated to the offloading EDs for uploading data. If the user chooses the BS to execution task, the uplink communications are serving multiple users. Let ${R^\mu }$ denotes the channels’ upload rate of the wireless network channel and can be obtained by: \begin{equation} {R^\mu } = W{\log _2}(1 + \frac{{{P^\mu }G}}{{WV}}), \end{equation} where $W$ is the wireless channel bandwidth, ${{P^\mu }}$ is the transmission power of the end device to upload data, $G$is the Channel gain of the wireless channel allocated to the end device by the BS, and $V$ is the variance of the channel with Additive White Gaussian Noise. \subsection{Delay and Energy Consumption Model} In our work, different offloading methods correspond to different delays and energy consumption. Specifically, when EDs offloading tasks, the delay refers to the sum of the transmission time of offloading data to the computation node, the execution processing time at the computation node, and the transmission time of receiving the data result processed by the computation node, and the energy consumption refers to the sum of the transmission energy consumption of offloading data to the computation node and the transmission energy consumption of receiving the data result processed by the computation node. \paragraph{Local Computing} When a task is offloaded for processing locally, we denote the local computing delay of task $t_i$ as $T_i^{local}$, and only relate to the computing capability ${{f^{end}}}$ and the required CPU-cycle frequency ${{c_i}}$. Therefore, the local computing delay can be obtained by: \begin{equation} T_i^{local} = \frac{{{c_i}}}{{{f^{end}}}}. \end{equation} Let ${P^c}$ denotes the computing power, and the energy consumption for task is denoted by $E_i^{local}$ and is defined as: \begin{equation} E_i^{local}{\text{ = }}{P^c}\frac{{{c_i}}}{{{f^{end}}}}. \end{equation} \paragraph{Edge Computing} For the edge computing method, the EDs can offload the task to the edge server through wireless connection between EDs and Small-Cell BS. In addition, edge computing needs to upload the required data to the edge server. The execution time of task on the edge server is given by: \begin{equation} T_i^{edge} = \frac{{{s_i}}}{{{R^{u}}}} + \frac{{{c_i}}}{{{f^{edge}}}}, \end{equation} where ${{f^{edge}}}$ stands for the computing capability of the edge server. Let ${P^u}$ denotes the upload power, and ${P^{idle}}$ denotes the idle power. To sum up, the energy consumption can be obtained by: \begin{equation} E_i^{edge} = {P^u}\frac{{{s_i}}}{{{R^u}}}{\text{ + }}{P^{idle}}\frac{{{c_i}}}{{{f^{edge}}}}. \end{equation} \paragraph{Cloud Computing} In the case of offloading tasks to cloud servers, the processing delay can be divided into three aspects, including the transmission delay of the wireless channel, the transmission delay of the base station to the cloud servers, and the computational delay when the cloud server processes the task. Thus, the total cloud computing delay for task $T_i^{cloud}$ is as follows: \begin{equation} T_i^{cloud} = \frac{{{s_i}}}{{{R^{u}}}} + \frac{{{s_i}}}{{{R^{trans}}}} + \frac{{{c_i}}}{{{f^{cloud}}}}, \end{equation} where ${{f^{cloud}}}$ stands for the computing capability of the cloud server, and ${{R^{trans}}}$ is the transmission rate of the Small-Cell BS through the core network to cloud servers. To offload tasks to cloud servers, there is no processing energy consumption on EDs, but the transfer energy consumption of the data upload and the idle energy consumption of EDs need to be considered. Then, the total energy consumption of cloud computing can be calculated by: \begin{equation} E_i^{cloud} = {P^{u}}\frac{{{s_i}}}{{{R^{u}}}}{\text{ + }}{P^{idle}}(\frac{{{s_i}}}{{{R^{trans}}}} + \frac{{{c_i}}}{{{f^{cloud}}}}). \end{equation} \section{Problem Formulation} Based on the system model in the above section, our objective is to minimize the overall cost of delay and energy consumption of all tasks by optimally choosing an offloading policy. We transform the original offloading problem into solving the optimization problem of the optimal transport scheme. We define $C(\alpha ,\beta )$ as the objective cost function, where $\alpha {\text{ = }}\sum\nolimits_{i = 1}^N {{a_i}{\delta _x}_{_i}}$ denotes a discrete probability measurement of the task to be offloaded by the end device, and $\beta {\text{ = }}\sum\nolimits_{i = 1}^N {{b_i}{\delta _x}_{_i}}$ denotes another discrete probability measure for tasks that has already been processed \cite{b16}. According to the definition of Monge-Kantorovich transport problem, the optimization problem is formulated as follows: \begin{equation} \begin{split} &\min \,\, C(\alpha ,\beta )=\mathop {\min }\limits_T \int_M c(x,y)d\gamma(x,y)\\ &s.t.\quad \left\{\begin{array}{lc} C1:a = (1,0, \cdots 0) \in {R^N}\\ C2:b = (0,{b_2}, \cdots ,{b_N}) \in {R^N}\\ C3:{T_\# }\alpha = \sum\limits_{i = 1}^N {{a_i}{\delta _{{T^{ - 1}}({x_i})}} = \beta }\\ C4:\sum\limits_{i = 1}^N {{b_i} = 1} \end{array}\right. \end{split} \end{equation} In (8), $C(\alpha ,\beta )$ represents the transmission distance, i.e. the delay and energy consumption that comes with offloading. $\gamma(x,y)$ stands for the computing power of three different compute nodes. Constraints C1 and C2 define the vectors a and b that make up the discrete probability measurement $\alpha$ and $\beta$. Constraints C3 enforce that the tasks assigned to each compute node are consistent with the tasks waiting to be offloaded and the matrix transformation $T$ represents a many-to-many mapping of offloading decision, and C4 means that a task can only be processed by one compute node. \section{Proposed Solution} In the above section, we formulate the optimization problem to optimize offloading performance. This section utilizes the Optimal-Transport-Based RL approach to design the corresponding algorithm and address the formulated optimization problem. \subsection{Optimal Transport} When faced with large-scale offloading, solving how to map multiple tasks from one space to another simultaneously, rather than just thinking about one task, is the sticking point to OT. Problem (8) is challenging to solve because constraint C3 is not linear, and Kantorovich Relaxation can relax the original constraint, allowing multiple tasks to be offloaded to multiple servers \cite{b14,b16}. Since the convex optimization problems are always paired, the convex maximization Problem (9) corresponding to the convex minimization Problem (8) is given as follows: \begin{equation} \min C(\alpha ,\beta ){\text{ = }}\mathop {\max }\limits_f \int_M {f(x)} d\alpha (x) + \int_M {{f^c}(y)d\beta (y)}, \end{equation} and the corresponding meaning of Problem (9) is to maximize the total number of tasks that can be offloaded simultaneously by changing the overall cost of delay and energy consumption. Let $c(x,y) = d(x,y) = ||x - y|{|_2}$ , then, Problem (10) is the dual problem of Problem (9) and can be solved by convex optimization method \cite{b17}. \begin{equation} \begin{split} &\min C(\alpha ,\beta ) = \mathop {\min }\limits_s\int_M{||s(x)|{|_2}dx},\\ &s.t.\quad \nabla \cdot s(x) = \alpha (x) - \beta (x). \end{split} \end{equation} \subsection{RL for Computation Offloading} OT is suitable for offline environments. For real-time systems that need to obtain real-time computing resources, offline offloading will bring an unbearable burden. RL methods can provide online updating and are widely used in offloading scheme, and the research emphasis of computation offloading based on RL is the learning of offloading policy. Specifically, first, observe its current state ${s_t}$, then take action ${a_t}$, and get its practical information, namely the immediate reward ${r_t}$ and new state ${s_{t + 1}}$, will be used to adjust the offloading policy and this process will be repeated until the policy is close to the optimal policy. When the Policy-Based RL is used to approximate the offloading policy, it can be described as a policy function containing learning parameters $\theta$ \cite{b18}. \begin{equation} {\pi _\theta }(s,a) = P(a|s,\theta ) \approx \pi (a|s) \end{equation} To maximize the long-term cumulative reward, the reward value ${r_i}$ can be defined as the cumulative reward after the current moment. \begin{equation} {r_i} = R(s,a) = {\gamma _a}\frac{{{T^{local}} - {T^{off}}}}{{{T^{local}}}} + {\gamma _b}\frac{{{E^{local}} - {E^{off}}}}{{{E^{local}}}} \end{equation} where ${{T^{local}}}$ and ${{E^{local}}}$ indicate the delay and energy consumption of directly processing locally. ${{T^{off}}}$ and ${{E^{off}}}$ indicate the delay and energy consumption of offloading. ${\gamma _a}$ and ${\gamma _b}$ denotes the value range of weight factors which balance the delay and the energy consumption and avoid the infinite total reward when the time is too long. Furthermore, in order to evaluate the expected reward of the offloading policy, we define the expected reward obtained after performing an offloading action a under the state s as the State-Action Value function and is expressed as: \begin{equation} {Q_\pi }(s,a) = {\mathbb{E}_\pi }[\sum\limits_{k = 0}^\infty {{\gamma ^k}{r_{t + k}}} |{S_t} = s,{A_t} = a]. \end{equation} After expressing the offloading policy as a continuous function, the optimization methods of continuous function such as the gradient ascent can be used to find the optimal policy. This requires an objective function that can be optimized, which is represented by the average reward for each step as: \begin{equation} {J_{avR}}(\theta ) = \sum\nolimits_s {{d_{{\pi _\theta }}}(s)} \sum\nolimits_a {{\pi _\theta }(s,a)R(s,a)}, \end{equation} and the gradient of the derivative of (14) with respect to $\theta$ can be expressed as: \begin{equation} {\nabla _\theta }L(\theta ) = \mathbb{E}{\pi _\theta }[{\nabla _\theta }\log {\pi _\theta }(s,a){Q_\pi }(s,a)]. \end{equation} Here, based on the Softmax function \cite{b19}, the policy function ${\pi _\theta }(s,a)$ uses the linear combination of the characteristics describing the state $s$, action $a$ and the parameter $\theta $ to weigh the probability of next action is expressed as follows: \begin{equation} {\pi _\theta }(s,a) = \frac{{{e^{\phi {{(s,a)}^T}\theta }}}}{{\sum\nolimits_b {{e^{\phi {{(s,b)}^T}\theta }}} }}. \end{equation} \subsection{Optimal-Transport-Based RL} In the above subsections, we use OT and RL to solve offline offloading and online updating, respectively. We combine OT and Policy-Based RL to propose an Optimal-Transport-Based RL (OTRL) approach, where OT is conducive to training a stable model, and RL explore the best offloading policy in the continuous learning process. The joint loss function ${L_{OTRL}}$ is written as: \begin{equation} {L_{OTRL}} = {\lambda _1}C(\alpha ,\beta ) + {\lambda _2}{J_{avR}}(\theta ). \end{equation} and the process can be divided into the following aspects: \begin{itemize} \item Offline training: The unique offloading decision obtained by solving cost function $C(\alpha ,\beta )$ under given computing resources and tasks can train the offline model. \item RL exploration: RL acquires real-time computing and communication resources through continuous interaction and gradually expands the exploration space by introducing the Policy-Based RL objective function ${J_{avR}}(\theta )$. \item OT fine-tune: We add cost function $C(\alpha ,\beta )$ again into the iterative process of RL to fine-tune the model and accelerate the convergence of the model. \end{itemize} In addition, we can gradually increase or decrease ${\lambda _1}$ and ${\lambda _2}$ to achieve parameter annealing when training the offloading model. The OTRL algorithm for computation offloading is shown in Algorithm 1. \begin{algorithm}[H] \caption{OTRL for Computation Offloading} \hspace*{0.02in} {\bf Input:} task probabilities $\alpha$ and $\beta$, parameters ${\lambda _1}$ and ${\lambda _2}$\\ \hspace*{0.02in} {\bf Output:} offloading model M and offloading policy $\theta $ \begin{algorithmic}[1] \FOR{each $iteration \in [1,MaxIter]$} \STATE $\lambda_{1}^{'},\lambda_{2}^{'} = AnnealingScheme({\lambda _1},{\lambda _2})$ \FOR{each $i \in [1,N]$} \STATE $\alpha {\text{ = }}\sum\nolimits_{i = 1}^N {{a_i}{\delta _x}_{_i}}$, $\beta {\text{ = }}\sum\nolimits_{i = 1}^N {{b_i}{\delta _x}_{_i}}$ \STATE $D_{i}^{'} = M({a_i},\theta )$ $//$Explore offloading policy \STATE ${r_i} = R(D_{i}^{'})$ $//$Compute cumulative reward \STATE $//$ Convert model outputs to offloading policy \STATE $\theta = \arg \max [soft\max ({r_i})]$\ \STATE ${b_i} = D_{i}^{'}$${a_i}\delta _{{x_i}}^T$\ $//$Computing nodes \ENDFOR \STATE $\theta ' = \arg \max [soft\max (C(\alpha ,\beta ))]$ $//$Optimal policy \STATE $//$ Update offloading model \STATE $\sum\nolimits_{i = 1}^m {[\lambda_{1}^{'}C(\alpha ,\beta ) + \lambda_{2}^{'}{J_{avR}}(\theta ,\theta ')]}$ \ENDFOR \RETURN result \end{algorithmic} \end{algorithm} \section{Simulation Experiments} In this section, we verify the offloading performance of the Optimal-Transport-Based RL approach. \subsection{Simulation Settings} In simulation, we assume that the computation capacity of the end device, edge server, and cloud server are set to 1GHz, 10GHz, and 100GHz, respectively. The wireless channel bandwidth is 50MHz, the number of channels is 50, the number of the end device is 100, and they are randomly distributed within the coverage of multiple base station. The wireless transmission power is 0.1W, the computation power of the end device is 0.5W, and the Additive White Gaussian Noise is -100dBm. The number of CPU cycles required by the edge server and cloud server are 200 cycles/bit and 50 cycles/bit. Moreover, we assume that the data size of tasks obeys a uniform distribution between [100,500]. On the basis of the above experimental parameter settings, we compare the proposed OTRL algorithm with the following three latest benchmark algorithms: \begin{itemize} \item DDPG algorithm: DDPG is a deep reinforcement learning technique adopted to achieve the optimal solution of the complicated nonlinear optimization problem \cite{b20}. \item Greedy algorithm: For each task, a greedy strategy is used to decide to execute a task at its EDs or offload it to servers for processing to minimize the delay. \item Random algorithm: Without violating the original task dependencies, the performance of other offloading algorithms should be at least higher than this benchmark algorithm. \end{itemize} \subsection{Simulation Results and Analysis} The experiment first verifies the convergence performance of the proposed OTRL algorithm in the offline training, and we take the loss function to highlight the convergence performance. As shown in Fig. 2, during the 50 rounds of training, it can be seen from the fitting curve that the value of loss function in two RL algorithms decreases rapidly. When the number of training reaches 30, the joint loss function ${L_{OTRL}}$ tends to be stable. With the help of both OT and RL, it can be seen that the proposed OTRL algorithm converges fast and is more stable than DDPG algorithm. \begin{figure}[htbp] \centering \includegraphics[height=6.60631cm,width=8cm]{2-1.pdf} \caption{Convergence curve of loss vs number of iterations.} \end{figure} Next, we consider how the the required data size during offloading impacts the offloading performance. Fig.3 shows the average cost under scenarios where the required data ranges from 100 KB to 1000 KB. In particular, the average cost of the Greedy algorithm and the Random algorithm increase relatively fast as the data size increases, while the average cost of the proposed OTRL algorithm increases relatively slowly. The figure shows that the proposed OTRL algorithm and the DDPG algorithm outperforms the other two benchmark algorithms because the increasing data leads to a more extensive search space for RL methods to obtain an optimal policy. \begin{figure}[htbp] \centering \includegraphics[height=6.60631cm,width=8cm]{3-1.pdf} \caption{Average cost under different data size.} \end{figure} As shown in Figs. 4, we consider the impact of different required CPU cycles to process the tasks, and the required CPU cycles for processing tasks ranges from 10 Gcycles to 20 Gcycles. Except for the Random algorithm and the Greedy algorithm, we can note that the average cost of the other two methods are relatively stable as the required CPU cycles change, which means they can adapt to different required resources dynamically. Furthermore, the proposed OTRL algorithm shows no clear sign of increasing. This is because the proposed algorithm can make intelligent offloading decisions to reduce the overall cost of delay and energy consumption. \begin{figure}[htbp] \centering \includegraphics[height=6.60631cm,width=8cm]{4-1.pdf} \caption{Average cost under different required CPU cycles.} \end{figure} In the previous two simulations, we obtained different average cost by changing task attributes containing data size and required CPU cycles. After standardized the input of the above two factors, we consider how the number of EDs impacts the offloading ratio. Fig. 5 shows the variation of offloading ratio as number of EDs change. We can observe that offloading ratios decreases with the increasing EDs and the OTRL algorithm outperforms the other three benchmark algorithms. What makes this phenomenon is that the OTRL algorithm can make full use of the collaborative resources of cloud servers and edge servers. \begin{figure}[htbp] \centering \includegraphics[height=6.60631cm,width=8cm]{5-1.pdf} \caption{Offloading ratio under different numbers of EDs.} \end{figure} \section{Conclusion} In this paper, we have studied the problem of computation offloading in cloud and edge computing, where multiple EDs have computation-intensive and time-sensitive tasks that need to be executed either locally or remotely. Considering the situation that EDs can offload tasks to edge stations, and edge stations can further offload tasks to nearby edge server or cloud server. The problem is formulated as the joint optimization of delay and energy consumption. To solve the formulated multi-objective optimization problem, we have proposed an Optimal-Transport-Based RL (OTRL) approach to find a solution for the intractable problem. Simulation results have demonstrated that the proposed approach can achieve a better trade-off performance on delay and energy consumption than other computation offloading schemes and decrease the complexity compared to the conventional RL methods. \section*{Acknowledgment} This work was supported by the National Key R${\text{\&}}$D Program of China (Grant No.2018YFB1800100), the National Natural Science Foundation of China (Grant No.U1909204), the Beijing Municipal Science and Technology Project (Grant No.Z191100007519007) and the Open Research Projects of Zhejiang Lab (Grant No.2021LC0AB03).
{'timestamp': '2021-03-12T02:20:06', 'yymm': '2103', 'arxiv_id': '2103.06611', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06611'}
arxiv
\section{Introduction} The goal of most Knowledge Graph (KG) Question Answering (QA) systems is to map natural language questions to corresponding SPARQL queries. This process is known as semantic parsing~\cite{berant2013semantic} and can be implemented in various ways. A common approach is to utilize query templates (alias graph patterns) with placeholders for relations and entities. The placeholders are then filled with entities and relations extracted from a given natural language question~\cite{DBLP:conf/www/AbujabalRYW18,DBLP:journals/semweb/HoffnerWMULN17,TBSL} to generate a SPARQL query, which is finally executed. Semantic parsing assumes that a template can be constructed or chosen to represent a natural language question's internal structure. Thus, the KGQA task can be reduced to finding a matching template and filling it with entities and relations extracted from the question. The performance of KGQA systems based on this approach depends heavily on the implemented query templates, which depend on the question's complexity and the KG's topology. Consequently, costly hand-crafted templates designed for a particular KG cannot be easily adapted to a new domain. In this work, we present a novel KGQA engine, dubbed TeBaQA. TeBaQA alleviates manual template generation's effort by implementing an approach that learns templates from existing KGQA benchmarks. We rely on learning of templates based on isomorphic basic graph patterns. The goal of TeBaQA is to employ machine learning and feature engineering to learn to classify natural language questions into isomorphic basic graph pattern classes. At execution time, TeBaQA uses this classification to map a question to a basic graph pattern, i.e., a template, which it can fill and augment with semantic information to create the correct SPARQL query. TeBaQA achieves state-of-the-art performance partially without any manual effort. In contrast to existing solutions, TeBaQA can be easily ported to a new domain using only benchmark datasets, partially proven by our evaluation over different KGs and train-test-sets. We use a best-effort to work with the data at hand instead of either (i) requiring a resource-intensive dataset creation and annotation process to train deep neural networks or (ii) to hand-craft mapping rules for a particular domain. Our contributions can be summarized as follows: \begin{itemize} \item We present TeBaQA, a QA engine that learns templates from benchmarks based on isomorphic basic graph patterns. \item We describe a greedy yet effective ranking approach for query templates, aiming to detect the best matching template for a given input query. \item We evaluate TeBaQA on several standard KGQA benchmark datasets and unveil choke points and future research directions. \end{itemize} The code is available at \url{https://github.com/dice-group/TeBaQA} and a demo of TeBaQA over encyclopedic data can be found at \url{https://tebaqa.demos.dice-research.org/}. We also provide an online appendix which contains more details about our algorithms and their evaluations at \url{https://github.com/dice-group/TeBaQA/blob/master/TeBaQA_appendix.pdf}. \section{Related Work} The domain of Knowledge Graph Question Answering has gained traction over the last few years. There has been a shift from simple rule-based systems to systems with more complex architectures that can answer questions with varying degrees of complexity. In this section, we provide an overview of the recent work. We begin with approaches that took part in QALD challenge series~\cite{qald-7,qald-8,qald-9}. gAnswer2~\cite{DBLP:conf/sigmod/ZouHWYHZ14} addresses the translation of natural language to SPARQL as a subgraph matching problem. Following the rule-based paradigm, QAnswer~\cite{DBLP:journals/semweb/DiefenbachGBSM20} utilizes the semantics embedded in the underlying KG (DBpedia and Wikidata) and employs a combinatorial approach to create SPARQL queries from natural language questions. QAnswer overgenerates possible SPARQL queries and has to learn the correct SPARQL query ranking from large training datasets. Second, we introduce approaches that rely on templates to answer natural questions over knowledge bases. Hao et al.~\cite{DBLP:conf/coling/HaoLHLZ18} introduced a pattern-revising QA system for answering simple questions. It relies on pattern extraction and joint fact selection, enhanced by relation detection, for ranking the candidate subject-relation pairs. NEQA~\cite{DBLP:conf/www/AbujabalRYW18} is a template-based KBQA system like TeBaQA, which uses a continuous learning paradigm to answer questions from unseen domains. Apart from using a similarity-based approach for template-matching, it relies on user feedback to improve over time. QUINT~\cite{Abujabal:2017:ATG:3038912.3052583} also suggests a template learning system that can perform on compositional questions by learning sub-templates. KBQA~\cite{DBLP:journals/pvldb/CuiXWSHW17} extracted 27 million templates for 2782 intents and their mappings to KG relations from a QA corpora (Yahoo! Answers). The way these templates are generated and employed differs from that of TeBaQA. NEQA relies on active learning on sub-parts and thereby, possibly misses the semantic connection between question parts. KBQA learns many templates and can hence fail to generalize well to other domains or KB structures. In 2019, Zheng et al.~\cite{zheng2019question} use structural query pattern, a coarse granular version of SPARQL basic graph patterns which they later augment with different query forms and thus can generate also SPARQL query modifiers. The closest work to ours is by Athreya et al.~\cite{athreya2020templatebased} based on a tree-based RNN to learn different templates on LC-QuAD v1 which the authors directly derive from the LC-QuAD v1 inherent SPARQL templates and thus cannot generalize to other KGs or datasets. CONQUEST~\cite{DBLP:conf/nldb/AvilaFMV20} is an enterprise KGQA system which also assumes the SPARQL templates are given. It then matches the questions and templates by vectorizing both and training one classifier, namely Gaussian Naïve Bayes. QAMP~\cite{DBLP:conf/cikm/VakulenkoGPRC19} is an unsupervised message passing system using a similarly simple approach to information extraction as TeBaQA. QAMP outperforms QAnswer on LC-QuAD v1. Recently, Kapanipathi et al.~\cite{DBLP:journals/corr/abs-2012-01707} present a system, dubbed NSQA, which is in pre-print. NSQA is based on a combination of semantic parsing and reasoning. Their modular approach outperforms gAnswer and QAnswer on QALD-9 as well as QAnswer and QAMP on LC-QuAD V1. In contrast to seminal semantic parsing work, e.g., by Berant et al.~\cite{berant2013semantic}, we assume relatively small training data; thus, learning a generalization via semantic building blocks will not work and consequently learn the whole template on purpose. Third, there are also other QA approaches which work with neural networks relying on large, templated datasets such as sequence-to-sequence models~\cite{DBLP:journals/corr/abs-1806-10478,DBLP:journals/corr/abs-1906-09302}. However, we do not focus on this research direction in this work. We refer the interested reader to extensive surveys and overview papers such as~\cite{DBLP:journals/corr/abs-1907-09361,DBLP:journals/kais/DiefenbachLSM18,DBLP:journals/semweb/HoffnerWMULN17}. \section{Approach} TeBaQA is based on isomorphic graph patterns, which can be extracted across different SPARQL queries and hence be used as templates for our KGQA approach. Figure~\ref{fig:qa-steps} provides an overview of TeBaQA's architecture and its five main stages: First, all questions run through a \textbf{Preprocessing} stage to remove semantically irrelevant words and create a set of meaningful n-grams. The \textbf{Graph-Isomorphism Detection and Template Classification} phase uses the training sets to train a classifier based on a natural language question and a SPARQL query by analyzing the basic graph pattern for graph isomorphisms. The main idea is that structurally identical SPARQL queries represent syntactically similar questions. At runtime, a question is classified into a ranked list of SPARQL templates. While \textbf{Information Extraction}, TeBaQA extracts all critical information such as entities, relations and classes from the question and determines the answer type based on a KG-agnostic set of indexes. In the \textbf{Query Building} phase, the extracted information are inserted into the top templats, the SPARQL query type is determined, and query modifiers are added. The resulting SPARQL queries are executed, and their answers are compared with the expected answer type. The subsequent \textbf{Ranking} is based on a combination of all information, the natural language question and the returned answers. In the following, we present each of these steps in more detail. We use DBpedia~\cite{dbpedia2014} as reference KG for the sake of simplicity in our description. \begin{figure}[htb!] \includegraphics[width=\linewidth]{img/TeBaQA_Architecture.pdf} \caption{TeBaQA architecture on the running example.} \label{fig:qa-steps} \end{figure} \subsection{Question Preprocessing}\label{Linguistic-Pruning} There are often words that do not contribute any information to the answer to natural language questions. Thus, we distinguish semantically relevant and irrelevant n-grams. Irrelevant n-grams can lead to errors that could propagate through the architecture. An example of this is the entity \url{dbr:The_The}\footnote{\texttt{dbr:} is a prefix which stands for \url{http://dbpedia.org/resource/}}. If the word \textit{The} were to be wrongly associated with this entity every time \textit{the} occurs in a question, the system's performance would decrease severely. However, irrelevant words are sometimes part of entities, e.g., \url{dbr:The_Two_Towers}, so we cannot always filter these words. For this reason, we combine up to six neighboring words from the question to n-grams and remove all n-grams that contain stop words only. To identify irrelevant words, we provide a stop word list that contains the most common words of a particular language that are highly unlikely to add semantic value to the sentence. Additionally, TeBaQA distinguishes relevant and irrelevant n-grams using part-of-speech (POS) tags. Only n-grams beginning with \lstinline|JJ|, \lstinline|NN| or \lstinline|VB| POS-tags are considered as relevant. After this preprocessing step, TeBaQA maps the remaining n-grams to entities from DBpedia in the information extraction step. \subsection{Graph-Isomorphism Detection and Template Classification} TeBaQA classifies a question to determine each isomorphic basic graph pattern (BGP). Since SPARQL is a graph-based query language~\cite{Perez:2009:SCS:1567274.1567278}, the structural equality of two SPARQL queries can be determined using an isomorphism. At runtime, TeBaQA can classify incoming questions to find the correct query templates, in which later semantic information can be inserted at runtime. \subsubsection{SPARQL BGP Isomorphism to Create Template Classes:} Using the training datasets, TeBaQA generates one basic graph pattern for each given question and its corresponding SPARQL query, see Figure~\ref{fig:pattern}. Subsequently, all \textit{isomorphic} SPARQL queries are grouped into the same class. Now, each class contains semantically different natural language questions but structurally similar SPARQL queries. \begin{figure}[htb!] \begin{tabular}{l} \begin{tikzpicture} \node[iri,anchor=center] (a) {<ent>}; \node[var,anchor=center,right=2cm of a] (b) {?uri} edge[arrin] node[lab] {<pred>} (a); \node[numcirc,left=0.2cm of a] {1}; \end{tikzpicture}\quad \begin{tikzpicture} \node[iri,anchor=center] (a) {<ent>}; \node[var,anchor=center,right=2cm of a] (b) {?uri} edge[arrin] node[lab] {<pred>} (a); \node[iri,anchor=center,right=2cm of b] (c) {<ent2>} edge[arrin] node[lab] {<pred2>} (b); \node[numcirc,left=0.2cm of a] {2}; \end{tikzpicture}\\ \begin{tikzpicture} \node[var,anchor=center] (a) {?uri}; \node[iri,anchor=center,right=2cm of a] (b) {<ent>} edge[arrin] node[lab] {<pred>} (a); \node[iri,anchor=center,below=0.8cm of a] (c) {<ent2>} edge[arrin] node[lab] {<pred2>} (a); \node[numcirc,left=0.2cm of a] {3}; \end{tikzpicture}\quad \begin{tikzpicture} \node[var,anchor=center] (a) {?x}; \node[iri,anchor=center,right=2cm of a] (b) {<ent>} edge[arrin] node[lab] {<pred>} (a); \node[iri,anchor=center,below=0.8cm of a] (c) {<ent2>} edge[arrin] node[lab] {<pred2>} (a); \node[var,anchor=center,below=0.8cm of b] (c) {?uri} edge[arrin] node[lab] {<pred3>} (a); \node[numcirc,left=0.2cm of a] {5}; \end{tikzpicture}\quad \begin{tikzpicture} \node[iri,anchor=center] (a) {<ent>}; \node[iri,anchor=center,below=0.8cm of a] (b) {<ent2>} edge[arrin] node[lab] {<pred>} (a); \node[numcirc,left=0.2cm of a] {6}; \end{tikzpicture}\\ \begin{tikzpicture} \node[var,anchor=center] (a) {?x}; \node[iri,anchor=center,right=2cm of a] (b) {<ent>} edge[arrin] node[lab] {<pred>} (a); \node[var,anchor=center,below=0.8cm of a] (c) {?uri} edge[arrin] node[lab] {<pred2>} (a); \node[numcirc,left=0.2cm of a] {8}; \end{tikzpicture}\quad \begin{tikzpicture} \node[iri,anchor=center] (a) {<ent>}; \node[var,anchor=center,right=2cm of a] (b) {?child} edge[arrin] node[lab] {<pred>} (a); \node[var,anchor=center,right=2cm of b] (c) {?uri} edge[arrin] node[lab] {<pred2>} (b); \node[numcirc,left=0.2cm of a] {4}; \node[var,anchor=centerr,below=0.8cm of a] (a1) {?uri}; \node[iri,anchor=center,right=2cm of a1] (b1) {<ent>} edge[arrin] node[lab] {<pred>} (a1); \node[numcirc,left=0.2cm of a1] {7}; \end{tikzpicture}\\ \end{tabular} \caption{All basic graph patterns used as classes for QALD-8 and QALD-9 which later become templates. Note, the depicted templates contain more than five examples in the training dataset. Our running example, "Who was the doctoral advisor of Albert Einstein?" belongs to template (1).} \label{fig:pattern} \end{figure} \begin{theorem}[Isomorphism of labeled graphs] \label{graph-isomorphism-theorem} Two labeled graphs are isomorphic when a 1:1 relationship and surjective function is present between the nodes of the graphs, wherein the node labels, edge labels, and neighborhood relationships are preserved by the mapping~\cite{gervasi2006computational}. \end{theorem} \subsubsection{Question Features and Classification} Next, TeBaQA trains a classifier that uses all questions of an isomorphism class as input to calculate features for this class. A feature vector holds all the information required to make a reliable statement about which question belongs to which class. The features can be seen in Table~\ref{table-question-features}. \begin{table*}[htb!] \caption{Features to map a question to an isomorphic basic graph pattern.}\label{table-question-features} \begin{tabularx}{\textwidth}{llX} \toprule \textbf{Feature} & \textbf{Type} & \textbf{Description} \\ \midrule QuestionWord & Nominal & Adds the question word (e.g. Who, What, Give) as a feature. \\ EntityPerson & Boolean & Checks the named entity tags of the sentence to see if any persons are mentioned in it. \\ NumberOfToken & Numeric & Stores the number of tokens separated by spaces excluding punctuation. \\ QueryResourceType & Nominal & Categorizes the question based on a list of subject areas, e.g., film, music, book or city.\\ Noun & Numeric & Aggregates the number of nouns. \\ Number & Numeric & Indicates how often numbers occur in the question.\\ Verb & Numeric & Aggregates the number of verbs. \\ Adjective & Numeric & Aggregates the number of adjectives. \\ Comperative & Boolean & Indicates whether comparative adjectives or adverbs are included in the sentence.\\ TripleCandidates & Numerical & Estimates how many SPARQL triples are needed to answer the question based on the number of verbs, adjectives, and related nouns.\\ \bottomrule \end{tabularx} \end{table*} The features can be divided into semantic and syntactic features. \textit{QuestionWord}, \textit{EntityPerson} and \textit{QueryResourceType} form the group of semantic features and represent particular content aspects of the question, e.g., persons or specific topics that are mentioned in the question. All other features describe the structure of the question. Note, other features were investigated, which did not improve the model's recognition rate. We report these features to aid future research in this area: 1) {Cultural Categories}: Mainly included music and movies, e.g., \textit{Who is the singer on the album The Dark Side of the Moon?} and 2) {Geographical entities}: Questions in which countries or cities occur, as well as where questions, e.g., \textit{In which country is Mecca located?} Using features above, it is possible to represent the question \textit{Who was the doctoral advisor of Albert Einstein?} with the following vector: \begin{lstlisting}[captionpos=b, basicstyle=\ttfamily,frame=single,basicstyle=\small] <Who,Person,8,dbo:Person,1,0,1,0,NoComperative,1> \end{lstlisting} TeBaQA trains a statistical classifier using the described features extracted from the input question and the isomorphic basic graph patterns as class labels. A feature vector's target class can be determined by generating the basic graph pattern for the corresponding SPARQL query and assigning the class, which represents this pattern. An evaluation can be found in Section~\ref{sec:eval_classifier}. \subsection{Information Extraction} TeBaQA identifies entities, classes, and relations to fill the placeholders of a particular SPARQL template. Since questions are shorter than usual texts, semantic entity linking tools such as DBpedia Spotlight~\cite{isem2013daiber} or MAG~\cite{moussallem2017mag,MAG} do not perform correctly due to the lack of semantic context information. For example, in \textit{Who was the doctoral advisor of Albert Einstein?}, the word \textit{Einstein} has to be linked to \url{dbr:Albert_Einstein} and not to any other person with that name. For this reason, we apply a KB-agnostic search index-based approach to identify entity, relation and class candidates. TeBaQA uses three indexes, which are created before runtime. \subsubsection{Entity Index} The entity index contains all entities from the target knowledge graph. To map an n-gram from the preprocessing step to an entity, TeBaQA queries against the index's label field. The index contains information about entities, relations and classes connected to the entity at hand. \subsubsection{Relation Index and Class Index} These two indexes contain all OWL classes and relations from a KG. The indexes are used to map n-grams to relations and classes of the ontologies of the KB.TeBaQA additionally indexes hypernyms and synonyms for all relations and classes.\footnote{The dictionary can be found at \url{https://github.com/dice-group/NLIWOD/tree/master/qa.annotation/src/main/resources} which was previously used by~\cite{DBLP:conf/esws/SinghBRS18}} Consider the question \textit{Who was the doctoral mentor of Einstein?}. DBpedia contains only the relation \url{dbo:doctoralAdvisor}\footnote{\url{dbo:} stands for \url{http://dbpedia.org/ontology/}} and not \url{dbp:mentor}\footnote{\url{dbp:} stands for \url{http://dbpedia.org/property/}}. Through the synonym \textit{advisor} of \textit{mentor}, the relation \url{dbo:doctoralAdvisor} can be determined. This example highlights the lexical and semantic gap between natural language and knowledge graphs. \subsubsection{Disambiguation} By querying the indexes for an n-gram, we get candidates for entities, relations and classes, whose labels contain all tokens of the n-gram. Since a candidate's label may contain more tokens than the n-gram, we apply a Levenshtein-distance filter of 0.8 on the candidates. All remaining candidates are used to fill a given template. \subsection{Query Building} \label{query_building} \subsubsection{Template Filling} For filling the templates, we facilitate the information about connected entities and connected relations for the found entities from the entity-index. For the triples in a template, there are two cases: 1.) The triple contains one placeholder for an entity and one placeholder for a relation. In this case, we resort to only the connected relation information from the entity index. An entity candidate $e$ and a relation candidate $p$ are combined to a triple $<e,p,?v>$ or $<?v,p,e>$ if the set of connected relations $S(e)$ of the entity $e$ contains $p$ and if the connected n-grams do not contain each other. 2.) The triple contains only one placeholder for a relation $p'$. This case only occurs when at least one triple in the template matches case 1. We can utilize these triples to generate matching triples for the given triple. Thus, we query the entity index and search for a set of entities $S(e')$ connected with the entity $e$ by the relation $p$. All connected relations from the entities in $S(e')$ in the set of relation candidates and whose n-grams do not cover the n-grams of $e$ and $p$ are candidates for $p'$. Each candidate SPARQL query is checked for consistency with the ontology. In general, there are query patterns that do not contain variables. This case only occurs in ask queries like \textit{Did Socrates influence Aristotle?}. We ignore this case to keep simplicity and aware of the performance impact. To summarize, TeBaQA creates several candidate SPARQL queries per template and thus per question. \subsubsection{Query Modifiers and Query Types} To translate a question into a semantically equivalent SPARQL query, it is often not enough to recognize the entities, relations or classes in the question and insert them into a SPARQL query. For example, the question \textit{How many children did Benjamin Franklin have?} asks for the number of children and not the concrete list. Thus, we apply a rule-based look-up to add query modifiers and choose a query type. The supported modifiers are $COUNT$, if the question contains keywords like \textit{How many or How much}, $Filter (?x<?y)$, if we identify comparatives and $ORDER\: BY\: [ASC (?x)\: |\: DESC (?x)]\: LIMIT \:1$, if the question contains superlatives. Additionally, we support ASK-type questions, if keywords like \textit{Is} or \textit{Are} are identified. Note, the templates and their respective basic graph pattern neither contain information about the query type nor information about query modifiers. Thus, TeBaQA generates one SPARQL query per candidate SPARQL query for each cross-product of query type and modifier that is recognized. The outcome is a list of executable queries for each input question. \subsection{Ranking} Since the \textit{conciseness} of an answer plays a decisive role in QA in contrast to full-text search engines, only the answer that corresponds best to the user's intention should be returned. Thus, all generated SPARQL queries and their corresponding answers are ranked. This ranking is carried out in two steps. First, we filter by 1) the expected answer type of the question in comparison to the actual answer type of the query and by 2) the cardinality of the result set. Second, TeBaQA ranks the quality of the remaining SPARQL queries. \subsubsection{Answer Type and Cardinality Check:} For certain types of answer sets, only those that match the question's expected answer type are considered for the next ranking step. We empirically analyzed the benchmark datasets and derived a rule-based system for the most common expected answer type and their distinguishing features. \begin{itemize} \item Temporal questions usually begin with the question word \textit{When}, e.g., \textit{When was the Battle of Gettysburg?}. TeBaQA expects a date as the answer type. \item Decision questions mostly start with a form of \textit{Be}, \textit{Do} or \textit{Have}. The possible answer type is boolean. \item Questions that begin with \textit{How much} or \textit{How many} can be answered with numbers. This also includes questions that begin with a combination of the question word \textit{How} and a subsequent adjective such as \textit{How large is the Empire State Building?} \end{itemize} If none of the above rules apply to a question, the result set's cardinality is checked. There are two cases: First, when several answers are needed to answer a question fully. Consider \textit{Which ingredients do I need for carrot cake?}, if only one answer is found for this question, it can be assumed that it is either wrong or incomplete. Second, when there is only one answer to a question, e.g., \textit{In which UK city are the headquarters of the MI6?}, an answer consisting of several entities would not be correct. To recognize to which query type (ASK or SELECT) a question belongs, the first noun or the first compound noun after the question word is checked. If they occur in the singular form, a single answer is needed to answer the question. For the above question \textit{In which UK city are the headquarters of the MI6?}, the compound noun would be \textit{UK city}. Since both words occur in the singular, it is assumed that only a single answer is required. If the first noun or group of nouns occurs in the plural, this indicates that the question requires multiple answers. In the question \textit{Which ingredients do I need for carrot cake?} the decisive word \textit{ingredients} is in the plural. However, the answer type of question may not be recognized correctly. For instance, if the question is grammatically correct but words whose singular form is identical to the plural form exist, such as \textit{news}, we cannot determine the correct answer type. These issues will be tackled in future research. Once the type of question and answer has been determined, all the answers whose type or cardinality does not match the question will be discarded. \subsubsection{Quality Ranking:} For the remaining SPARQL queries, TeBaQA calculates a $rating$ based on the sum of the individual scores of the bindings $B$ and the input question $phrase$. A binding $B$ is the mapping of entities, relations and classes to placeholders contained in one SPARQL query $q$. To compute the {relatedness factor} $r$, the following factors are taken into account: \begin{itemize} \item \textbf{Annotation Density}: The annotation density measures that the more words from the sentence are linked to an entity, class or relation, the more likely it is that it corresponds to the intention of the user. For the question \textit{What is the alma mater of the chancellor of Germany Angela Merkel?} one candidate query may apply the binding \url{dbr:Angela}, while another query applies the binding \url{dbr:Angela_Merkel}. The former refers only to the word \textit{Angela}. The latter refers to two words of the sentence: \textit{Angela Merkel} and covers longer parts of the $phrase$. \item \textbf{Syntactic Similarity}: The syntactic similarity is an indicator of how similar a n-gram of the sentence and the associated binding are. For example, in the question \textit{Who is the author of the interpretation of dreams?} the n-gram \textit{the interpretation of dreams} can be linked with \url{dbr:The_Interpretation_of_Dreams} or \url{dbr:Great_Book_of_Interpretation_of_Dreams} among others. The former has a smaller Levenshtein distance and a greater syntactic similarity with the selected n-gram. \end{itemize} We cover both aspects with the following formulas: \[ rating = \sum_{B \in q} r(B, phrase)\] \[r(entity, phrase) = |words(phrase)| - levenshtein\_ratio(label(B), phrase)\] After all entities, classes, and relations used in a query have been evaluated and summed up, the rating is corrected down by 30\% if more than 50 results are returned by the query, based on empirical observations in the datasets. \section{Evaluation}\label{chapter:evaluation} \subsection{Datasets} We performed the evaluation on the 8th and 9th Question Answering over Linked Data challenge training datasets (QALD-8 train~\cite{qald-8} and QALD-9 train~\cite{qald-9}), which contain 220 (QALD-8) and 408 (QALD-9) heterogeneous training questions. Additionally, we evaluated on the two LC-QuAD~\cite{LC-QuADv1,lc-quadv2} datasets with 4000 train and 1000 test questions and 24.000 train and 6.000 test questions, respectively. Across datasets, the questions vary in complexity since they also include comparatives, superlatives, and temporal aggregations. An example of a simple question is \textit{How tall is Amazon Eve?}. A more complex example is \textit{How many companies were founded in the same year as Google?} since it contains a temporal aggregation (\textit{the same year}). We created separate instances of TeBaQA for each of the training datasets and evaluated each instance on the corresponding test dataset. \subsection{Classification Evaluation} \label{sec:eval_classifier} For the QALD-8 and QALD-9 datasets, eight classes were identified for each dataset, compare Figure~\ref{fig:pattern}. For LC-QuAD v1 and LC-QuAD v2, TeBaQA identified 17 classes for both datasets. Since the two LC-QuAD datasets were constructed for more diversity, the classification is more challenging. Note, we omitted classes with less than five examples in the training dataset. We are aware that we are trading our overall performance for classification accuracy. To this end, we evaluated a variety of machine learning methods, which required questions to be converted into feature vectors. In particular, we used the QALD-8 and QALD-9 training datasets as our training data and used 10-fold cross-validation to evaluate the computed models. All duplicate questions and questions without SPARQL queries were removed from the training datasets. We tested multiple machine learning algorithms with the WEKA framework\footnote{\url{https://www.cs.waikato.ac.nz/ml/weka/}}~\cite{eibe2016weka} on our training data using 10-fold cross-validation. To achieve comparable results, TeBaQA uses only the standard configuration of the algorithms. The macro-weighted F-Measure for one fold in cross-validation is calculated from the classes' F-Measures, weighted according to the size of the class. After that, we calculated the average macro-weighted F-Measure across all folds. On the QALD datasets, the algorithm \textit{RandomizableFilteredClassifier} achieves the highest F-Measures of 0.523964 (QALD-8) and 0.528875 (QALD-9), respectively. On LC-QuAD v1, we achieve a template classification f-measure of 0.400464 and 0.425953 on LC-QuAD v2 using a MultilayerPerceptron. Consequently, we use the best performing classifiers for the end-to-end evaluation. Similar experiments can be found in Athreya et al.'s work~\cite{athreya2020templatebased}. The authors use a recurrent neural network, i.e., a tree-LSTM, to identify templates in LC-QuAD and achieve an accuracy of 0.828 after merging several template classes manually. \subsection{GERBIL QA Benchmark}\label{sec:gerbil-benchmark} For evaluation, we used the FAIR benchmarking platform GERBIL QA~\cite{DBLP:journals/semweb/UsbeckRHCHNDU19} to ensure future reproducibility of the experiments. Table~\ref{table:qa-systeme-vergleich} contains the results of selected Question Answering systems, measured against the QALD-8 and the QALD-9 test benchmarks\footnote{The links to our GERBIL-experiments can be found on our Github page: \url{https://github.com/dice-group/TeBaQA/blob/master/README.md}}. We focused on English questions only, as English is supported by all available QA systems at the time of these experiments. The macro value for Precision, Recall and F-Measure was selected. The evaluation was performed with GERBIL version 0.2.3 if possible. We report always the highest numbers if several papers reported numbers and evaluation with GERBIL was not possible. \begin{table}[htb!] \setlength{\tabcolsep}{6pt} \centering \caption{Results of TeBaQA and other state-of-the-art QA systems for multiple datasets. * indicates F-1 measure instead of QALD F-Measure~\cite{DBLP:journals/semweb/UsbeckRHCHNDU19}. ** Numbers taken from the corresponding paper.} \label{table:qa-systeme-vergleich} \resizebox{\textwidth}{!}{% \begin{tabular}{lccrrrr} \toprule \textbf{System}& \textbf{KB}& \textbf{Dataset}& \textbf{Precision} & \textbf{Recall} & \textbf{QALD F-Measure} & \textbf{Avg. Time in s}\\ \midrule gAnswer2~\cite{DBLP:conf/sigmod/ZouHWYHZ14} & DBpedia& QALD-8 & 0.337 & 0.354 & 0.440 & 4.548 \\ QAnswer~\cite{DBLP:journals/semweb/DiefenbachGBSM20} & DBpedia& QALD-8 & 0.452 & 0.480 & 0.512 & 0.446 \\ Zheng et al.~\cite{zheng2019question}** & DBpedia& QALD-8 &0.459 & 0.463& * 0.461 &- \\ TeBaQA & DBpedia& QALD-8 & 0.476 & 0.488 & \textbf{0.556} & 28.990 \\ \midrule Elon~\cite{qald-9} & DBpedia & QALD-9& 0.049 & 0.053 & 0.100 & 0.219 \\ gAnswer~\cite{DBLP:conf/sigmod/ZouHWYHZ14} & DBpedia & QALD-9 & 0.293 & 0.327 & 0.430 & 3.076 \\ NSQA~\cite{DBLP:journals/corr/abs-2012-01707}** & DBpedia& QALD-9 & 0.314 & 0.322 & *0.453 & - \\ QAnswer~\cite{DBLP:journals/semweb/DiefenbachGBSM20} & DBpedia & QALD-9& 0.261 & 0.267 & 0.289 & 0.661 \\ QASystem~\cite{qald-9} & DBpedia & QALD-9& 0.097 & 0.116 & 0.200 & 1.014 \\ Zheng et al.~\cite{zheng2019question}** & DBpedia& QALD-9 &0.458 & 0.471 & \textbf{*0.463} &- \\ TeBaQA & DBpedia& QALD-9 & 0.241 & 0.245 & 0.374 & 5.049 \\ \midrule NSQA~\cite{DBLP:journals/corr/abs-2012-01707}** & DBpedia& LC-QuAD v1& 0.382 & 0.404 & *0.383 & - \\ QAMP~\cite{DBLP:conf/cikm/VakulenkoGPRC19}** & DBpedia& LC-QuAD v1 & 0.250 & 0.500 & *0.330 & 0.720 \\ QAnswer~\cite{DBLP:journals/semweb/DiefenbachGBSM20} ** & DBpedia& LC-QuAD v1 & 0.590 & 0.380 & \textbf{*0.460} & 1.500 \\ TeBaQA & DBpedia& LC-QuAD v1&0.230 & 0.229 & 0.300 & 36.000 \\ \midrule TeBaQA & Wikidata& LC-QuAD v2 & 0.140 & 0.136 & 0.227 & -- \\ \bottomrule \end{tabular} } \end{table} On the QALD-8 benchmark, TeBaQA achieved the best results in terms of F-Measure by 5\% QALD F-measure. Our average time is significantly larger than the other reported systems since the ranking mechanism gets activated and then fires several SPARQL queries after the initial null-retrieving SPARQL query. On QALD-9, TeBaQA is in fourth place with a QALD F-Measure of 0.37. This implies that TeBaQA achieves comparable or partially better results than other semantic QA systems with a wide margin of possible improvements, as shown in the ablation study. QALD-9 is a more challenging benchmark than QALD-8 since it contains many questions that require complex queries with more than two triples. A more in-depth analysis shows that questions from QALD-9 often require complex templates that are not contained in the training queries or have only low support in the training set~\cite{DBLP:journals/corr/abs-2011-07743}. This mismatch leads to a high number of misclassifications and explains the limited performance on QALD-9 compared to QALD-8 and, thus, its limited generalization abilities to unseen templates. Although we are not outperforming the state-of-the-art systems on QALD-9, TeBaQA a novel research avenue w.r.t. learning from data. On the LC-QuAD dataset, which contains the most complex questions, TeBaQA achieves an F-Measure of 0.30. We ran this benchmark only once in our system and had some errors during runtime. We will further investigate the performance on LC-QuAD in our future research. Note, we ran LC-QuAD only once through the system to test our independence of the dataset similar to the methodology of Berant et al.~\cite{wang-etal-2015-building}. To the best of our knowledge and after reaching out to the authors of LC-QuAD, we are the first system to evaluate on LC-QuAD v2. Since LC-Quad v2 uses Wikidata instead of DBpedia, we generated separate indexes for the Wikdata KG. The rest of the system remained unchanged. This shows, that TeBaQA can be easily adapted to other Knowledge Graphs. \subsection{SPARQL operation modifiers} The Achilles heel of most QA systems is their inability to deal with SPARQL operation modifiers, e.g., questions involving aggregations or superlatives~\cite{DBLP:conf/semweb/0002DUN17}. In contrast to those other systems, TeBaQA contains functionalities to identify the query type and other modifiers. We analyzed the results of TeBaQA on these benchmark questions and found that TeBaQA was able to answer many of those questions, while other systems like QAswer and gAnswer fail on this; see supplementary material. \subsection{Ablation Study} \label{ablation} \begin{table}[htb!] \setlength{\tabcolsep}{6pt} \centering \caption{Ablation study for TeBaQA on the QALD-9 test benchmark.} \label{table:ablation_study} \resizebox{\textwidth}{!}{% \begin{tabular}{lrrrr} \toprule \textbf{QA System} & \textbf{Precision} & \textbf{Recall} & \textbf{Avg. Time} & \textbf{QALD F-Measure} \\ \midrule Perfect classification & 0.205 & 0.210 & 4.618 & 0.337 \\ Perfect classification + EL & 0.407 & 0.407 & 0.355 & 0.578 \\ Perfect classification + ranking & 0.245 & 0.257 & 4.029 & 0.399 \\ Perfect EL & 0.301 & 0.317 & 0.713 & 0.473\\ Perfect EL + ranking & 0.302 & 0.320 & 0.653 & 0.477 \\ Perfect ranking & 0.258 & 0.270 & 6.281 & 0.405 \\ Perfect classification + EL + ranking & 0.407 & 0.407 & 0.251 & 0.578 \\ \bottomrule \end{tabular} } \end{table} We performed an ablation study to find the modules of TeBaQA's pipeline, which influence the end-to-end performance the most. Since the number of possible entities is roughly a magnitude larger than the number of relations and for the sake of experiment time, we omitted to test for perfect relation and class linking. For the perfect classification experiment, the QALD F-Measure is lower than for the overall system, see Table~\ref{table:qa-systeme-vergleich}. Investigating the detailed outputs, TeBaQA selects the simple templates containing only one triple more often than the more complex templates because they have more instances, i.e., support, on the QALD-9 train dataset. In many cases, a simple query generates a result set that is a superset of the target result set and, in consequence, decreases the precision. When TeBaQA fails to fill the correct complex template with the correct entities, the query result set is often disjoint from the target result set. It is also reasonable that TeBaQA fails to fill the more complex templates due to missing or incorrect entity links. Still, there is a gap in the system, which becomes evident when looking at the perfect classification plus ranking. Ranking gets only activated if the perfect template filled with semantic information does not retrieve any answer. That is, TeBaQA fails to find the correct modifiers or needs to circle through other semantic information candidates. When the perfect classification is combined with perfect entity linking, the results reach a QALD F-measure of 0.58, which clearly would outperform any other system. The same happens if we add the perfect ranking. The results are the same in both cases because the ranking is most often not triggered since the perfect template is already filled correctly. The strongest, single influence is the entity linking part, enabling TeBaQA to jump to 0.47 F-measure. We will tackle this challenging module in future work. Regarding runtime, failing to find the perfect template and then iterating through the ranking, i.e., querying the SPARQL endpoint often, increases the average time needed significantly. \section{Summary and Future Work} We presented TeBaQA, a QA system which learns to map question to SPARQL template mappings using basic graph pattern isomorphisms. TeBaQA significantly eases the domain/KB adoption process as it relies only on a benchmark dataset at its core. In the future, we will evaluate TeBaQA on more heterogeneous KG benchmarks to identify further choke points. We will also improve the question classification and information extraction by using novel deep learning mechanism. \textbf{Acknowledgements} We acknowledge the support of the Federal Ministry for Economic Affairs and Energy (BMWi) project SPEAKER (FKZ 01MK20011A), ScaDS.AI (01/S18026A) as well as the Fraunhofer Zukunftsstiftung project JOSEPH and the Eurostars Project PORQUE (FKZ 01QE2056C). This work was partially supported by the German Federal Ministry of Transport and Digital Infrastructure (BMVI) in the project LIMBO (no. 19F2029I) and by the German Federal Ministry of Education and Research (BMBF) in the project SOLIDE (no. 13N14456) within ’KMU-innovativ: Forschung f\"ur die zivile Sicherheit’ in particular ’Forschung f\"ur die zivile Sicherheit’. \bibliographystyle{abbrv}
{'timestamp': '2022-02-03T02:16:36', 'yymm': '2103', 'arxiv_id': '2103.06752', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06752'}
arxiv
\section{ArCode} \label{sec:ArCode} ArCode is a tool for analyzing programs written in Java, creating their API usage models, identifying deviations in the code from a correct implementation, and providing recommendations on how to fix the found deviations. It is implemented as a plugin for IntelliJ IDEA development environment. There are three main inputs to ArCode: \begin{itemize} \item Information about the framework of interest (e.g. JAAS framework) \item Path to training projects directory \item Path to the program under development \end{itemize} ArCode leverages static analysis techniques to extract some facts about API dependencies and their usage constraints from the framework binary code. It then analyzes programs in the training repository and filters out those that are violating API usage constraints. Mining the remained training programs, it builds a \texttt{Framework API Specification (FSpec)} model for the framework of interest. FSpec represents correct ways of leveraging a framework's API to implement usecases or architectural concerns. Next, ArCode analyzes the program under development and creates its graph-based API usage model. This model alongside with the created FSpec are used to compute the graph edit distance \cite{bunke1997relation} between the current implementation and a correct implementation. This distance shows how far the current implementation is from a correct way of implementing an architectural concern or usecase. If the computed distance is greater than zero, it means that there is a deviation from a correct implementation. Therefore, ArCode provides a ranked list of recommendations on how to fix the found deviation. Each recommendation consists of a graph-based demonstration of the correct version of API usage and an automatically generated code snippet that implements that correct API usage. Detailed scientific aspects of ArCode is presented in its technical paper \cite{shokri2021arcode}. \subsection{Design and Implementation} \begin{figure} \centering \includegraphics[width=.8\textwidth]{Images/ArCodeProcess.png} \centering \caption{ArCode main modules and their interactions.} \label{fig:ArCodeProcess} \end{figure} ArCode plugin is composed of three main modules which are responsible for \textbf{(i)} creating Framework API Specification (FSpec) model for a framework of interest, \textbf{(ii)} analyzing the program under development and identifying implementation deviations, and \textbf{(iii)} generating graph-based as well as code snippet recommendations. \figref{fig:ArCodeProcess} provides a high level overview of these modules and their interactions. \subsection{Features} ArCode plugin helps programmers with three main features. \subsubsection{Architectural Concern Summerization} ArCode analyzes the program under development and creates API usage model for it. Then, a graph-based representation of this model is rendered and returned to the programmer. Moreover, a translation of this model to an executable java code snippet is automatically generated and provided for more comprehension of API usages in the program. \subsubsection{Implementation Deviation Detection} After creating the API usage model of the program under development, ArCode searches through the created FSpec to identify incorrect API usages (i.e. API miuses) in the program. Then, it generates a list of change recommendations to be applied to the program. Each recommendation has a score value between 0 and 1 assigned to it. The higher the score is, the less changes needed to be applied to the program to make it a correct implementation. If score equals 1, it means that the program is following a correct implementation and the corresponding recommendation follows the same implementation. However, if there is no recommendation with score equal to 1, it means that the program deviates from a correct implementation and needs to be fixed. \subsubsection{Fix Recommendation} In case that there is a deviation from correct implementation, programmer would be able to navigate between provided recommendations. Recommendations with higher scores are most likely to be what programmer intended to implement. Please not that a higher score indicates a higher similarity between the current implementation and a recommendation. However, ArCode also provides recommendations with lower scores to give the programmer insights into what other correct API usages could be followed to make the code a correct implementation. Recommendation scores are colored green, blue, orange, and red to make programmers aware that the recommendation is very similar, somewhat similar, not similar, very different than the current implementation respectively. \subsection{How to use ArCode} The source code as well as released versions of ArCode plugin are available at this repository on GitHub: \url{https://github.com/SoftwareDesignLab/ArCode-Plugin}. Once the plugin is installed on Intellij IDEA, ArCode's menu will appear as a sub-menu of \textit{tools} menu in this IDE (\figref{fig:ArCodeMenu}). Programmer needs to fill out the fields in the \textit{settings} menu as shown in \figref{fig:ArCodeSettings}. That is the way to configure ArCode plugin. More details on ArCode settings could be found from ArCode plugin repository. Then, by clicking on \textit{ArCode Runner} menu, ArCode starts analyzing the program and generating recommendations. \begin{figure} \centering \includegraphics[width=.8\textwidth]{Images/ArCodeMenu.pdf} \centering \caption{ArCode main menu} \label{fig:ArCodeMenu} \end{figure} \begin{figure} \centering \includegraphics[width=.8\textwidth]{Images/ArCodeSettings.pdf} \centering \caption{ArCode Settings menu} \label{fig:ArCodeSettings} \end{figure} \section{Conclusion \& Future Work} \label{sec:conclusion} Obtaining API specification of a framework can enable the correct implementation of architectural tactics and patterns. This paper introduces \textsc{ArCode}, a novel approach for inferring frameworks' API specification from limited projects. It relies on a Graph-based Framework API Usage model (GRAAM), which is an inter-procedural context-, and flow-sensitive representation of APIs in a program. Furthermore, \textsc{ArCode} also extracts inter-framework dependencies between APIs from framework source code and uses them to identify incorrect API usages in programs. It uses an inference algorithm to combine all extracted GRAAMs into a framework specification model. In a series of experiments, we demonstrated that it is possible to infer a framework specification model that accurately captures correct API usage to implement tactics and patterns. Moreover, recommendation systems empowered by the created framework specification model are able to provide accurate API recommendations, identify API misuses and provide a fix recommendation. Future work includes exploration of additional frameworks with regard to our technique and leveraging dynamic analysis alongside static analysis to extracting inter-framework dependencies. \section{Working Definitions} \label{sec:Def} We use various technical terms with respect to software design, programming concepts, and processing and analyzing program data. We define these terms first, ensuring a broader audience can understand the essence of the paper. \noindent--- \textbf{Framework or Application Framework:} We use the term and definition based on Cervantes, Velasco-Elizondo, and Kazman's IEEE Software article on ``A Principled Way to Use Frameworks in Architecture Design.'' A framework is a reusable software element that provides generic functionality, addressing recurring concerns across a range of applications. Software frameworks are related to \textit{patterns} and \textit{tactics} in that frameworks instantiate these concepts. The patterns and tactics that a framework instantiates allow particular quality attributes to be satisfied. \noindent--- \textbf{Specification} or \textbf{API specification}: is not used as a formal or mathematical notion. Instead, it refers to comprehensive properties of a framework's API that should be considered while using that API in a program. It includes key architectural elements of a framework (e.g., classes, concepts, methods), possible \textit{correct} API sequence calls, their data dependencies, and \textit{semantically equivalent} API calls of a framework. \noindent--- \textbf{Intra- and Inter-procedural program analysis}: an intra-procedural analysis only considers data or control flow contained within a single scope (i.e., function or method). An inter-procedural analysis analyzes the whole program taking into accounts data/control flow across multiple scopes according to the method/function calls. \noindent--- \textbf{API misuses} \mehdi{Define} While leveraging APIs of a framework to correctly implement a tactic or a pattern in a program, one should consider API usage constraints such as choosing correct APIs or calling APIs in a correct order. Violation from any of these constraints is known as API misuses. \mehdi{Revisit} \ali{Revisited} \section{Experimental Study}\label{sec:experimentalStudy} To show the practical usefulness of our approach for complex software systems, we used it in experimental studies of JAAS (Java Authentication and Authorization Services) and RMI (Remote Method Invocation) frameworks to generate recommendations for projects that incorporate them to implement tactic and patterns. JAAS addresses security architectural concerns in applications, and RMI supports interactions between different modules and methods in distributed systems. In these two studied frameworks \textbf{(i)} we investigate whether \textsc{ArCode} can learn correct ways framework APIs are invoked to implement tactics/patterns. We rely on a learning saturation experiment; \textbf{(ii)} we evaluate the accuracy of \textit{API recommendation} to help programmers implement tactics and patterns, and \textbf{(iii)} we analyze ArCode's performance in \textit{API misuse detection}. Additionally, we compare \textsc{ArCode}'s performance with MAPO~\cite{zhong2009mapo} and GrouMiner~\cite{Nguyen2009}, two approaches which were developed for API recommendation and misuse detection, but not evaluated on frameworks with architectural implications~\footnote{Frameworks used to implement tactics or patterns}. \subsection{Data Collection}\label{subsection:DataCollection} To create the training data for \textsc{ArCode}, we identified a large number of popular open-source projects using JAAS and RMI frameworks. These projects were collected from different public and open-source code repositories including GitHub, BitBucket and Maven. A team of three members peer reviewed programs and compiled them to generate their bytecode. The purpose of reviewing programs was to make sure that each selected program implemented authentication and authorization tactics and inter-process communication patterns and had more than one API call in its code. The final repository contains \textbf{51} projects that uses JAAS, and \textbf{50} projects that uses RMI. This repository has a total \textbf{1,106,886} lines of code (Java files), \textbf{8,831} classes and \textbf{9,600} methods. \subsection{Finding API Usages in Programs}\label{sec:evaluation_GRAAMs} We created GRAAMs for projects in the code repository based on the approach discussed in this paper (\secref{sec:GRAAM}). We also created API usages for GrouMiner, and MAPO approaches accordingly. It is worth mentioning that a program may have more than one entrypoint~\footnote{A program's entrypoint is the first method invoked once it starts executing (e.g. the \textsf{main()} method).}. Therefore, it is possible that more than one API usage can be found per program. One issue we encountered in our experiments was failure of GrouMiner when the number of nodes in its API usage graph (i.e. graph-based object usage model) precedes 19. Since we have use the source code of GrouMiner provided to us by the authors of this approach, and to stay faithful to the code, we did not make any changes to its source code. Therefore, we exclude API usage graphs with more than 19 nodes from our experiment. \begin{comment} \begin{figure} \centering \begin{subfigure}[b]{0.50\textwidth} \centering \includegraphics[width=\textwidth]{Images/Comparison_APIUsageExtraction_JAAS.pdf} \centering \caption{JAAS-based projects} \label{fig:comparison_APIUsageExtraction_JAAS} \end{subfigure}% \begin{subfigure}[b]{0.50\textwidth} \centering \includegraphics[width=\textwidth]{Images/Comparison_APIUsageExtraction_RMI.pdf} \centering \caption{RMI-based projects} \label{fig:comparison_APIUsageExtraction_RMI} \end{subfigure}% \caption{Distribution of the size of found API usage representation per approach for JAAS and RMI -based projects} \label{fig:comparison_APIUsageExtraction} \vspace{-5pt} \end{figure} \end{comment} \subsection{Experiment 1: \textsc{ArCode} Learning Saturation} \label{subsection:FSMCreation} To investigate the learning capability of \textsc{ArCode}, we create its \textbf{\textit{learning curve}}. This curve represents the rate of new knowledge added to FSpec comparing to the size of new GRAAMs it visits. In the case that \textsc{ArCode} has a good learning ability, the rate of growth of FSpec should decrease by visiting more GRAAMs. \figref{fig:model_saturation_JAAS} and \figref{fig:model_saturation_RMI} show learning curve of \textsc{ArCode} while creating FSpec for JAAS and RMI frameworks in the training phase. Blue curves represent the cumulative size of $k$ visited GRAAMs by ArCode. Orange curves show the size of FSpec after visiting $k$ GRAAMs. To conduct this experiment, we first sort the GRAAMs based on the number of their nodes. Then, we feed \textsc{ArCode} starting with bigger chunks of information. While there is an increase in the number of FSpec nodes in the initial steps, after visiting 24 GRAAMs of JAAS-based programs, we observe reaching 90\% completion of the final FSpec model. It means that after this point, there would be only 10\% new information learnt by FSpec. Likewise, \textsc{ArCode} reaches 90\% completion of its FSpec after visiting 51 GRAAMs of RMI-related projects. The \textsc{ArCode} learning curve indicates that: \begin{comment} \begin{table}[] \centering \caption{Comparing the model creation process in \textsc{ArCode}, MAPO and, GrouMiner} \label{table:comparison_mining} \begin{tabular}{@{}rcccc@{}} \cmidrule(l){2-5} \multicolumn{1}{c}{} & \multicolumn{2}{c}{\textbf{\# of Patterns/Sequences}} & \multicolumn{2}{c}{\textbf{Time (seconds)}} \\ \multicolumn{1}{c}{\textbf{}} & \textbf{JAAS} & \textbf{RMI} & \textbf{JAAS} & \textbf{RMI} \\\midrule \textbf{MAPO} & 20 & 13 & 2401 & 1162 \\ \textbf{GROUMiner} & 341 & 563 & 3895 & 116 \\ \textbf{ArCode} & 52 & 102 & 2410 & 1150 \\ \bottomrule \end{tabular} \end{table} \end{comment} \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering\captionsetup{width=.9\linewidth}% \includegraphics[width=\textwidth]{Images/FSM_Saturation_JAAS_DSC.pdf} \centering \caption{ArCode learning curve while visiting 51 JAAS-based sound GRAAMs} \label{fig:model_saturation_JAAS} \end{subfigure}% \begin{subfigure}[b]{0.48\textwidth} \centering\captionsetup{width=.9\linewidth}% \includegraphics[width=\textwidth]{Images/FSM_Saturation_RMI_DSC.pdf} \centering \caption{ArCode learning curve while visiting 89 RMI-based sound GRAAMs} \label{fig:model_saturation_RMI} \end{subfigure}% \caption{Model saturation while creating FSpecs of JAAS and RMI frameworks} \label{fig:model_saturation} \vspace{-5pt} \end{figure} \begin{tcolorbox}[size=title, opacityfill=0.15] \textbf{Finding 1:} Two case studies of RMI and JAAS indicate that there are \textit{limited correct ways} that developers incorporated these frameworks in their program; \textsc{ArCode}'s learning technique was able to enumerate and learn all these possible sound usages of the frameworks. \end{tcolorbox} \subsection{API Recommendation to Implement Tactics/Patterns} \label{sec:eval_API_Recommendation} To evaluate the quality of recommendations, we randomly select 80\% of the projects of each framework in the code repository as training and the remaining 20\% as testing data set. We use the same train and test data sets for \textsc{ArCode}, GrouMiner, and MAPO approaches to make a fair comparison between their performance. To generate labeled test cases for this experiment, we first create GRAAMs of each program in the test data set and then, we remove the last node of each GRAAM. Since a recommendation system is expected to recommend the removed API, that API would be used as the label of that test case. Next, we ask the recommendation system to return a ranked list of recommendations for each test case. Finally, based on the position of the correct recommendation in the ranked list, we compute the top-K accuracy of the recommendations ($k:1\rightarrow10$). Though, since we expect only one correct answer for each test case, the results for top-K precision and top-K recall would be the same as top-K accuracy in our experiments. \begin{comment} \begin{equation} \begin{split} Precision_{Top-K} =\dfrac{TP}{Total\_Experiments} \end{split} \end{equation} \end{comment} \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\textwidth]{Images/NextAPI-JAAS-Top_10.pdf} \centering \caption{JAAS-based projects} \label{fig:evaluation_next_API_JAAS} \end{subfigure}% \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\textwidth]{Images/NextAPI-RMI-Top_10.pdf} \centering \caption{RMI-based projects} \label{fig:evaluation_next_API_RMI} \end{subfigure}% \caption{Accuracy of \textsc{ArCode}, GrouMiner, and MAPO for next API recommendations on JAAS and RMI experiments} \label{fig:evaluation_next_API} \vspace{-5pt} \end{figure} We also computed the top-K accuracy of recommendations for MAPO and GrouMiner approaches. \figref{fig:evaluation_next_API} shows the result of this experiment. In the case of JAAS framework (\figref{fig:evaluation_next_API_JAAS}), \textsc{ArCode} achieved a 59\% accuracy while considering only the top ranked (top-1) API recommendation. However, if we consider top-2 recommendations, the accuracy improves to 84\%. Finally, if we consider top-8 APIs (or beyond), the accuracy of recommendations provided by \textsc{ArCode} tops 94\%. Compared to \textsc{ArCode}, the accuracy of MAPO and GrouMiner reaches 50\% and 41\% for JAAS-based programs. For RMI-based programs, ArCode provides 91\% accuracy for top-2 recommendations and beyond. The highest accuracy for MAPO and GrouMiner is 43\% and 17\%. Based on our observation, the diversity of API usages in JAAS-based programs is fewer compared to those of RMI-based programs. As a result, all approaches have their best performance in JAAS-based repository. Nevertheless, \textsc{ArCode} still outperforms MAPO and GrouMiner in both JAAS- and RMI-based tests. These results bring us to the following observation: \begin{tcolorbox}[size=title, opacityfill=0.15] \textbf{Finding 2:} ArCode's next API recommendation outperforms the prior work significantly (40\% and more). In both case studies top-2 recommendations were reliable (85\% in JAAS and 95\% in RMI), however ArCode top-1 recommendations in RMI were more reliable than JAAS. \end{tcolorbox} \subsection{API Misuse: Detecting a Missed API} One of common API missuses is missing a critical API call while implementing a tactic. Authenticating users with \code{LoginContext.login()} without first calling \code{HttpSession.invalidate()}~\cite{ICSA2017} or checking the role of a user before granting access are just some of many examples. To examine the accuracy of our approach in identifying such cases of API misuse in programs, similar to the API recommendation experiment (\secref{sec:eval_API_Recommendation}), we generate labeled test cases for this experiment. To do so, we randomly remove an API call from each program in an iterative manner. We were able to generate 77 test cases for JAAS-based and 80 test cases for RMI-based experiments. Then, we ask the system to identify the missed API and recommend a fix for it. \figref{fig:evaluation_missed_API} depicts the result of this experiment. In the case of the JAAS framework (\figref{fig:evaluation_missed_API_JAAS}), \textsc{ArCode} achieved a 78\% accuracy considering only the top ranked (top-1) API recommendation. Top-2 recommendation shows 91\% accuracy and finally, the accuracy of recommendations provided by \textsc{ArCode} tops 95\% for top-8 recommendations and beyond. Comparing to \textsc{ArCode}, the accuracy of MAPO and GrouMiner reaches 34\% and 28\% respectively. This test scenario is more complicated compared to the previous test case (next API recommendation) because, in addition to the ancestors, the descendants of the provided recommendation and the correct answer should match as well. Therefore, the accuracy of pattern-based approaches decreases in this usecase. Based on the results of this experiment we found: \begin{tcolorbox}[size=title, opacityfill=0.15] \textbf{Finding 3:} ArCode can identify a missed API in implementation of tactics/patterns and provide a recommendation to fix it. ArCade's top-2 recommendation accuracy in JAAS and RMI case studies are above 90\%. Furthermore, ArCode outperforms prior work with 60\% and more, making it a more reliable approach for API recommendations to implement tactics and patterns using frameworks. \end{tcolorbox} \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\textwidth]{Images/MissedAPI-JAAS-Top_10.pdf} \centering \caption{JAAS-based projects} \label{fig:evaluation_missed_API_JAAS} \end{subfigure}% \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\textwidth]{Images/MissedAPI-RMI-Top_10.pdf} \centering \caption{RMI-based projects} \label{fig:evaluation_missed_API_RMI} \end{subfigure}% \caption{Accuracy of \textsc{ArCode}, GrouMiner, and MAPO for missed API recommendations on JAAS and RMI experiments} \label{fig:evaluation_missed_API} \vspace{-5pt} \end{figure} \subsection{API Misuse: Wrong API Usage} Another type of misusing APIs in a program includes calling APIs in a wrong order in that program. Although such a program might not show a compile time error, the expected tactic is not implemented correctly. In this experiment, we create test cases that include an incorrect API usage in each project (e.g. incorrect order of APIs). Then, we ask the system to first, identify this API misuse and second, recommend a fix to make that API usage correct. To create such test cases, we go over all APIs in each program iteratively, selecting two random APIs and swapping them to generate incorrect usages of APIs. Following this approach, we were able to generate 432 test cases for JAAS and 246 test cases for RMI framework. Then, we ask the system to identify this API misuse and recommend a fix for it. Like the two other test scenarios, the system returns a ranked recommendation and we compute accuracy for top-k ($k: 1\rightarrow10$) recommendations. \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\textwidth]{Images/SwappedAPI-JAAS-Top_10.pdf} \centering \caption{JAAS-based projects} \label{fig:evaluation_swapped_API_JAAS} \end{subfigure}% \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\textwidth]{Images/SwappedAPI-RMI-Top_10.pdf} \centering \caption{RMI-based projects} \label{fig:evaluation_swapped_API_RMI} \end{subfigure}% \caption{Accuracy of \textsc{ArCode}, GrouMiner, and MAPO for fix recommendations on JAAS and RMI experiments} \label{fig:evaluation_swapped_API} \vspace{-5pt} \end{figure} The result of this experiment is demonstrated in \figref{fig:evaluation_swapped_API}. In the case of JAAS framework, \textsc{ArCode} shows 77\% accuracy for top-1 recommendations. Also, if we consider 8-top returned recommendations (or beyond), the accuracy of \textsc{ArCode} tops 97\%. The results show that MAPO and GrouMiner reach 7\% and 4\% accuracy respectively. This test scenario is the most complicated case compared to the previous experiments. Since we are swapping two APIs, ancestors and descendants of both the first and second APIs should be matched against those that are recommended. Thus, we observe accuracy degrading for MAPO and GrouMiner in such experiments. Based on the results of this experiment, we observed that: \begin{tcolorbox}[size=title, opacityfill=0.15] \textbf{Finding 4:} ArCode accurately detects wrong API usages and generates fix recommendation for them. Wrong API usages are more complicated that finding a missed API call in a tactic/pattern. In these complex misuses, ArCode with a large difference (60\% to 90\%) outperformed two of the prior work (GrouMiner and MAPO). \end{tcolorbox} \section{Training Data Processing and Validation Phase}\label{sec:GRAAM} In the previous phase, we obtained collected projects that use a framework API and are compilable. However, these two characteristics do not guarantee these projects to be \textit{sound}. Therefore, this second phase focuses on finding sound projects that can be used for training. Distinguishing sound and unsound projects require a sophisticated \textit{\textbf{program representation model}} that can capture fundamental information regarding the usage of the framework APIs including but not limited to object instantiation, static and non-static method calls, as well as static and non-static field accesses. These constructs can be scattered over multiple methods, which requires an inter-procedural analysis of the program. Such a representation must also capture implementation of interfaces and inheritances of abstract classes of the framework. Moreover, this model shall be able to represent relationships between the framework APIs, allowable data dependencies between these methods, the logical and a usecase-driven order of method calls, and semantically equivalent sequences of API calls. In this phase, we present an approach to pre-process the training data to (1) extract the above elements, and (2) validate the training data so projects which incorrectly implement tactics/patterns can be eliminated from the training process. \subsection{Motivating Examples}\label{subsec:Examples} \listref{code:JAASSample1} and \listref{code:JAASSample2} show two real-world code snippets of the \textit{authentication} tactic~\cite{Bass} implemented using the JAAS framework. The correct implementation of this security tactic requires a careful sequence of API calls and manipulations of data objects. Although these two code snippets implement authentication tactic in a different code structure, they both: create a \code{Subject} object and an object that implements the \code{CallbackHandler} interface and pass them to the constructor of the instantiated \code{LoginContext} object; and then call the \code{login()} method from \code{LoginContext}. In addition to the above statements, the code in \listref{code:JAASSample2} goes further and calls the \code{getSubject()} method from a \code{LoginContext} object (line 11) and calls the \code{getPrincipal()} method from a \code{Subject} object (line 12). From these two examples, we observe the followings: \noindent- \textbf{Observation \#1:} Only a subset of statements in a program (the highlighted lines) are related to the framework of interest and should be part of a framework API specification model. \noindent- \textbf{Observation \#2:} The framework-related statements could be scattered across multiple methods. Thus, the framework API specification model shall be able to interconnect these statements that are within different scopes. \noindent- \textbf{Observation \#3:} Multiple (sub) programs with the same behavior might be written slightly different. For instance, both code snippets in \listref{code:JAASSample1} and \listref{code:JAASSample2} create \code{Subject} and \code{CallbackHandler} objects to be passed to the constructor of \code{LoginContext}. Although the order of object instantiation in two code snippets is different, it does not change the behavior of the program. Therefore, it is necessary to develop an API usage representation model that adequately captures correct usages of frameworks' APIs while taking these concerns into account. We developed a novel \textbf{Graph-based Framework API Usage Model (GRAAM)} to address these concerns. \begin{listing} \tiny \begin{lstlisting}[language = javaEXT] 1. public class TestJaasAuthentication { 2. public static void main(String[] args) { 3. String user = System.getProperty("user"); 4. String pass = System.getProperty("pass"); 5. boolean loginStatus = true; 6. try { 8. LoginContext loginContext = getLoginContext(user,pass); 9. | loginContext.login(); | 10. } catch (LoginException e) { loginStatus = false; } 11. if(loginStatus) System.out.println("Login Successful."); 12. else System.out.println("Login Failed."); 13. } 14. private static LoginContext getLoginContext(String u, String p) throws LoginException{ 15. | CallbackHandler handler = new RanchCallbackHandler(u, p); | 16. | Subject subject = new Subject(); | 17. | LoginContext lc = new LoginContext("RanchLogin", subject, handler)}; | 18. return lc; 19. } 20. } \end{lstlisting} \caption{\textit{Sample \#1: a code snippet that implements Authentication tactic using JAAS framework}}\label{code:JAASSample1} \end{listing} \normalsize \begin{listing} \tiny \begin{lstlisting}[language = JavaExt] 1. public class LoginUsecase { 2. private static Logger LOGGER = Logger.getLogger(LoginUsecase.class); 3. public static void main(String[] args){ 4. BasicConfigurator.configure(); 5. LoginContext lc = null; 6. System.setProperty("java.security.auth.login.config", "jaas2.config"); 7. try{ 8. |Subject subject = new Subject();| 9. |lc = new LoginContext("rainyDay2", subject, new JAASCallbackHandler(| |"user1", "pass1"));| 10. |lc.login();| 11. |Subject subject = lc.getSubject();| 12. |subject.getPrincipals();| 13. LOGGER.info("established new logincontext"); 14. } 15. catch (LoginException e){ 16. LOGGER.error("Authentication failed " + e); 17. } 18. } 19. } \end{lstlisting} \caption{\textit{Sample \#2: a code snippet that implements Authentication tactic using JAAS framework}} \label{code:JAASSample2} \end{listing} \normalsize \subsection{Pre-Processing and Validation}~\label{subsec:PrimaryAPIUsageGraph} This pre-processing step identifies APIs that are used to implement tactics and patterns in a program, validates their usage based on several ground-truths obtained from the framework's source code, and creates \textit{Graph-based Framework API Usage Models (GRAAMs)} for correct API usages. We follow a four-step process: \textbf{(1)} System Dependence Graph (SDG) extraction, \textbf{(2)} Slicing of the SDG, \textbf{(3)} Removal of API usage violations, and \textbf{(4)} Generation of Graph-based Framework API Usage Models (GRAAMs). \subsubsection{System Dependence Graph (SDG) Extraction} First, we perform an \textit{inter-procedural} static analysis on a program and extract its context-sensitive \textit{Call Graph} using 1-CFA algorithm. A call graph is a directed graph representing relationships between caller and callee methods in a program~\cite{grove1997call}. A 1-CFA context-sensitive callgraph~\cite{shivers1991control} distinguishes between situations where a method $m_3$ is being called from $m_1$ or $m_2$. This type of call graph considers the possibility of different behaviors of the program in callee method (e.g. \textit{$m_3$}) based on different caller methods (e.g. $m_1$ or $m_2$). For the sake of scalability, we did not choose a higher sensitivity of context (i.e., n-CFA for $n>1$). Next, we compute the System Dependence Graph (SDG) of the program under analysis. An SDG is a directed graph representing a whole program~\cite{horwitz1990interprocedural}. The nodes in this graph are \textit{statements} in the program and the edges are either \textit{data} or \textit{control} dependencies between nodes. Since we incorporate a context-sensitive call graph, the constructed SDG holds the following characteristics: \begin{itemize}[leftmargin=*] \item[--] \textit{flow-sensitive}: it accounts the order of execution of statements in the program being analyzed; \item[--] \textit{context-sensitive}: it distinguishes different call sites. The same method \textit{m} can be invoked by different methods (call sites). As a result, \textit{m} is analyzed differently based on its corresponding call site. \item[--] \textit{inter-procedural}: it represents the system as a whole, interconnecting statements within different methods based on the caller-callee relationships; \end{itemize} We use T. J. Watson Libraries for Analysis (WALA)\footnote{http://wala.sourceforge.net} to construct SDGs with the aforementioned attributes. We chose WALA over other tools (e.g. Soot~\cite{vallee2010soot}) because it provides built-in supports for extracting SDGs from a 1-CFA call graph as well as different versions of Java language (e.g. Java 8). \subsubsection{Slicing the Extracted SDG} In this second step, we compute a slice\footnote{A program slice includes only the set of statements that may affect a point of interest of the program (referred as the slice criterion)~\cite{weiser1981program}.} of the program \textit{p} under analysis that includes all statements \textit{s} in the SDG that are either (i) a \textit{framework-related} statement; or (ii) that may be \textit{affected by} a framework-related statement or (iii) that \textit{affects} a framework-related statement. \concept{Framework-related Statements} are the statements $s_f$ that match the conditions (a)-(f) listed below. Each statement $s_f$ can be related with the framework either \textit{\textbf{directly}} (cases \textit{a}, \textit{b}, and \textit{c}) or \textit{\textbf{indirectly}} via inheritance (cases \textit{d}, \textit{e}, and \textit{f}): \begin{enumerate}[leftmargin=15pt] \item[(a)] it invokes a method from a \textit{framework data type} (classes or interfaces declared in the framework); \item[(b)] it instantiates an object from a \textit{framework data type}; \item[(c)] it accesses a field from a \textit{framework data type}; \item[(d)] it invokes a method implemented by an application class that inherits or implements a \textit{framework data type}; \item[(e)] it instantiates an object from an application class that inherits or implements a \textit{framework data type}; \item[(f)] it accesses a field from an application class that inherits or implements a \textit{framework data type}; \end{enumerate} \begin{comment} \begin{listing} \begin{lstlisting}[language = javaEXT] 1. public static void main(String[] args) { 2. |String user = System.getProperty("user");| 3. |String pass = System.getProperty("pass");| 4. boolean loginStatus = true; 5. |LoginContext lc = null;| 6. try { 7. |lc = getLoginContext(user,pass);| 8. |lc = id(lc);| (*@\textbf{9.}@*) lc.login(); 10. @|} catch (LoginException e) { loginStatus = false; }|@ 11. @|if(loginStatus) {\System.out.println("Login Successful.");}|@ 12. @| else {System.out.println("Login Failed.");}|@ 13. } 14. private static LoginContext getLoginContext(String u, String p) throws LoginException{ 15. System.out.println("Initializing login context"); (*@\textbf{16.}@*) |CallbackHandler handler = new RanchCallbackHandler(u,p);| (*@\textbf{17.}@*) |return new LoginContext("RanchLogin" , handler);| 18. } 19. private static LoginContext id(LoginContext loginContext) { 20. |return loginContext;| 21. } 22.} \end{lstlisting} \caption{\textit{Identifying JAAS framework related statements and their relationships in a code snippet}} \label{code:JAASSample3} \vspace{4pt} \end{listing} \normalsize \end{comment} After computing a slice of the SDG, we remove all the nodes (statements) in the remained graph that are not framework-related yet keeping the direct and indirect dependencies between framework statements. The outcome of this process is the program's \concept{Primary API Usage Graph} $g = (V,E)$, which is a directed labelled sub-graph of the SDG, with nodes $v \in V$ and edges $e \in E$ where $E \subseteq V \times V$. The set of nodes $V$ in a primary API usage graph is partitioned into three types: start node $V_{start}$, end nodes $V_{end}$ and framework API usage nodes $V_f$: \begin{enumerate}[leftmargin=15pt] \item[(1)] A \textit{\textbf{start node}} $v_{start} \in V_{start}$ represents the begining of the framework usage in a program. Each primary API usage graph starts with a single \textit{start node}; \item[(2)] Each \textit{\textbf{end node}} $v_{end} \in V_{end}$ indicates the termination of the framework usage. Each primary API usage graph ends with one or more \textit{end node(s)}; \item[(3)] Each \textit{\textbf{framework API usage node}} $v_f \in V_f$ denotes a framework-related statement in a program (i.e., $V_f = S_f$). Each $v_f$ has an associated \textbf{\textit{instruction type}} $type(v_f)$ (i.e. \textit{object instantiation}, \textit{field access} or \textit{method invocation}). Furthermore, each $v_f$ has a \textbf{\textit{target framework data type}} $target(v_f)$, that depends on the instruction type. In case of object instantiations, $target(v_f)$ is the framework class type of the object; for method invocations, $target(v_f)$ is the target of the call; and for field accesses, the $target(v_f)$ is the framework type that contains the field. \end{enumerate} The edge set $E$ in a primary API usage graph has two partitions: \textit{\textbf{sequence}} edges $E_s \subseteq (V_{start} \times V_f) \cup (V_f \times V_{end}) \cup (V_f \times V_f) $ and \textit{\textbf{data dependency}} edges $E_d \subseteq V_f \times V_f$: \begin{enumerate}[leftmargin=15pt] \item[(1)] A data dependency edge $e_{data} = v_{src} \xrightarrow{data} v_{dst}$ indicates that $v_{dst}$ uses data that has been defined by $v_{src}$. \item[(2)] A sequence dependency $e_{seq} = v_{src} \xrightarrow{seq.} v_{dst}$ indicates that $v_{dst}$ is used after $v_{src}$ in the program. \end{enumerate} \begin{figure} \centering \begin{subfigure}[b]{0.4\textwidth} \centering \hspace{-1pt} \vspace{20pt} \includegraphics[width=.8\textwidth]{Images/Sample1_GRASP-new.PDF} \centering \caption{Primary API usage graph for \listref{code:JAASSample1}} \label{fig:Grasp_for_Sample1} \end{subfigure}% ~ \begin{subfigure}[b]{0.4\textwidth} \centering \includegraphics[width=.8\textwidth, right]{Images/Sample_2_PrimaryAPIUsageGraph.pdf} \caption{Primary API usage graph for \listref{code:JAASSample2} } \label{fig:Grasp_for_Sample2} \end{subfigure} \caption{Extracted primary API usage graphs from sample code snippets} \label{fig:Grasps_for_Sample_Codes} \vspace{-6pt} \end{figure} \figref{fig:Grasp_for_Sample1} and \figref{fig:Grasp_for_Sample2} show the primary API usage graphs for the code snippets in \listref{code:JAASSample1} and \ref{code:JAASSample2}. We use solid edges to show data dependencies and dashed edges to indicate sequence dependencies. For example, since the \code{CallbackHandler} object is used in the \code{LoginContext}'s constructor, there is a data dependency edge between \code{init CallbackHandler} and \code{init LoginContext} nodes in the primary API usage graphs. Nodes with a lighter background represent statements that are related with the framework indirectly (via inheritance). \subsubsection{Removing API Usage Violations} We explained so far how we analyze a project to extract its API usage information and represent it as a primary API usage graph. However, we want to eliminate any erroneous API usages in our training corpus. Therefore, we need a reliable ground truth to identify such incorrect usages in a code repository and filter them out from the training data. \textsc{ArCode} analyzes the framework's source codes and captures the API usage rules that are not visible to the developers, but are implicitly reflected in the source code of frameworks. To do so, it performs a static analysis of the framework's source code to capture \textit{implicit} data dependencies between APIs of a framework. Since this information is obtained directly from the framework, not from programs that use the framework, it could be considered as a ground truth for identifying API misuses. The main idea is to leverage \textbf{reader-writer} roles of API methods inside a framework to find dependencies between them. Using these dependencies, one can find partial API strict orders that must be followed in a program. As a results, API misuses in a program could be identified with confidence by finding violations from these strict orders. \textit{Writer} and \textit{Reader} methods are defined as: \noindent-- \textbf{\textit{Writer method:}} A method is considered as a writer regarding a specific class \textit{field} if it changes the value of that specific field somewhere in its body. \noindent-- \textbf{\textit{Reader method:}} A method is considered as a reader regarding a specific class \textit{field} if it uses the value of that specific field somewhere in its body. \begin{figure}[!htbp] \centering \includegraphics[width=\textwidth]{Images/IFD_1.pdf} \caption{Extracting Inter-framework Dependencies between API methods from LoginContext class (JAAS framework)} \label{fig:IFD_Sample} \vspace{-6pt} \end{figure} \begin{figure}[!htbp] \centering \includegraphics[width=.7\textwidth]{Images/IFD_smaller.pdf} \caption{IFD Model based on Fig.~\ref{fig:IFD_Sample}} \label{fig:IFD_model} \vspace{-6pt} \end{figure} As an example, \figref{fig:IFD_Sample} shows three methods from \code{LoginContext} class in the JAAS framework. This class has various fields including \code{subject} and \code{loginSucceeded}. While method \code{login()} assigns values (\textit{writes}) to \code{subject} and \code{loginSucceeded} fields, methods \code{getSubject()} and \code{logout()} use (\textit{read}) these fields' values. As a result, \code{getSubject()} and \code{logout()} methods are dependent to some data generated in \code{login()} method. We extract these information and create our \concept{Inter-Framework Dependency (IFD)} model. The IFD built for the framework's code shown in \figref{fig:IFD_Sample} is depicted in \figref{fig:IFD_model}. We use IFD model for identifying incorrect programs w.r.t. a framework usage. If a programmer has a framework-related statement $s_2$ in a program before API $s_1$ while based on IFD model $s_2$ reads data generated by $s_1$ ($s_1 \xrightarrow[]{\text{data}} s_2 $), then, that program is considered as an incorrect program. \subsubsection{Generating Graph-based Framework API Usage Models (GRAAM)} The last step of pre-processing and data validation phase focuses on creating a representation of each training data, a Graph-based Framework API Usage Model (GRAAM), which can be used by \textsc{ArCode}'s learning algorithm. We provide a definition for a GRAAM further in this section. As discussed earlier, it is possible that two programs with different sequences of framework-related statements implement the same tactic. For example, although \listref{code:JAASSample1} and \listref{code:JAASSample2} implement the same use case, the instantiation order of \code{Subject} and \code{CallbackHandler} in their programs and so, in their corresponding primary API usage graphs (\figref{fig:Grasp_for_Sample1} and \figref{fig:Grasp_for_Sample2}) is different. We call these sequences of API usage nodes as \concept{Semantically Equivalent API Sequences}. Two sequences of framework usage nodes, $seq_1$ and $seq_2$, are semantically equivalent if both conditions are true: \begin{itemize}[leftmargin=*] \item there is a \textit{bijection} between the nodes in $seq_1$ and $seq_2$. Each paired nodes $s_1 \in seq_1$ and $s_2 \in seq_2$ have the same \textit{type} and \textit{target framework type}, i.e. $type(s_1) = type(s_2)$ and $target(s_1) = target(s_2)$; and \item the two sequences are isomorphic considering only the data dependency between APIs in each sequence. \end{itemize} As a result, a \concept{Graph-based Framework API Usage Model} (GRAAM) is a directed graph $g$ which has the same set of nodes as a \textit{primary API usage graph}, but a different edge type: \textbf{API Order Constraint} edges. Semantically equivalent API sequences have a single representative in a GRAAM. In other words, two different programs with the same behavior (w.r.t. APIs of the same framework) have isomorphic GRAAMs. For example, parts of the programs in \listref{code:JAASSample1} and \listref{code:JAASSample2} including instantiation of \code{Subject}, \code{CallbackHandler}, \code{LoginContext}, and calling \code{login()} method, implement the same tactic (authenticate actors). Thus, their corresponding sub-GRAAMs are the same. This property of GRAAM enables us to have the same representation for semantically equivalent API usages in different programs. Hence, when we look at a code repository, we can correctly identify the same API usages and compute their frequencies. \begin{figure} \centering \includegraphics[width=\textwidth]{Images/GRAAM_1_2.pdf} \caption{Built GRAAMs for programs in (a) \listref{code:JAASSample1} and (b) \listref{code:JAASSample2}. Since both programs use \textit{semantically the same} API sequences for creating a \code{LoginContext} object and calling \code{login()} method, their corresponding Sub-GRAAMs confined by the purple dashed line are isomorphically the same.} \label{fig:CreatedGRAAMs} \end{figure} To create a GRAAM, we \textbf{(i)} start with a validated primary API usage graph, \textbf{(ii)} remove all the sequence edges except edges from start node and edges to end node(s), and \textbf{(iii)} add relevant edges from IFD model to the graph. To be more specific, this graph is built based on framework-related statements identified in the program, their \textit{data dependencies} captured from the program, plus data dependencies mined from the framework's source code. The reasoning behind removing sequence edges and keeping data edges is that if the data produced in an API call $a_1$ is not being used by an API call $a_2$, it means that calling $a_1$ before $a_2$ in the program is not required, i.e., the order of $a_1$ and $a_2$ does not affect the program's behavior. We reflect this non-restriction situation in our GRAAM by eliminating this order constraint between $a_1$ and $a_2$. \figref{fig:CreatedGRAAMs} shows the created GRAAMs for the examples in \listref{code:JAASSample1} and \ref{code:JAASSample2}. These GRAAMs are created based on the primary API usage graphs depicted in \figref{fig:Grasps_for_Sample_Codes} and the IFD model shown in \figref{fig:IFD_model}. For instance, the edge between \code{LoginContext.login()} and \code{LoginContext.getSubject()} in \figref{fig:CreatedGRAAMs}b comes from data dependency between \code{LoginContext.login()} and \code{LoginContext.getSubject()} captured in IFD model depicted in \figref{fig:IFD_model}. As shown in \figref{fig:CreatedGRAAMs}, parts of programs in \listref{code:JAASSample1} and \listref{code:JAASSample2} that implement the same thing have the same sub-GRAAMs. \section{Introduction} To satisfy performance, security, reliability and other quality concerns, architects need to compare and carefully choose a combination of architectural patterns, styles or tactics. Then later in the development cycle, these architectural choices must be implemented completely and correctly in order to avoid a drift from envisioned design. Prior work~\cite{KazmanFrameworks} by Cervantes, Velasco-Elizondo, and Kazman confirms that software designers and developers are increasingly relying on application frameworks as first-class design concepts to facilitate implementation of architectural tactics and patterns. \textit{Software frameworks} are reusable software elements that provide key functionalities, addressing recurring concerns across a range of applications. They incorporate many architectural patterns and tactics to prevent software designers and developers from implementing software from scratch~\cite{KazmanFrameworks,cervantes2019data}. For instance, the architecture of most contemporary enterprise applications relies on the \textit{Spring Framework} that provides pre-packaged solutions to implement various architectural concepts ranging from \textit{Model-View-Controller} (MVC) patterns to \textit{authentication} and \textit{authorization} security tactics~\cite{Bass,ICSA2017}. Developers use Application Programming Interfaces (APIs) to import and use the frameworks' functionalities~\cite{cervantes2019data,MUJHID201781}. Therefore, programs' quality largely depends on using these APIs correctly~\cite{ICSE2018}. Multiple studies have shown that proper use of a framework's API requires an in-depth understanding of its underlying architectural patterns and tactics, class structure, and set of tacit sequence calls, data-flows as well as interfaces that need to be implemented \cite{KazmanFrameworks,robillard2009makes,Johnson:1992:DFU:141936.141943,ICSE2018}. Recent qualitative and quantitative studies have reported that implementing architectural tactics is more complex compared to delivering software functionalities, and novice and non-architecture savvy developers struggle in implementing architectural tactics and patterns~\cite{ICSE2018, ICSA2017}. Previous paper by Soliman, Galster, and Riebisch published at ICSA~\cite{7930203} has indicated that developers rely on sources such as Q\&A websites (e.g. StackOverflow) to find information on how to use frameworks, implement tactics and patterns for specific quality attributes~\cite{DBLP:conf/wicsa/SolimanGSR16}. However, prior research have also shed a light that snippets on accepted answers of Q\&A websites can contain design flaws, bugs or vulnerabilities that get reproduced across multiple software systems that reused that code snippet ``as is''~\cite{baltes2019usage,fischer2017stack}. The prior work on framework API recommendations~\cite{acharya2007mining, shoham2008static, mover2018mining, fowkes2016parameter, dang2015api, lamba2015pravaaha, amann2019investigating,zhong2018empirical,zhong2009mapo,hsu2011macs,dang2015api,saied2018towards,saied2020towards,gu2019codekernel, thung2016api, zheng2011cross,ren2020demystify,monperrus2013detecting,amann2018systematic,amann2019investigating,wasylkowski2007detecting} focus on low level, local data structure related concerns and basic utility frameworks used to implement various data structures. This line of work fall short of addressing the challenges of implementing tactics and patterns and has not fully studied frameworks used to bring a new architectural tactic or pattern into a given system design. Other researchers have attempted to develop recommender systems to assist programmers in implementing architectural tactics and patterns~\cite{ICSA2017,DBLP:conf/icse/MirakhorliCK15,DBLP:conf/icsa/BhatTSBHM19}. However, prior work does not support implementing architectural tactics and patterns using frameworks. In this paper, we aim to study frameworks with architectural implications that address tactics or patterns. We propose an approach entitled \textsc{ArCode} to help programmers implement an architectural tactic or pattern using API recommendations. \textsc{ArCode} leverages a novel learning technique to infer an \textit{accurate} and \textit{explicit} API specification model which will be used for generating recommendations. The significance of the contribution made by this paper is briefly described below: \begin{itemize}[leftmargin=*] \item To the best of our knowledge, this is the first study focusing on inferring and using API specification of a software framework with architectural implications (e.g., frameworks implements architectural tactics and patterns). \item We present a program analysis approach to reverse engineer a novel \textsc{\textbf{G}raph-based F\textbf{r}amework \textbf{A}PI Us\textbf{a}ge \textbf{M}odel} (\textbf{GRAAM}), which is an \textit{abstract and semi-formal representation} of how a framework's API is being used in a given program to implement tactics and patterns. \item An automated approach to detect projects that violate frameworks API properties. We release a program analysis method that analyze the byte code of frameworks and extract an explicit usage model of framework APIs using a concept named \textsc{\textbf{I}nter-\textbf{F}ramework \textbf{D}ependency} (\textbf{IFD}) model. Later the IFD can be used to identify projects that violate a framework's implicit API order constraints. \item A novel \textit{inference algorithm} called \textbf{\textsc{ArCode}} to construct the framework API specification model from a repository of \textbf{GRAAMs}. \textsc{ArCode} is an inter-procedural context-, and flow- sensitive static analysis approach to automatically infer a specification model of frameworks from two sources, limited sample programs and a framework source code. \item An empirical investigation of the usefulness of the proposed approach to recommend APIs and detect API misuses for tactics' implementation on two popular Java-based frameworks. We use Java Authentication and Authorization Services (JAAS) and Remote Method Invocation (RMI) as case studies. JAAS framework is used to implement \textit{authentication} and \textit{authorization} security tactics~\cite{ICSA2017}, while RMI framework is used as a building block to implement a number of object oriented patterns such as client-server and remote method call. We demonstrate that \textsc{ArCode} can help developers implement tactics and patterns via an accurate API recommendation and API misuse detection when such frameworks are used. \end{itemize} \begin{figure*} \centering \includegraphics[width=\textwidth]{Images/ArCode-Overview.pdf} \centering \caption{Overview of our approach (\textsc{ArCode})} \label{fig:overview} \end{figure*} The remainder of this paper is organized as follows: \secref{sec:overview} provides an overview of our approach. \secref{sec:Preparation} briefly describes data collection phase. \secref{sec:GRAAM} presents our graph-based API usage model (GRAAM) for a program. \secref{sec:ArCode} describes \textsc{ArCode}, our automated approach for inferring a framework API specification model from extracted GRAAMs. An experimental evaluation of the approach is presented in \secref{sec:experimentalStudy}. \secref{sec:Threats_to_Validity} discusses threats to validity of the approach. \secref{sec:relatedWork} reviews related work. Lastly, \secref{sec:conclusion} concludes this paper. \section{Motivation}\label{sec:motivation} While pattern-based approaches are capable of finding frequent API usages that programmers commonly practice in their code, there is an important downside to such approaches, a high rate of false-positive and false-negative in their recommendations~\cite{amann2018systematic}. Two main factors contribute to this issue. First, although programmers frequently copy-paste code snippets from resources that are meant to be trustworthy (e.g., Stack Overflow) to their code, those resources sometimes provide incorrect API usages ~\cite{baltes2019usage,fischer2017stack}. Hence, a pattern-based approach would incorrectly consider it as a correct API usage pattern. Second, there might be a correct usage of an API that has not been (or rarely has been) implemented by programmers in a code repository. Due to the low frequency of correct usage occurrences, pattern-based approaches do not include this correct API usage in their API usage patterns. To elucidate the aforementioned issues with pattern-based approaches, we selected two well-appreciated approaches in this field, MAPO \cite{zhong2009mapo} and GrouMiner \cite{Nguyen2009}, to investigate their capability of capturing correct API usages. We focus on an open-source java-based framework, Java Authentication and Authorization framework (JAAS)\footnote{\url{https://docs.oracle.com/javase/7/docs/technotes/guides/security/jaas/JAASRefGuide.html}}. We chose JAAS due to its popularity and vast utilization in Java-based applications. \listref{code:motivation_sample} demonstrates one possible correct usage of JAAS API to implement \textit{authentication} usecase in a program\footnote{ \url{https://javaranch.com/journal/2008/04/authentication-using-JAAS.html}}. It includes: (1) Instantiating an object of \code{CallbackHandler} interface (line 6), (2) Instantiating an object of \code{LoginContext} class by passing the previously created callback handler object to its constructor (line 8), (3) Invoking \code{login()} method of the created LoginContext instance (line 9), (4) Invoking \code{getSubject()} method of the created LoginContext instance (line 10), and finally (5) Invoking \code{logout()} method of the created LoginContext instance (line 11). \begin{listing} \tiny \begin{lstlisting}[language = javaEXT] 1. public class SampleJaasAuthentication { 2. ... 3. public static void main(String[] args) { 4. String userName = System.getProperty("user"); 5. String password = System.getProperty("pass"); 6. CallbackHandler handler = new MyCallbackHandler(userName, password); 7. try { 8. LoginContext loginContext = new LoginContext("MyLogin", handler); 9. loginContext.login(); 10. System.out.println(loginContext.getSubject()); 11. loginContext.logout(); 12. } catch (LoginException e) { 13. System.out.println("Login Failed."); 14. } 15. } 16. ... 17.} \end{lstlisting} \caption{\textit{A correct authentication tactic implemented using JAAS APIs} }\label{code:motivation_sample} \end{listing} \normalsize We created a repository of programs that incorporate JAAS API to implement authentication and authorization usecases (\secref{subsection:DataCollection}). Based on our observations, over \textbf{35\%} of programs in this repository implemented authentication usecase as the same as code snippet in \listref{code:motivation_sample}. Thus, one would expect that below API usage pattern be discovered from this code repository: \textbf{Expected API Usage Pattern:} \code{CallbackHandler instantiation} $\rightarrow$ \code{LoginContext instantiation} $\rightarrow$ \code{LoginContext.login()} $\rightarrow$ \code{LoginContext.getSubject()} $\rightarrow$ \code{LoginContext.logout()} \hl{What pattern was discovered? Do you mean this particular one was not discovered?} Nonetheless, our findings show that even well-appreciated pattern-based approaches like MAPO and GrouMiner are not able to identify this API usage pattern. Instead, the patterns they find do not cover the whole sequence or miss some APIs in between. Since MAPO and GrouMiner do not capture the expected API usage pattern, it would be identified as an API misuse, which is incorrect. \section{Overview} \label{sec:overview} \textsc{ArCode} is designed to perform API recommendation and misuse detection for application frameworks used to implement architectural tactics and patterns. In particular, these frameworks express a great degree of inter-process communication and API interactions beyond a single class, module or process~\cite{ICSA2017}. \textsc{ArCode} aims to help novice developers, and non-architecture savvy developers to use frameworks. \textsc{ArCode} learns the API specification of frameworks from limited \textit{sound} program examples. A program is considered \concept{sound} if it uses the framework API correctly to implement the tactic. As shown in \figref{fig:overview}, the approach has four phases: \begin{itemize}[leftmargin=18pt] \item[\circled{1}] \textbf{Data Collection and Preparation Phase:} We create a code repository of programs that incorporate the framework of interest. Section~\ref{sec:experimentalStudy} use \textit{learning saturation} as a measure of indicating how many training projects are required. \item[\circled{2}] \textbf{Training-Data Pre-Processing and Validation Phase:} Given the training data, we perform a \textit{context-}, \textit{path-}, and \textit{flow-sensitive} static analysis to create an \textit{inter-procedural} graph-based representation of API usages for each program. In this phase, we ensure that only sound training programs will be included in our training data. To guarantee the syntax correctness, we first compile programs and generate their jar files. Moreover, to verify that a program is semantically error free (w.r.t. API usages), we use a novel technique to extract \textsc{\textbf{I}nter-\textbf{F}ramework \textbf{D}ependency} (\textbf{IFD}) model from the framework's internal source code. This model encompasses mandatory order constraints of APIs that are enforced by the framework and must be preserved in any given program. This approach identifies and rules out incorrect API usages and API violations. Leveraging the IFD model, we separate sound programs from those that violate implicit rules of API usage required by the framework. \item[\circled{3}] \textbf{Training Phase:} For each sound program, we create its \textbf{G}raph-based F\textbf{r}amework \textbf{A}PI Us\textbf{a}ge \textbf{M}odel (GRAAM) which is an \textit{abstract model} demonstrating how the framework API was used in a given validated training data. Finally, via a recursive learning method the framework API specification model is created from a set of generated GRAAMs. \item[\circled{4}] \textbf{Recommendation Phase}: The learnt model is used in this phase to implement a recommender system guiding programmers in using APIs. Specifically, this system analyzes the program under development and recommends what APIs should be considered and how they should be used in that program to correctly implement a tactic or a pattern. Furthermore, if there are API misuses, ARCODE will detect and recommend fixes. \end{itemize} \section{Data Collection and Preparation Phase}\label{sec:Preparation} The first phase of this approach is focused on collecting a set of projects that uses a framework of interest. These projects should match the following criteria: \textit{(i)} it imports and uses the framework API, and \textit{(ii)} it is syntactically correct. For checking the first condition, we scan the source code and check for API statements in the code. To guarantee the syntax correctness (second condition), we compile the programs to generate their JAR files. \section{Recommendation Phase} Once \textsc{ArCode} is trained and a FSpec model is built, it can be used to help programmers correctly implement architectural patterns and tactics through providing correct API recommendations. The recommendation system has the following steps: \begin{enumerate}[leftmargin=*] \item \textbf{Process Partial Program:} it takes in a partial program written by a programmer and creates its GRAAM; \item \textbf{Context Based Recommendation:} the recommender engine finds the most similar \textit{semantically equivalent} API usages inside the FSpect to the given GRAAM. Then it finds changes needed to be performed on the GRAAM to make it a correct implementation of a tactic or pattern. \item \textbf{Ranked List}: the outcome is provided in the form of ranked list of API recommendations (e.g. remove, add, replace). The rank of each recommendation in the list is determined based on the frequency of its corresponding edges in the FSpec. \end{enumerate} \textsc{ArCode} can identify the next APIs required to be called in a program to make it a complete and correct implementation. It also is able to detect misuses of APIs in a program and recommend fixes for it. Some API misuses are not detectable in the compile time since it does not violate syntax of the language. However, these are serious semantic bugs which can compromise the entire objective of a tactic/pattern. \section{Related Work}\label{sec:relatedWork} There have been numerous works on identifying frameworks' API specifications and creating models that enable API recommendation and misuse detection systems. The aim of these systems is to help programmers correctly use API calls and prevent incorrect usage of APIs in their programs~\cite{robillard2013automated, zhong2017empirical}. Many researchers define patterns of \textbf{API co-occurrences} in the same scope of a program as an API specification. Works in this category find the frequency of co-appearance of APIs in the same context and use it to create API co-occurrence patterns. While most of the approaches in this category find such patterns within a method~\cite{li2005pr, zheng2011cross, Moritz2013, monperrus2013detecting, saied2015mining, saied2015could, thung2016api, nguyen2016api, xie2019hirec, niu2017api}, some go beyond and find patterns in a bigger scope (e.g. class or program)~\cite{lamba2015pravaaha, nguyen2019focus}. We have found these works useful for simple API recommendation or misuse detection tasks. However, they become impractical when the problem gets more complex as to accurately \textbf{(i)} identify an incorrect API \textit{order} in a code, or \textbf{(ii)} recommend the \textit{next} API based on the order of other APIs in a \textit{sequence}. To address the aforementioned issues, more sophisticated approaches find \textbf{API sequence} patterns in a code repository. This is an important specification needed for a correct API recommendation or misuse detection. The developed techniques in this category range from finding partial API usage patterns and creating rule-based specifications \cite{liu2006ltrules, acharya2007mining, wasylkowski2007detecting} to mining a complete sequence of API usage patterns~\cite{shoham2008static, zhong2009mapo, hsu2011macs, zhang2012automatic, wang2013mining, asaduzzaman2014cscc, dang2015api, saied2020towards,saied2018towards, fowkes2016parameter}. As an example, MAPO~\cite{zhong2009mapo}, one of the most respected API specification miners, aims to create patterns of API usage sequences and leverage that to find relevant code samples for programmers. Although sequential API specification miners take API order into account, they are not able to: \textbf{(i)} provide more API-related information in a program (e.g. data dependency) than the order of appearance in the code, and \textbf{(ii)} distinguish between two semantically equivalent sequences (\secref{sec:GRAAM}). \textbf{Graph-based API} pattern finders are the most advanced methods developed to cover sequence-based API pattern miners shortcomings and create more detailed API specifications (e.g. data dependency between APIs). Specifically, these works aim to track the usage of APIs related to a single object~\cite{Nguyen2009, nguyen2010graph, nguyen2012grapacc, ghafari2014towards, mover2018mining} or multiple objects~\cite{asaduzzaman2017recommending,asaduzzaman2017femir, pacheco2019mining, amann2019investigating, gu2019codekernel} in a specific scope in programs. For instance, GrouMiner~\cite{Nguyen2009}, a well-appreciated graph-based API pattern miner, finds relationships between APIs of the same type in a method. While the mentioned works present more detailed API specifications, they still: \textbf{(i)} do not track dependencies across different scopes (inter-procedural), \textbf{(ii)} can not represent the whole context of an API usage, and \textbf{(iii)} can not identify semantically equivalent, yet in different order, API usages in programs. \textsc{\textbf{ArCode}} performs an inter-procedural program analysis and infers a context-sensitive graph-based API specification for frameworks. This approach produces isomorphically the same graphs for API usages that have different sequences but are semantically equivalent. \begin{comment} In conclusion, we found that current research and developed techniques in the field of API usage mining are limited in terms of their scope, coverage and accuracy of the results. To be more precise, following are the gaps we found in the current works: \begin{itemize} \item No work modeled the whole specification of a framework \item Lack of considering the context of API usages \item Not considering semantically equivalent sub-sequences. \item Suffering from false positive and false negative issues while detecting API misuses or providing API recommendations. \end{itemize} \end{comment} \section{Training Phase: Inferring a Framework API Specification Model (FSpec)} \label{sec:ArCode} \textsc{ArCode} uses the repository of created GRAAMs to infer the Framework API Specification Model (FSpec). \subsection{Framework API Specification Model (FSpec)} \label{subsec:FSM} We use the collected sound GRAAMs to build a unified graph-based Framework API Specification Model (FSpec) which represents \textbf{correct} ways to use the framework. This model aims to (a) reflect only possible correct combinations of API calls, (b) to contain only paths that represent a correct framework's API call sequence, and (c) to create one representative for all the semantically equivalent API usages. \begin{figure} \centering \includegraphics[width=0.63\textwidth]{Images/Final_FSM.pdf} \caption{Built Framework API Specification Model (FSpec) from depicted GRAAMs in \figref{fig:CreatedGRAAMs}a and \figref{fig:CreatedGRAAMs}b} \label{fig:BuiltModel_1} \vspace{-6pt} \end{figure} \figref{fig:BuiltModel_1} shows a Framework API Specification model (FSpec) built from the GRAAMs shown in \figref{fig:CreatedGRAAMs}a and \figref{fig:CreatedGRAAMs}b. Similar to a GRAAM, an FSpec encompasses three types of nodes: \textit{start node}, \textit{end node}, and \textit{framework-related node}. An FSpec has the same edge type as a GRAAM, \textit{API order constraint} edge. This type of edge represents the strict orders of framework APIs one should follow to correctly incorporate that framework in a program. However, FSpec has a new label on each edge: \textit{frequency}. Frequency of a sub-graph of FSpec represents the number of times that the corresponding API usage was observed in the code repository of sound programs. For instance, all edges between the start node and \code{login()} node in \figref{fig:BuiltModel_1} are labeled with frequency of $2$. That means, there were two (semantically) equivalent API usages observed in the code repository that both \textbf{(i)} instantiated objects of \code{Subject} and \code{CallbackHandler}, \textbf{(ii)} used those objects to instantiate an object of \code{LoginContext}, and then, \textbf{(iii)} called \code{login()} method of \code{LoginContext}. After the \code{login()} node, however, the frequencies are changed to 1. It means that there was a program that has not used any other APIs of JAAS framework after \code{login()} method. In addition to that, the model shows that there was a program that continued calling framework APIs and had two more API calls. FSpec represents \textit{semantically equivalent} API usages in a single representation. This property shows the \textbf{generalizability} of \textsc{ArCode} in the sense that when it visits an instance of correct API usage in a program, a representative of all the semantically equivalent API usages to the originally visited one would be added to the FSpec under construction. \subsection{Inferring a FSpec Model from Sound GRAAMs} To infer a framework's API specification model (FSpec), \textsc{ArCode} finds mergeable parts of created \textit{sound} GRAAMs. We will define mergeable parts of GRAAMs later in this section. Through the inference process, if \textsc{ArCode} finds meargable part of a GRAAM similar to one that was previously added to the FSpec model, then, it increases the frequencies of the corresponding edges in FSpec. Otherwise, it adds the corresponding new nodes to the model and sets their edge frequency to 1. To guarantee that all paths from start to end nodes represents a correct framework usage, we have provided inference rules to identify \concept{Mergeable sub-GRAAMs}. Two sub-GRAAMs are mergeable if \textbf{(i)} both include the start node, and \textbf{(ii)} their corresponding sequences are \textit{semantically equivalent}. Assuming that there are two GRAAMs $g_{1}$ and $g_{2}$, we explain how the merging algorithm works such that $g_{2}$ merges into $g_{1}$. \begin{itemize}[leftmargin=*] \item We first identify all the mergeable sub-GRAAM pairs from $g_{1}$ and $g_{2}$; \item Amongst the identified merging candidates, the pair with the highest number of nodes is selected; \item The frequency of edges from $sub-g1$ increments by the frequency of corresponding edges from $sub-g2$; \item The remained parts of $g2$ which are not included in $sub-g2$ will be added to $g_1$; \item We repeat this process until there are no more mergeable sub-GRAAM pairs from $g_{1}$ and $g_{2}$. This process guarantees that in the end, no semantically equivalent sequences exists in the start node's children list. \end{itemize} To clarify this algorithm, there are three different parts in \figref{fig:middle_merge} that could be a candidate for merging purposes. The \textit{upper part} starts with the root (e.g. node $1$ from $g_1$ and node $5$ from $g_2$) of the graph and may (or may not) contain some successors of the root. The \textit{middle part} does not contain root nor any end nodes. The \textit{lower part} contains at least one end node and may (or may not) include predecessors of the end node. To merge two GRAAMs $g_1$ and $g_2$, the algorithm only considers their \textit{upper parts} to avoid the emergence of incorrect paths. \figref{fig:middle_merge} provides an example of this situation. Assume that $1 \rightarrow 2 \rightarrow 3 \rightarrow 4$ and $5 \rightarrow 2 \rightarrow 3 \rightarrow 6$ are two \textit{correct} API sequences. Upon merging $g_1$ and $g_2$ from their middle part, two \textit{incorrect} paths ($1 \rightarrow 2 \rightarrow 3 \rightarrow 6$ and $5 \rightarrow 2 \rightarrow 3 \rightarrow 4$) are appeared in the merged graph. \begin{figure} \centering \floatbox[{\capbeside\thisfloatsetup{capbesideposition={left,center},capbesidewidth=4cm}}]{figure}[\FBwidth] {\caption{Emergence of unexpected and unsound sequences by merging $g_{1}$ and $g_{2}$ from their middle parts}\label{fig:middle_merge}} {\includegraphics[height=38mm]{Images/MiddleMerge.pdf}} \end{figure} \section{Threats to Validity}\label{sec:Threats_to_Validity} \textsc{ArCode} aims to filter out incorrect API usages from a code repository and then, learn correct API usages from the remained programs. While the learnt framework API specification model (FSpec) does not include incorrect API usages, we can not claim that it covers all the possible correct API usages. Another notable point is that \textsc{ArCode} leverages conservative merging rules while creating an FSpec. Although it can guarantee that no incorrect API usage emerges in the final FSpec, it can affect the efficiency of the training phase as well as the size of the final FSpec adversely. Moreover, the Inter-framework Dependency (IFD) model introduced in this paper is created based on static analysis over the source code of the framework to find reader-writer roles of API methods inside that framework. However, some modern frameworks use dynamic features of object oriented languages (e.g. reflections) to implement the framework. In these cases, performing dynamic analysis alongside static analysis would result in capturing more accurate dependencies between APIs. Concerning the evaluation of \textsc{ArCode} provided in this paper, we used two popular Java based frameworks, JAAS and RMI. For generality purposes, conducting experiments with more frameworks would be advised. \section{Conclusion \& Future Work} \label{sec:conclusion} In this paper we introduced ArCode plugin, which is a tool that helps programmers achieve a better understanding of the current state of architectural concerns implementation in their program. It also facilitates finding and fixing implementation deviations. Although this tool provides very insightful fix recommendations, it is the programmer's responsibility to apply the suggested changes to correct the implementation. There might be a few interactions between the programmer and ArCode to make sure that the final code complies with a correct API usage. As of our future work, we aim to automate the process of performing fix recommendations in the program under development. In that regard, based on the selected recommendation, ArCode will automatically change the program. Then, it will re-analyze the code, re-generate program's API usage model and code summery, and populates a new list of recommendations. Also, future work direction includes automatically synthesizing the code from scratch based on the selected API usage by the programmer. \section{ArCode In Practice} \label{sec:InPractice} \begin{figure} \centering \includegraphics[width=.8\textwidth]{Images/SampleCode.pdf} \centering \caption{A program that intends to implement authentication tactic.} \label{fig:CodeSample} \end{figure} To showcase how ArCode works, we start with a program in which a programmer aims to implement Authentication tactic by incorporating APIs from JAAS framework. \figref{fig:CodeSample} shows this program. The start point of the program is \code{main(...)} method. First, an object of \code{JaasUser} is created at line 25. This is a class that programmer has developed and is expected to correctly implement authentication tactic. Except for \code{main(...)} method, \code{JaasUser} has 5 methods each of which are responsible for calling an API of JAAS framework to support the authentication process. Following lines 26 to 32, programmer first instantiates an object of \code{LoginContext} at line 9 using an instantiated object of \code{CallbackHandler} from line 4. Then, it supposed to call \code{login()} method of instantiated \code{LoginContext} at line 13. However, the programmer mistakenly has not implemented this part. Next, the \code{Subject} that supposed to be populated by calling \code{login()} method is printed in line 17. Here, since \code{login()} method is not called, then \code{loginContext.getSubject()} at line 17 will return null and so it does not print the desired output (i.e. a semantical error). Finally, calling \code{logout()} method at line 21 concludes the authentication process. This simple program demonstrates a possible case of API misuse when a programmer aims to implement architectural concerns. As APIs of JAAS framework are called in different methods, it would be hard for a programmer to correctly track API calls and their relationships. Specifically, tracking API usages in a program becomes a challenging and an error-prone task while working on a large-scale software. ArCode supports programmers with automatically tracing and summarizing these API usages and representing them as a graph-based API usage model. It also generates a summarized version of API usages as an executable Java code snippet. These summerizations help programmer better understand how architectural concerns are currently implemented in their program. \figref{fig:CodeSampleSummery} depicts the summerization (w.r.t. JAAS API) of the program shown in \figref{fig:CodeSample}. \begin{figure*} \centering \includegraphics[width=.8\textwidth]{Images/ArCodeRec.pdf} \centering \caption{Receiving recommendations from ArCode plugin in IntelliJ IDEA} \label{fig:ArCodeRec} \end{figure*} \begin{figure} \centering \begin{subfigure}[b]{0.8\textwidth} \centering \hspace{-1pt} \includegraphics[width=.8\textwidth]{Images/ProgramUnderDevelopment.pdf} \centering \end{subfigure}% \begin{subfigure}[b]{.9\textwidth} \centering \includegraphics[width=\textwidth, right]{Images/SampleCodeSummery-code.pdf} \end{subfigure} \caption{Summerized version of code snippet shown in \figref{fig:CodeSample} as a graph-based API usage model and a code snippet} \label{fig:CodeSampleSummery} \vspace{-6pt} \end{figure} Next, ArCode leverages the built Framework API Specification (FSpec) model to identify deviations from a correct implementation. In case that such a deviation is found, a list of recommendations will be generated for the programmer. \figref{fig:ArCodeRec} shows how ArCode plugin analyzes programmer's code, finds deviations from correct implementation, and provides recommendations. On the left side of this figure, a summarized version of the current implementation is shown as a graph-based API usage model as well as its related code snippet. On the right side, a possible way of fixing the found deviation is demonstrated by means of a graph-based API usage model and its corresponding code snippet. The programmer can navigate between the recommendation list through the items in the combo box. By selecting a new value from the combo box, the right panel will re-render the corresponding recommendation graph and code snippet. Values in the combo box represent the score of each recommendation. Scores are float numbers between 0 and 1. Recommendations with scores closer to 1 have more similarities to the current implementation. For programmers' convenient, scores in the range of [0.8, 1], [0.5, 0.8), [0.2, 0.5), and [0, 0.2) are colored as \textit{green}, \textit{blue}, \textit{orange}, and \textit{red} respectively. For instance, as shown in \figref{fig:ArCodeRec}, ArCode identifies that the programmer's current implementation deviates from a correct authentication implementation. Therefore, it provides a list of recommendations as a guidance on how to fix this problem. The highest score in the combo box of \figref{fig:ArCodeRec} is 0.88. It means that many parts of the program complies with a correct API usage. Nevertheless, there are some API misuses needed to be fixed. For instance, the recommended graph-based API usage model has an additional node, \code{LoginContext.login()}, compared to API usage model of the current implementation. Black dotted arrows represent data-dependencies between APIs. It means that programmer needs to call \code{login()} method of the instantiated \code{LoginContext} in the code. Green dotted arrows represent API call sequence constraints. It means that calling \code{login()} method must be placed in the code before the location that either \code{logout()} or \code{getSubject()} methods are called. Furthermore, on the lower right side of \figref{fig:ArCodeRec} an executable code snippet is displayed. Programmer can follow the code snippet to find a more comprehensive insight into the problem and its related fix recommendation. \section{Introduction} Nowadays program developers increasingly rely on Integrated Development Environments (IDEs) to accelerate the development pace, achieve better control over their projects, and implement programs that correctly follow the programming language syntax \cite{vihavainen2014novices, wu2020ggf}. These IDEs are supported and enhanced by enormous plugins and tools developed by experts to facilitate code implementations. IntelliJ IDEA\footnote{https://www.jetbrains.com/idea} is a leading IDE developed by JetBrains which comes with many features such as code completion, code navigation, and building projects \cite{intellij2011most}. Novice, as well as expert programmers receive many helpful fine-grained advice from these tools and plugins, mostly in a limited scope \cite{zayour2016qualitative, liu2020self}. For example, based on a partially written expression in a program, an auto-completion plugin would be able to leverage information obtained from the method context to provide some recommendations on how to complete the expression. These plugins make programmers’ life much easier, such that many program developers cannot write a simple program without them. While programmers benefit from plugins and tools provided by IDEs, there are some important concerns that have not been addressed by them. For instance, despite the advancements in programming languages and development environments, junior program developers still suffer from lack of proper comprehension of the program under development \cite{schroter2017comprehending, xia2017measuring, stapleton2020human, dias2020evaluating} including its architectural aspects \cite{galster2016makes}. Furthermore, they find it difficult to implement complicated usecases and architectural tactics from scratch \cite{harrison2007leveraging}. These tactics are mostly implemented by incorporating APIs of frameworks. Studies show that framework documentations are not well-prepared for junior programmers to learn how to implement different usecases by incorporating that framework in their code \cite{robillard2011field}. Moreover, some empirical studies show that programmers cannot rely on tutorials nor Q\&A posts to learn how to correctly incorporate these APIs for a tactic or usecase implementation \cite{baltes2019usage, fischer2017stack}. In these cases, even if a programmer receives fine-grained recommendations from the IDE, it would not be enough towards building a real-world functioning application. Achieving this level of knowledge and experience and applying it in designing and implementing a program is not a trivial task. Therefore, to support programmers in the mentioned scenarios, empowering IDEs with more sophisticated tools and plugins is crucial. In this paper, we introduce ArCode, a tool that helps programmers understand implemented architectural concerns in their programs, find possible incorrect implementations, and fixing them. To that extent, Arcode learns how to correctly leverage API of frameworks from two sources: \textbf{(i)} by analyzing frameworks' bytecode, and \textbf{(ii)} from a sample of programs incorporating API of frameworks of interest. It then performs static analysis on the under development program and creates a graph-based model of API usage in that program. In an interaction with the programmer, ArCode is capable of providing recommendations on how to fix possible API misuses. \section*{Acknowledgments} This work was partially funded by the US National Science Foundation (NSF) under grant number CCF-1943300, CNS-1816845 and CNS-1823246. \bibliographystyle{IEEEtran}
{'timestamp': '2021-03-12T02:26:42', 'yymm': '2103', 'arxiv_id': '2103.06735', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06735'}
arxiv
\section{Conclusion and Future Work} \label{sec:conclusion} In this paper, we investigated the interplay of size, language variant, and fine-tuning task type in Arabic pre-trained language models using carefully controlled experiments on a number of Arabic NLP tasks. Our results show that pre-training data and subtask data variant proximity is more important than pre-training data size. We confirm these results on existing models. We exploit this insight in defining an optimized system selection model for the studied tasks. We make all of our created models and fine-tuning code publicly available. In future work, we plan to explore other design decisions that may contribute to the fine-tuning performance, including vocabulary size, tokenization techniques, and additional data mixtures. We also plan to utilize {AnonBERT} models in a number of other Arabic NLP tasks, and integrate them in the open-source toolkit, CAMeL~Tools \cite{obeid-etal-2020-camel}. \section*{Acknowledgment} This research was supported with Cloud TPUs from Google’s TensorFlow Research Cloud (TFRC). This work was also carried out on the High Performance Computing resources at New York University Abu Dhabi. The first and second authors were supported by the New York University Abu Dhabi Global PhD Student Fellowship program. We thank Salam Khalifa, and Ossama Obeid for helpful discussions. We also thank the anonymous reviewers for their valuable comments. \section{Introduction} Pre-trained language models such as BERT~\cite{devlin2019bert} and RoBERTa~\cite{liu2019roberta} have shown significant success in a wide range of natural language processing (NLP) tasks in various languages. Arabic has benefited from extensive efforts in building dedicated pre-trained language models, achieving state-of-the-art results in a number of NLP tasks, across both Modern Standard Arabic (MSA) and Dialectal Arabic (DA)~\cite{antoun-etal-2020-arabert,abdulmageed2020arbert}. However, it is hard to compare these models to understand what contributes to their performances because of their different design decisions and hyperparameters, such as data size, language variant, tokenization, vocabulary size, number of training steps, and so forth. Practically, one may empirically choose the best performing pre-trained model by fine-tuning it on a particular task; however, it is still unclear why a particular model is performing better than another and what design choices are contributing to its performance. To answer this question, we pre-trained various language models as part of a controlled experiment where we vary pre-training data sizes and language variants while keeping other hyperparameters constant throughout pre-training. We started by scaling down MSA pre-training data size to measure its impact on performance in fine-tuning tasks. We then pre-trained three different variants of Arabic: MSA, DA, and classical Arabic (CA), as well as a mix of these three variants. We evaluate our models along with eight other recent Arabic pre-trained models across five different tasks covering all the language variants we study, namely, named entity recognition (NER), part-of-speech (POS) tagging, sentiment analysis, dialect identification, and poetry classification, spanning 12 datasets. Our contributions can be summarized as follows: \begin{itemize} \setlength{\itemsep}{0pt} \item We create and release eight Arabic pre-trained models, which we name AnonBERT, with different design decisions, including one (CAMeLBERT-Mix) that is trained on the largest dataset to date.\footnote{Our pre-trained models are available at \url{https://huggingface.co/CAMeL-Lab}, and the fine-tuning code and models are available at \url{https://github.com/CAMeL-Lab/CAMeLBERT}.} \item We investigate the interplay of data size, language variant, and fine-tuning task type through controlled experimentation. Our results show that variant proximity of pre-training data and task data is more important than pre-training data size. \item We exploit this insight in defining an optimized system selection model. \end{itemize} \input{02_TABLE_01_model_configurations} \section{Related Work} \label{sec:related} There have been several research efforts on Arabic pre-trained models achieving state-of-the-art results in a number of Arabic NLP tasks. One of the earliest efforts includes AraBERT~\cite{antoun-etal-2020-arabert}, where they pre-trained a monolingual BERT model using 24GB of Arabic text in the news domain. \newcite{safaya2020kuisail} pre-trained ArabicBERT using 95GB of text mainly from the Arabic portion of the OSCAR corpus. Based on ArabicBERT, \newcite{talafha2020multidialect} further pre-trained their model using 10 million tweets, which included dialectal data. \newcite{lan-etal-2020-empirical} released several English-Arabic bilingual models dubbed GigaBERTs, where they studied the effectiveness of cross-lingual transfer learning and code-switched pre-training using Wikipedia, Gigaword, and the OSCAR corpus. Most recently, \newcite{abdulmageed2020arbert} developed two models, ARBERT and MARBERT, pre-trained on a large collection of datasets in MSA and DA. They reported new state-of-the-art results on the majority of the datasets in their fine-tuning benchmark. Moreover, there have been various studies explaining why pre-trained language models perform well on downstream tasks either in monolingual \cite{hewitt-manning-2019-structural, jawahar-etal-2019-bert, liu-etal-2019-linguistic, tenney-etal-2019-bert, tenney2018what} or multilingual settings \cite{wu-dredze-2019-beto, chi-etal-2020-finding, kulmizev-etal-2020-neural, vulic-etal-2020-probing}. Most of these efforts leveraged probing techniques to explore the linguistic knowledge that is captured by pre-trained language models such as morphosyntactic and semantic knowledge. More recently, there have been additional efforts investigating the effects of pre-training data size and tokenization on the performance of pre-trained language models. \newcite{zhang2020need} showed that pre-training RoBERTa requires 10M to 100M words to learn representations that reliably encode most syntactic and semantic features. However, a much larger quantity of data is needed for the model to perform well on typical downstream NLU tasks. \newcite{rust2020good} empirically compared multilingual pre-trained language models to their monolingual counterparts on a set of nine typologically diverse languages. They showed that while the pre-training data size is an important factor, the designated tokenizer of each monolingual model plays an equally important role in the downstream performance. In this work, we primarily focus on understanding the behavior of pre-trained models against variables such as data sizes and language variants. We compare against eight existing models. We find that AraBERTv02 ($X_3$) is the best on average and it wins or ties for a win in six out of 12 subtasks. Our {CAMeLBERT-Star} model is second overall on average, and it wins or ties for a win in four out of 12 subtasks. Interestingly, these systems are complementary in their performance and between the two, they win or tie for a win in nine out of 12 subtasks. \section{Pre-training {AnonBERT}} \label{sec:pre-training} We describe the datasets and the procedure we use to pre-train our models. We use the original implementation released by Google for pre-training.\footnote{\url{https://github.com/google-research/bert}} \subsection{Data} \paragraph{MSA Training Data} For MSA, we use the Arabic Gigaword Fifth Edition \cite{Parker:2011:arabic}, Abu El-Khair Corpus \cite{elkhair201615}, OSIAN corpus \cite{zeroual-etal-2019-osian}, Arabic Wikipedia,\footnote{\url{https://archive.org/details/arwiki-20190201}} and the unshuffled version of the Arabic OSCAR corpus \cite{ortiz-suarez-etal-2020-monolingual}. \paragraph{DA Training Data} For DA, we collect a range of dialectal corpora: LDC97T19-CALLHOME Transcripts \cite{Gadalla:1997:callhome}; LDC2002T38-CALLHOME Supplement Transcripts \cite{ldc_callhome_ara_transcr_suppl_2002_t38}; LDC2005S08-Babylon Levantine Arabic Transcripts \cite{ldc_bab_arabic_2005_s08}; LDC2005S14-CTS Levantine Arabic Transcripts \cite{ldc_cts_levarabic_td_2005_s14}; LDC2006T07-Levantine Arabic Transcripts \cite{ldc_cts_lev_ara_td5_t_2006_t07}; LDC2006T15-Gulf Arabic Transcripts \cite{ldc_arb_gulf_cttr_2006_t15}; LDC2006T16-Iraqi Arabic Transcripts \cite{ldc_arb_iraq_cttr_2006_t16}; LDC2007T01-Levantine Arabic Transcripts \cite{ldc_arb_lev_cttr_2007_t01}; LDC2007T04-Fisher Levantine Arabic Transcripts \cite{ldc_la_cts_ann_2007_t04}; Arabic Online Commentary Dataset (AOC) \cite{Zaidan:2011:arabic}; LDC2012T09-English/Arabic Parallel text \cite{ldc_ara_dialect_eng_para_2012_t09}; Arabic Multi Dialect Text Corpora \cite{Almeman:2013:automatic}; A Multidialectal Parallel Corpus of Arabic \cite{Bouamor:2014:multidialectal}; Multi-Dialect, Multi-Genre Corpus of Informal Written Arabic \cite{Cotterell:2014:multi-dialect}; YouDACC \cite{Salama:2014:youdacc}; PADIC \cite{Meftouh:2015:machine}; Curras \cite{Jarrar:2016:curras}; WERd \cite{DBLP:conf/asru/AliN0R17}; LDC2017T07-BOLT Egyptian SMS \cite{ldc_bolt_sms_chat_ara_src_transliteration_2017_t07}; Shami \cite{kwaik2018shami}; SUAR \cite{Al-Twairesh:2018:suar}; Arap-Tweet \cite{Zaghouani:2018:araptweet}; Gumar \cite{khalifa2018gumar}; MADAR \cite{Bouamor:2018:madar}; Habibi \cite{elhaj2020habibi}; NADI \cite{mageed-etal-2020-nadi}; and QADI \cite{abdelali2020qadi}. \paragraph{CA Training Data} For CA, we use the OpenITI corpus (v1.2)~\cite{lorenz_nigst_2020_3891466}. \subsection{Pre-processing} After extracting the raw text from each corpus, we apply the following pre-processing. We first remove invalid characters and normalize white spaces using the utilities provided by the original BERT implementation. We also remove lines without any Arabic characters. We then remove diacritics and kashida using CAMeL~Tools~\cite{obeid-etal-2020-camel}. Finally, we split each line into sentences with a heuristic-based sentence segmenter. \subsection{Preparing Data for BERT Pre-training} We follow the original English BERT model's hyperparameters for pre-training. We train a WordPiece~\cite{schuster2012} tokenizer on the entire dataset (167 GB text) with a vocabulary size of 30,000 using Hugging~Face's tokenizers.\footnote{\url{https://github.com/huggingface/tokenizers}} We do not lowercase letters nor strip accents. We use whole word masking and a duplicate factor of 10. We set maximum predictions per sequence to 20 for the datasets with a maximum sequence length of 128 tokens and 80 for the datasets with a maximum sequence length of 512 tokens. \subsection{Pre-training Procedure} We use a Google Cloud TPU (v3-8) for model pre-training. We use a learning rate of 1e-4 with a warmup over the first 10,000 steps. We pre-trained our models with a batch size of 1,024 sequences with a maximum sequence length of 128 tokens for the first 900,000 steps. We then continued pre-training with a batch size of 256 sequences with a maximum sequence length of 512 tokens for another 100,000 steps. In total, we pre-trained our models for one million steps. Pre-training one model took approximately 4.5 days. \section{Fine-tuning Tasks} \label{sec:fine-tuning} We evaluate our pre-trained language models on five NLP tasks: NER, POS tagging, sentiment analysis, dialect identification, and poetry classification. Specifically, we fine-tune and evaluate the models using 12 datasets (corresponding to 12 subtasks). We used Hugging~Face's transformers~\cite{wolf2020huggingfaces} to fine-tune our {AnonBERT} models.\footnote{We used transformers v3.1.0 along with PyTorch v1.5.1} The fine-tuning was done by adding a fully connected linear layer to the last hidden state. \paragraph{Tasks and Variants} We selected the fine-tuning datasets and subtasks to represent multiple variants of Arabic by design. For some of the datasets, the variant is readily known. However, other datasets contain a lot of social media text where the dominant variant of Arabic is unknown. Therefore, we estimate the proportion of MSA sentences in each dataset by identifying whether the text is MSA or DA using the Corpus 6 dialect identification model in \newcite{salameh-etal-2018-fine} as implemented in CAMeL Tools~\cite{obeid-etal-2020-camel}. This technique does not model CA. Of course, none of the datasets was purely MSA or DA; however, based on known dataset variants, we observe that having about 40\% or fewer MSA labels strongly suggests that the dataset is dialectal (or a strong dialectal mix). Table~\ref{dataset} presents the number of labels, size, unit, variant, and MSA percentage for the datasets used in the subtasks. \subsection{Named Entity Recognition}\label{ner} \paragraph{Dataset} We fine-tuned our models on the publicly available Arabic NER Dataset ANERcorp ($\sim$150K words) \cite{Benajiba:2007:ANERcorp} which is in MSA and we followed the splits defined by~\newcite{obeid-etal-2020-camel}. We also kept the same IOB (inside, outside, beginning) tagging format defined in the dataset covering four classes: Location (LOC), Miscellaneous (MISC), Organization (ORG), and Person (PERS). \paragraph{Experimental Setup} During fine-tuning, we used the representation of the first sub-token as an input to the linear layer. All models were fine-tuned on a single GPU for 3 epochs with a learning rate of 5e-5, batch size of 32, and a maximum sequence length of 512. Since ANERcorp does not have a dev set, we used the last checkpoint after the fine-tuning is done to report results on the test set using the micro $F_1$ score. \subsection{Part-of-Speech Tagging} \paragraph{Dataset} We fine-tuned our models on three different POS tagging datasets: (1) the Penn Arabic Treebank (PATB)~\cite{Maamouri:2004:patb} which is in MSA and includes 32 POS tags; (2) the Egyptian Arabic Treebank (ARZATB)~\cite{Maamouri:2012:arz} which is in Egyptian (EGY) and includes 33 POS tags; and (3) the GUMAR corpus~\cite{khalifa2018gumar} which is in Gulf (GLF) and includes 35 POS tags. \paragraph{Experimental Setup} Similar to NER, we used the representation of the first sub-token as an input to the linear layer. Our models were fine-tuned on a single GPU for 10 epochs with a learning rate of 5e-5, batch size of 32, and a maximum sequence length of 512. We used the same hyperparameters for the fine-tuning across the three POS tagging datasets. After the fine-tuning, we used the best checkpoints based on the dev sets to report results on the test sets using the accuracy score. \subsection{Sentiment Analysis} \paragraph{Dataset} We used a combination of sentiment analysis datasets to fine-tune our models. The datasets are: (1) the Arabic Speech-Act and Sentiment Corpus of Tweets (ArSAS) \cite{ELMADANY18.22}; (2) the Arabic Sentiment Tweets Dataset (ASTD) \cite{nabil-etal-2015-astd}; (3) SemEval-2017 task 4-A benchmark dataset \cite{Rosenthal:2017:semeval-2017}; and (4) the Multi-Topic Corpus for Target-based Sentiment Analysis in Arabic Levantine Tweets (ArSenTD-Lev) \cite{baly2019arsentdlev}. We combined and preprocessed the datasets in a similar way to what was done by \newcite{AbuFarha:2019:mazajak} and \newcite{obeid-etal-2020-camel}. That is, we removed diacritics, URLs, and Twitter usernames from all the tweets. \paragraph{Experimental Setup} Our models were fine-tuned on ArSenTD-Lev and the train splits from SemEval, ASTD, and ArSAS (23,327 tweets) on a single GPU for 3 epochs with a learning rate of 3e-5, batch size of 32, and a maximum sequence length of 128. After the fine-tuning, we used the best checkpoint based on a single dev set from SemEval, ASTD, and ArSAS to report results on the test sets. We used the $F_{1}^{PN}$ score which was defined in the SemEval-2017 task 4-A; $F_{1}^{PN}$ is the macro $F_1$ score over the positive and negative classes only while neglecting the neutral class. \subsection{Dialect Identification} \paragraph{Dataset} We fine-tuned our models on four different dialect identification datasets: (1) MADAR Corpus 26 which includes 26 labels; (2) MADAR Corpus 6 which includes six labels; (3) MADAR Twitter Corpus~\cite{Bouamor:2018:madar,salameh-etal-2018-fine,bouamor2019madar} which includes 21 labels; and (4) NADI Country-level~\cite{mageed-etal-2020-nadi} which includes 21 labels. The datasets were preprocessed by removing diacritics, URLs, and Twitter usernames while maintaining the same train, dev, and test splits for each dataset. Moreover, we collated the tweets belonging to a particular user in the MADAR Twitter Corpus in groups of 5 before feeding them to the model. We refer to this preprocessed version as MADAR-Twitter-5 to avoid confusion with the publicly available original MADAR Twitter Corpus. \paragraph{Experimental Setup} Our models were fine-tuned for 10 epochs with a learning rate of 3e-5, batch size of 32, and a maximum sequence length of 128. After the fine-tuning, we used the best checkpoints based on the dev sets to report results on the test sets using the macro $F_1$ score. Moreover, for the MADAR-Twitter-5 evaluation, we took a voting approach. That is, each user in the dev and test sets is assigned to the most frequent predicted country label. In case of a tie, we always pick the most frequent predicted country label based on the training set. \subsection{Poetry Meter Classification} \paragraph{Dataset} We used the Arabic Poem Comprehensive Dataset (APCD)~\cite{yousef2019learning}, which is mostly in CA, to fine-tune our models to identify the meters of Arabic poems. The dataset contains around 1.8M poems and covers 23 meters. We preprocessed the dataset by removing diacritics from the poems and separated the halves of each verse by using the \texttt{[SEP]} token. We applied an 80/10/10 random split to create train, dev, and test sets respectively. \paragraph{Experimental Setup} We fine-tuned our models on a single GPU for 3 epochs with a learning rate of 3e-5, batch size of 32, and a maximum sequence length of 128. After the fine-tuning, we used the best checkpoint based on the dev set to report results on the test set using the macro $F_1$ score. \input{05_TABLE_03_msa_models} \section{Evaluation Results and Discussion} \label{sec:evaluation} We first present an experiment where we investigate the effect of pre-training data size. We then report on {AnonBERT} models pre-trained on MSA, DA, and CA data, in addition to a model that is pre-trained on a mixture of these variants. We then provide a comparison against publicly available models. \subsection{Models with Different Data Sizes} \label{datasize-analysis} To investigate the effect of pre-training data size on fine-tuning tasks, we pre-train MSA models in a controlled setting where we scale down the MSA pre-training size by a factor of two while keeping all other hyperparameters constant. We pre-train four {AnonBERT} models on MSA data as follows: MSA-1/2 (54GB, 6.3B words), MSA-1/4 (27GB, 3.1B words), MSA-1/8 (14GB, 1.5B words), and MSA-1/16 (6GB, 636M words). In Table \ref{table:msa-result}, we show the results on our fine-tuning subtasks. We observe that the full MSA model and the MSA-1/4 model are on average the highest performing systems, even though the MSA-1/4 model was pre-trained on a quarter of the full MSA data. The MSA-1/4 model wins or ties for a win in seven out of 12 subtasks, and it is also the best model on average in the DA and CA subtasks. We also observe that different subtasks have different patterns. For some subtasks, plateauing in performance happens rather early. For instance, the performance on Gumar (GLF) does not change even if we increase the size. Similarly, the difference in performance on PATB (MSA) is very small. For other subtasks, the improvement is not consistent with the size, as seen in SemEval. When we calculate the correlation between the performance and the pre-training data size, we note that ArSAS has a strong positive correlation of 0.96, however, MADAR-6 has a negative correlation of -0.62. In fact, the average of the correlation of each of the 12 experiments is 0.25, which is not a strong pattern correlating size with performance. These observations suggest that the size of pre-training data has limited and inconsistent effect on the fine-tuning performance. This is consistent with \newcite{micheli-etal-2020-importance}, where they concluded that pre-training data size does not show a strong monotonic relationship with fine-tuning performance in their controlled experiments on French corpora. \input{05_TABLE_04_main} \subsection{Models with Different Language Variants} \label{subsec:model_variant} Next, we explore the relationship between language variants in pre-training and fine-tuning datasets. \subsubsection{MSA, DA, and CA} \paragraph{Task Type Difference} We compare the behavior of three models pre-trained on MSA, DA, and CA data. From Table \ref{table:main}, we observe that the difference in performance (Max-Min) among {AnonBERT}'s MSA, DA, and CA models is 4.6\% on average, ranging from 0.2\% to 14.5\%. To study trends by task type, we compute the average performance difference across the subtasks for each task. NER is the most sensitive to the pre-trained model variant (14.5\%), followed by sentiment analysis (8.2\%), dialect identification (3.8\%), poetry classification (1.3\%), and POS tagging (0.7\%). This indicates the importance of optimal pairing of pre-trained models and fine-tuning tasks. On average the {CAMeLBERT-MSA} model performs best, and is the winner in 10 out of 12 subtasks. The following are the two exceptions: (a) the {CAMeLBERT-DA} model performs best in the highly dialectal MADAR-6 subtask; and (b) the {CAMeLBERT-CA} model outperforms other models in the poetry classification task, which is in classical Arabic. These two exceptions suggest that performance in fine-tuning tasks may be associated with the variant proximity of the pre-training data to fine-tuning data; although we also acknowledge that {CAMeLBERT-MSA}'s data is two times the size of {CAMeLBERT-DA}'s, and 18 times the size of {CAMeLBERT-CA}'s, which may give {CAMeLBERT-MSA} an advantage. \paragraph{OOV Effect} To further investigate the effect of variant proximity on performance, we compute the word out-of-vocabulary (OOV) rate of all fine-tuning test sets against the pre-training data, as a way to estimate their similarity.\footnote{We use a simple token as a unit, where we segment text with white space and punctuation.} Note that {CAMeLBERT-Mix}, where we concatenate MSA, DA, and CA pre-training data, has the lowest OOV rate by design. In Table \ref{table:main}, we show the OOV rates for each dataset. In all the cases, we obtain the best performance where the model has the lowest OOV rate. To better understand the relationship between fine-tuning performance and OOV rates, we assessed the correlation between model performance and OOV rates for each dataset. We found a strong negative correlation of -0.82 on average. Interestingly, the {CAMeLBERT-CA} model which was pre-trained only on 6 GB of data outperforms other models that are pre-trained on significantly larger data in the poetry classification task. It is also worth mentioning that the {CAMeLBERT-CA} model has the lowest OOV rate on the poetry dataset (0.9\%), while having access to approximately 18 times less data compared to the {{CAMeLBERT-MSA}} model (6GB vs 107GB). This again suggests that the variant proximity of pre-training data to fine-tuning data is more important than the size of pre-training data. \input{05_TABLE_05_all_models} \subsubsection{Mix of MSA, DA, and CA} To further study the interplay of language variants and pre-training data size, we pre-trained a model ({CAMeLBERT-Mix}) on the concatenation of the MSA, DA, and CA datasets. This is the largest dataset used to pre-train an Arabic language model to date. As shown in Table \ref{table:main}, the {CAMeLBERT-Mix} model improves over other models in three cases, all of which are dialectal, suggesting that the {CAMeLBERT-Mix} model does better in some dialectal context. However, we do not see an increase in performance in other cases when compared with the best performing model, although the size of the pre-training data and the variety of the data are increased. This suggests that having a wide language variety in pre-training data can be beneficial for DA subtasks, whereas variant proximity of pre-training data to fine-tuning data is important MSA and CA subtasks. \subsubsection{Selecting an Optimal Model} Taking these insights into consideration, one cannot help but consider the exciting possibility of a system-selection ensembling approach that can help users make decisions with reasonable expectations using what they know of their specific tasks. We outline here such a setup: the user has access to three versions of the models: {AnonBERT}'s CA, MSA, and Mix. If the task data is known a priori to be CA, then we select the {CAMeLBERT-CA} model; if the task data is known to be MSA, we select the {CAMeLBERT-MSA} model; otherwise, we use the {CAMeLBERT-Mix} model (for dialects, i.e.). We report on this model in Table \ref{table:main} and \ref{table:all_models} as {CAMeLBERT-Star}. It is noteworthy that this model is not the same as oracularly selecting the best performer among our four models (MSA, DA, CA, and Mix). In fact, it is lower in performance than such oracular system as the {CAMeLBERT-MSA} model performs better than {CAMeLBERT-Mix} model in NADI. We do not claim here that this is a foolproof method; however, it is an interesting candidate for {\it common wisdom} of the kind we are hoping to develop through this effort. \subsection{Comparison with Existing Models} Table~\ref{table:all_models} compares our work with other existing models. We do not use models that require morphological pre-tokenization to allow direct comparison, and also because existing tokenization systems are mostly focused on MSA or EGY \cite{Pasha:2014:madamira,Abdelali:2016:farasa,obeid-etal-2020-camel}. We are aware that design decisions such as vocabulary size and number of training steps are not the same across these eight existing pre-trained models, which might be a contributing factor to their varying performances. We plan to investigate the effects of such decisions in future work. \paragraph{Task Performance Complementarity} The best model on average is AraBERTv02 ($X_3$); it wins or ties for a win in six out of 12 subtasks (four MSA and two DA). Our {CAMeLBERT-Star} is second overall on average, and it wins or ties for a win in four out of 12 subtasks (three DA, one CA). Interestingly, the two systems are complementary in their performance and between the two they win or tie for a win in nine out of 12 subtasks. The three remaining subtasks are won by MARBERT ($X_7$) (NADI, DA), ARBERT ($X_8$) (ANERcorp, MSA; PATB, MSA), and GigaBERT ($X_6$) (PATB, MSA). In practice, such complementarity can be exploited by system developers to achieve higher overall performance. \paragraph{Size and Performance} Considering the data size and performance of the other pre-trained models ($X_1$ to $X_8$), we observe a similar trend to our {AnonBERT} models. AraBERTv02 ($X_3$) is the best on average, with only 77GB of pre-training data. AraBERTv01 ($X_2$) is the smallest (24GB); however, on average it outperforms other models pre-trained on much larger datasets, such as and ArabicBERT ($X_4$, 95GB) and multi-dialectal Arabic BERT ($X_5$, 95GB with 10M tweets). This confirms that pre-training data size may not be an important factor to fine-tuning performance, as we showed in Section~\ref{datasize-analysis}. \paragraph{Variant Proximity and Performance} When we examine the proximity in terms of language variants of the pre-training data and the fine-tuning data across the eight existing pre-trained models, we observe the following. First, the monolingual MSA models ($X_2$, $X_3$, $X_4$, $X_8$) are better performers than the mixed models ($X_5$, $X_7$) on average (78.5\% and 78.4\%, respectively).\footnote{The average over macro-average performances.} Second, the monolingual MSA models perform better than the mixed models in MSA subtasks on average (82.6\% and 82.1\%, respectively), while the mixed models perform better than the MSA models in DA subtasks on average (73.5\% and 73.9\%, respectively).\footnote{The average over variant-wise-average performances.} This result is consistent with our analysis of the {CAMeLBERT-Mix} and the {CAMeLBERT-MSA} models in Section~\ref{subsec:model_variant}, where we found that the {CAMeLBERT-Mix} model is the best choice for DA subtasks, whereas the {CAMeLBERT-MSA} model is the best in MSA subtasks. \paragraph{\it On MARBERT and ARBERT} In another study that compared models pre-trained on MSA alone or a mix of MSA and DA data, \newcite{abdulmageed2020arbert} reported that MARBERT ($X_7$, pre-trained on MSA-DA mix) is more powerful than ARBERT ($X_8$, pre-trained on MSA). In our study, we do replicate their specific relative performance in terms of macro-average in our experiments (78.9\% for MARBERT and 78.5\% for ARBERT). It is not clear why MARBERT and ARBERT do not exhibit similar trends as observed in the analysis of our own {AnonBERT} models and other existing models. This may be attributed to numerous factors such as the degree of MSA-DA mixture, genre, and the pre-training procedure details. It is also worth noting that the data used to pre-train our {CAMeLBERT-MSA} model is a subset of the data used to pre-train our {CAMeLBERT-Mix} model, whereas the pre-training data for MARBERT and ARBERT are derived from different data sources. \section{Credits} This document has been adapted by Steven Bethard, Ryan Cotterrell and Rui Yan from the instructions for earlier ACL and NAACL proceedings, including those for 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} \newcite{lorenz_nigst_2020_3891466} The following instructions are directed to authors of papers submitted to EACL 2021 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} EACL provides this description and accompanying style files at \begin{quote} \url{http://eacl2021.org/downloads/eacl2021-templates.zip} \end{quote} We strongly recommend the use of these style files, which have been appropriately tailored for the EACL 2021 proceedings. \paragraph{\LaTeX-specific details:} The templates include the \LaTeX2e{} source (\texttt{\small eacl2021.tex}), the \LaTeX2e{} style file used to format it (\texttt{\small eacl2021.sty}), an ACL bibliography style (\texttt{\small acl\_natbib.bst}), an example bibliography (\texttt{\small acl2020.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 EACL 2021. Authors of papers accepted for presentation at EACL 2021 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 EACL 2021 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 eacl2021.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|
{'timestamp': '2021-09-07T02:11:46', 'yymm': '2103', 'arxiv_id': '2103.06678', 'language': 'en', 'url': 'https://arxiv.org/abs/2103.06678'}
arxiv